test.cc 764 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828
  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(ClientTest, MoveConstructible) {
  305. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  306. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  307. }
  308. TEST(ClientTest, MoveAssignable) {
  309. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  310. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  311. }
  312. #ifdef _WIN32
  313. TEST(StartupTest, WSAStartup) {
  314. WSADATA wsaData;
  315. int ret = WSAStartup(0x0002, &wsaData);
  316. ASSERT_EQ(0, ret);
  317. }
  318. #endif
  319. TEST(DecodePathTest, PercentCharacter) {
  320. EXPECT_EQ(
  321. decode_path_component(
  322. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  323. U8("descrip=Gastos áéíóúñÑ 6"));
  324. }
  325. TEST(DecodePathTest, PercentCharacterNUL) {
  326. string expected;
  327. expected.push_back('x');
  328. expected.push_back('\0');
  329. expected.push_back('x');
  330. EXPECT_EQ(decode_path_component("x%00x"), expected);
  331. }
  332. TEST(DecodePathTest, UnicodeEncoding) {
  333. // %u0041 = 'A' (1-byte UTF-8)
  334. EXPECT_EQ("A", decode_path_component("%u0041"));
  335. // %u00E9 = 'é' (2-byte UTF-8)
  336. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  337. // %u3042 = 'あ' (3-byte UTF-8)
  338. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  339. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  340. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  341. // %uD800 = surrogate (invalid, silently dropped)
  342. EXPECT_EQ("", decode_path_component("%uD800"));
  343. }
  344. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  345. // A sign or whitespace inside the two-character escape window must not be
  346. // accepted as a valid percent-encoding; the sequence is passed through
  347. // literally, matching decode_uri_component / decode_path_component.
  348. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  349. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  350. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  351. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  352. // Well-formed escapes still decode.
  353. EXPECT_EQ("-", decode_query_component("%2D", false));
  354. EXPECT_EQ("A", decode_query_component("%41", false));
  355. }
  356. TEST(SanitizeFilenameTest, VariousPatterns) {
  357. // Path traversal
  358. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  359. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  360. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  361. // Normal and edge cases
  362. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  363. EXPECT_EQ("filename.txt",
  364. httplib::sanitize_filename("/path/to/filename.txt"));
  365. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  366. EXPECT_EQ("", httplib::sanitize_filename(".."));
  367. EXPECT_EQ("", httplib::sanitize_filename(""));
  368. // Null bytes stripped
  369. EXPECT_EQ("safe.txt",
  370. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  371. // Whitespace-only rejected
  372. EXPECT_EQ("", httplib::sanitize_filename(" "));
  373. }
  374. // Forward declaration (see the base64_encode note below): split builds move the
  375. // definition into httplib.cc, so re-declaring it here lets the test link.
  376. namespace httplib {
  377. namespace detail {
  378. bool is_chunked_transfer_encoding(const Headers &headers);
  379. } // namespace detail
  380. } // namespace httplib
  381. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  382. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  383. auto make = [](std::initializer_list<const char *> lines) {
  384. Headers h;
  385. for (auto te : lines) {
  386. if (te) { h.emplace("Transfer-Encoding", te); }
  387. }
  388. return h;
  389. };
  390. // Sole coding, matched case-insensitively.
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  392. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  393. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  394. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  395. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  396. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  397. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  398. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  399. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  400. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  401. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  403. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  404. // were received, into one list. Headers preserves that order, so the answer
  405. // is decided by the last coding of the last line and the order the lines
  406. // arrived in is significant.
  407. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  408. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  409. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  410. // The split can fall anywhere in the list.
  411. EXPECT_TRUE(
  412. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  413. EXPECT_FALSE(
  414. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  415. // A trailing line naming no coding leaves the list ending in nothing, so it
  416. // must not inherit the chunked from the line before it.
  417. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  418. }
  419. // Forward declaration: in split builds split.py strips `inline` and moves the
  420. // definition into httplib.cc, so detail::base64_encode is not visible from the
  421. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  422. // in both header-only and split builds.
  423. namespace httplib {
  424. namespace detail {
  425. std::string base64_encode(const std::string &in);
  426. } // namespace detail
  427. } // namespace httplib
  428. TEST(Base64EncodeTest, KnownAnswers) {
  429. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  430. // where the accumulator's top bit is already set before the next shift.
  431. EXPECT_EQ("", detail::base64_encode(""));
  432. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  433. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  434. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  435. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  436. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  437. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  438. // High bytes keep the top bit set across several rounds.
  439. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  440. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  441. }
  442. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  447. string reservedCharacters = ";,/?:@&=+$";
  448. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  449. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  450. }
  451. TEST(ClientQueryOrder, PreserveOrder) {
  452. // This test reproduces Issue #2259: client may reorder query parameters
  453. // when sending a GET request. The expected behavior is that the client
  454. // preserves the original query string order when the caller supplied it
  455. // as part of the path.
  456. Server svr;
  457. svr.Get("/", [&](const Request &req, Response &res) {
  458. // Echo back the raw target so the test can assert ordering
  459. res.set_content(req.target, "text/plain");
  460. });
  461. std::thread t{[&] { svr.listen(HOST, PORT); }};
  462. auto se = detail::scope_exit([&] {
  463. svr.stop();
  464. t.join();
  465. ASSERT_FALSE(svr.is_running());
  466. });
  467. svr.wait_until_ready();
  468. Client cli(HOST, PORT);
  469. ASSERT_TRUE(cli.is_valid());
  470. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  471. auto res = cli.Get(original);
  472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  473. // Expect the echoed target to exactly match the original path (order
  474. // preserved)
  475. EXPECT_EQ(res->body, original);
  476. }
  477. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  478. string chineseCharacters = U8("中国語");
  479. string russianCharacters = U8("дом");
  480. string brazilianCharacters = U8("óculos");
  481. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  482. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  483. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  484. "%D0%B4%D0%BE%D0%BC");
  485. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  486. }
  487. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  488. string unescapedCharacters = "-_.!~*'()";
  489. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  490. }
  491. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  492. string reservedCharacters = ";,/?:@&=+$";
  493. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  494. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  495. }
  496. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  497. string chineseCharacters = U8("中国語");
  498. string russianCharacters = U8("дом");
  499. string brazilianCharacters = U8("óculos");
  500. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  501. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  502. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  503. "%D0%B4%D0%BE%D0%BC");
  504. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  505. }
  506. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  507. // Issue #2082 use case: encoding path component with ampersand
  508. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  509. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  510. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  511. }
  512. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  513. string unescapedCharacters = "-_.!~*'()";
  514. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  515. }
  516. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  517. string reservedCharacters = ";,/?:@&=+$#";
  518. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  519. }
  520. TEST(EncodeUriTest, TestUTF8Characters) {
  521. string chineseCharacters = U8("中国語");
  522. string russianCharacters = U8("дом");
  523. string brazilianCharacters = U8("óculos");
  524. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  525. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  526. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  527. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  528. }
  529. TEST(EncodeUriTest, TestCompleteUri) {
  530. string uri =
  531. "https://example.com/path/to/resource?query=value&param=test#fragment";
  532. EXPECT_EQ(
  533. httplib::encode_uri(uri),
  534. "https://example.com/path/to/resource?query=value&param=test#fragment");
  535. }
  536. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  537. string uri =
  538. "https://example.com/path with spaces/file name.html?q=hello world";
  539. EXPECT_EQ(httplib::encode_uri(uri),
  540. "https://example.com/path%20with%20spaces/"
  541. "file%20name.html?q=hello%20world");
  542. }
  543. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  544. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  545. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  546. }
  547. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  548. string unescapedCharacters = "-_.!~*'()";
  549. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  550. }
  551. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  552. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  553. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  554. string encodedBrazilian = "%C3%B3culos";
  555. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  556. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  557. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  558. }
  559. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  560. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  561. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  562. "Piri Tommy Villiers - on & on");
  563. }
  564. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  565. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  566. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  567. }
  568. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  569. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  570. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  571. }
  572. TEST(DecodeUriTest, TestUTF8Characters) {
  573. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  574. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  575. string encodedBrazilian = "%C3%B3culos";
  576. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  577. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  578. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  579. }
  580. TEST(DecodeUriTest, TestCompleteUri) {
  581. string encodedUri = "https://example.com/path%20with%20spaces/"
  582. "file%20name.html?q=hello%20world";
  583. EXPECT_EQ(
  584. httplib::decode_uri(encodedUri),
  585. "https://example.com/path with spaces/file name.html?q=hello world");
  586. }
  587. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  588. string original =
  589. "https://example.com/path with spaces/file name.html?q=hello world";
  590. string encoded = httplib::encode_uri(original);
  591. string decoded = httplib::decode_uri(encoded);
  592. EXPECT_EQ(decoded, original);
  593. }
  594. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  595. // decode_uri is the inverse of encode_uri: an escaped reserved character
  596. // stays encoded so it is not promoted into a real delimiter, while
  597. // non-reserved escapes still decode (like JS decodeURI).
  598. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  599. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  600. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  601. "%3F%3A%40%26%3D%2B%24%2C%3B");
  602. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  603. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  604. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  605. "http://example.com/a%2Fb");
  606. // decode_uri_component still decodes the reserved character.
  607. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  608. }
  609. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  610. string original = "Piri Tommy Villiers - on & on";
  611. string encoded = httplib::encode_uri_component(original);
  612. string decoded = httplib::decode_uri_component(encoded);
  613. EXPECT_EQ(decoded, original);
  614. }
  615. TEST(TrimTests, TrimStringTests) {
  616. EXPECT_EQ("abc", detail::trim_copy("abc"));
  617. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  618. EXPECT_TRUE(detail::trim_copy("").empty());
  619. }
  620. TEST(AsciiTest, LocaleIndependentClassification) {
  621. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  622. // which consult the global C locale: std::isalnum(0xC5) can return true
  623. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  624. // helpers must classify every byte by the ASCII grammar alone.
  625. for (int i = 0; i < 256; i++) {
  626. auto c = static_cast<char>(i);
  627. auto is_digit = i >= '0' && i <= '9';
  628. auto is_upper = i >= 'A' && i <= 'Z';
  629. auto is_lower = i >= 'a' && i <= 'z';
  630. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  631. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  632. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  633. << "byte " << i;
  634. }
  635. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  636. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  637. // Non-ASCII bytes must be percent-encoded, never passed through as
  638. // alphanumeric.
  639. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  640. }
  641. TEST(FromCharsTest, Double) {
  642. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  643. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  644. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  645. auto parse = [](const std::string &s, double &v) {
  646. return detail::from_chars(s.data(), s.data() + s.size(), v);
  647. };
  648. double v = -1.0;
  649. // Representative quality values.
  650. EXPECT_EQ(parse("0", v).ec, std::errc{});
  651. EXPECT_DOUBLE_EQ(v, 0.0);
  652. EXPECT_EQ(parse("1", v).ec, std::errc{});
  653. EXPECT_DOUBLE_EQ(v, 1.0);
  654. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  655. EXPECT_DOUBLE_EQ(v, 0.8);
  656. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  657. EXPECT_DOUBLE_EQ(v, 0.001);
  658. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  659. EXPECT_DOUBLE_EQ(v, 1.0);
  660. // A missing integer or fractional part is tolerated.
  661. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  662. EXPECT_DOUBLE_EQ(v, 0.5);
  663. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  664. EXPECT_DOUBLE_EQ(v, 5.0);
  665. // Values outside [0, 1] still parse; the caller range-checks them.
  666. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  667. EXPECT_DOUBLE_EQ(v, 123.456);
  668. // Stops at the first byte that is not part of the number and reports where.
  669. std::string trailing = "0.9, text/html";
  670. auto r = parse(trailing, v);
  671. EXPECT_EQ(r.ec, std::errc{});
  672. EXPECT_DOUBLE_EQ(v, 0.9);
  673. EXPECT_EQ(*r.ptr, ',');
  674. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  675. // outright, and an 'e'/'E' simply ends the number.
  676. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  677. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  678. std::string exp_input = "1.5e3";
  679. r = parse(exp_input, v);
  680. EXPECT_EQ(r.ec, std::errc{});
  681. EXPECT_DOUBLE_EQ(v, 1.5);
  682. EXPECT_EQ(*r.ptr, 'e');
  683. // Invalid inputs.
  684. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  685. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  686. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  687. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  688. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  689. // Pathological but well-formed inputs must stay bounded (no overflow, no
  690. // out-of-bounds table access) and stay within [0, 1] for the caller.
  691. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  692. std::errc{});
  693. EXPECT_DOUBLE_EQ(v, 0.0);
  694. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  695. std::errc{});
  696. EXPECT_GE(v, 0.0);
  697. EXPECT_LE(v, 1.0);
  698. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  699. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  700. }
  701. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  702. // Simple case without quality values
  703. std::vector<std::string> result1;
  704. EXPECT_TRUE(detail::parse_accept_header(
  705. "text/html,application/json,text/plain", result1));
  706. EXPECT_EQ(result1.size(), 3U);
  707. EXPECT_EQ(result1[0], "text/html");
  708. EXPECT_EQ(result1[1], "application/json");
  709. EXPECT_EQ(result1[2], "text/plain");
  710. // With quality values
  711. std::vector<std::string> result2;
  712. EXPECT_TRUE(detail::parse_accept_header(
  713. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  714. EXPECT_EQ(result2.size(), 3U);
  715. EXPECT_EQ(result2[0], "application/json"); // highest q value
  716. EXPECT_EQ(result2[1], "text/html");
  717. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  718. }
  719. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  720. // Mixed with and without quality values
  721. std::vector<std::string> result;
  722. EXPECT_TRUE(detail::parse_accept_header(
  723. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  724. EXPECT_EQ(result.size(), 3U);
  725. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  726. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  727. EXPECT_EQ(result[2], "application/json"); // q=0.5
  728. }
  729. TEST(ParseAcceptHeaderTest, EdgeCases) {
  730. // Empty header
  731. std::vector<std::string> empty_result;
  732. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  733. EXPECT_TRUE(empty_result.empty());
  734. // Single type
  735. std::vector<std::string> single_result;
  736. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  737. EXPECT_EQ(single_result.size(), 1U);
  738. EXPECT_EQ(single_result[0], "application/json");
  739. // Wildcard types
  740. std::vector<std::string> wildcard_result;
  741. EXPECT_TRUE(detail::parse_accept_header(
  742. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  743. EXPECT_EQ(wildcard_result.size(), 3U);
  744. EXPECT_EQ(wildcard_result[0], "application/json");
  745. EXPECT_EQ(wildcard_result[1], "text/*");
  746. EXPECT_EQ(wildcard_result[2], "*/*");
  747. }
  748. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  749. // Common browser Accept header
  750. std::vector<std::string> browser_result;
  751. EXPECT_TRUE(
  752. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  753. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  754. browser_result));
  755. EXPECT_EQ(browser_result.size(), 6U);
  756. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  757. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  758. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  759. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  760. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  761. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  762. // API client header
  763. std::vector<std::string> api_result;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  766. api_result));
  767. EXPECT_EQ(api_result.size(), 3U);
  768. EXPECT_EQ(api_result[0], "application/json");
  769. EXPECT_EQ(api_result[1], "application/xml");
  770. EXPECT_EQ(api_result[2], "text/plain");
  771. }
  772. TEST(ParseAcceptHeaderTest, SpecialCases) {
  773. // Quality value with 3 decimal places
  774. std::vector<std::string> decimal_result;
  775. EXPECT_TRUE(detail::parse_accept_header(
  776. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  777. EXPECT_EQ(decimal_result.size(), 2U);
  778. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  779. EXPECT_EQ(decimal_result[1], "text/html");
  780. // Zero quality (should still be included but with lowest priority)
  781. std::vector<std::string> zero_q_result;
  782. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  783. zero_q_result));
  784. EXPECT_EQ(zero_q_result.size(), 2U);
  785. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  786. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  787. // No spaces around commas
  788. std::vector<std::string> no_space_result;
  789. EXPECT_TRUE(detail::parse_accept_header(
  790. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  791. no_space_result));
  792. EXPECT_EQ(no_space_result.size(), 3U);
  793. EXPECT_EQ(no_space_result[0], "text/html");
  794. EXPECT_EQ(no_space_result[1], "application/json");
  795. EXPECT_EQ(no_space_result[2], "text/plain");
  796. }
  797. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  798. // Quality values always use '.' as the decimal separator, so parsing must
  799. // not depend on the process locale. An embedding application may have
  800. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  801. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  802. std::string saved = cur ? cur : "C";
  803. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  804. "fr_FR.UTF-8"};
  805. bool switched = false;
  806. for (const auto loc : comma_locales) {
  807. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  808. std::localeconv()->decimal_point[0] == ',') {
  809. switched = true;
  810. break;
  811. }
  812. }
  813. if (!switched) {
  814. std::setlocale(LC_NUMERIC, saved.c_str());
  815. GTEST_SKIP() << "no comma-decimal locale available on this host";
  816. }
  817. // The higher-weighted type appears later in the list, so a correct parse
  818. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  819. // sensitive parse reads both weights as 0 and leaves the original order.
  820. std::vector<std::string> result;
  821. EXPECT_TRUE(detail::parse_accept_header(
  822. "application/json;q=0.1,text/html;q=0.9", result));
  823. ASSERT_EQ(result.size(), 2U);
  824. EXPECT_EQ(result[0], "text/html");
  825. EXPECT_EQ(result[1], "application/json");
  826. std::setlocale(LC_NUMERIC, saved.c_str());
  827. }
  828. TEST(ParseAcceptHeaderTest, InvalidCases) {
  829. std::vector<std::string> result;
  830. // Invalid quality value (> 1.0)
  831. EXPECT_FALSE(
  832. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  833. // Invalid quality value (< 0.0)
  834. EXPECT_FALSE(
  835. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  836. // Invalid quality value (not a number)
  837. EXPECT_FALSE(detail::parse_accept_header(
  838. "text/html;q=invalid,application/json", result));
  839. // Empty quality value
  840. EXPECT_FALSE(
  841. detail::parse_accept_header("text/html;q=,application/json", result));
  842. // Invalid media type format (no slash and not wildcard)
  843. EXPECT_FALSE(
  844. detail::parse_accept_header("invalidtype,application/json", result));
  845. // Empty media type
  846. result.clear();
  847. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  848. // Only commas
  849. result.clear();
  850. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  851. // Valid cases should still work
  852. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  853. EXPECT_EQ(result.size(), 1U);
  854. EXPECT_EQ(result[0], "*/*");
  855. EXPECT_TRUE(detail::parse_accept_header("*", result));
  856. EXPECT_EQ(result.size(), 1U);
  857. EXPECT_EQ(result[0], "*");
  858. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  859. EXPECT_EQ(result.size(), 1U);
  860. EXPECT_EQ(result[0], "text/*");
  861. }
  862. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  863. Server svr;
  864. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  865. EXPECT_EQ(req.accept_content_types.size(), 3U);
  866. EXPECT_EQ(req.accept_content_types[0], "application/json");
  867. EXPECT_EQ(req.accept_content_types[1], "text/html");
  868. EXPECT_EQ(req.accept_content_types[2], "*/*");
  869. res.set_content("ok", "text/plain");
  870. });
  871. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  872. EXPECT_TRUE(false);
  873. res.set_content("bad request", "text/plain");
  874. });
  875. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  876. auto se = detail::scope_exit([&] {
  877. svr.stop();
  878. listen_thread.join();
  879. ASSERT_FALSE(svr.is_running());
  880. });
  881. svr.wait_until_ready();
  882. Client cli("localhost", PORT);
  883. {
  884. auto res = cli.Get(
  885. "/accept_ok",
  886. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  888. EXPECT_EQ(StatusCode::OK_200, res->status);
  889. }
  890. {
  891. auto res = cli.Get("/accept_bad_request",
  892. Headers{{"Accept", "text/html;q=abc,application/json"}});
  893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  894. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  895. }
  896. }
  897. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  898. Server svr;
  899. svr.Get("/", [](const Request & /*req*/, Response &res) {
  900. res.set_content("ok", "text/plain");
  901. });
  902. std::atomic<int> start_count{0};
  903. std::atomic<bool> running_when_called{false};
  904. svr.set_start_handler([&]() {
  905. running_when_called = svr.is_running();
  906. start_count++;
  907. });
  908. auto port = svr.bind_to_any_port(HOST);
  909. std::thread t([&]() { svr.listen_after_bind(); });
  910. auto se = detail::scope_exit([&] {
  911. svr.stop();
  912. t.join();
  913. ASSERT_FALSE(svr.is_running());
  914. });
  915. svr.wait_until_ready();
  916. // A successful request proves the accept loop is running, which the start
  917. // handler precedes; so by now the handler must have run exactly once.
  918. Client cli(HOST, port);
  919. cli.set_connection_timeout(std::chrono::seconds(5));
  920. auto res = cli.Get("/");
  921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  922. EXPECT_EQ(StatusCode::OK_200, res->status);
  923. EXPECT_EQ(1, start_count.load());
  924. EXPECT_TRUE(running_when_called.load());
  925. }
  926. TEST(DivideTest, DivideStringTests) {
  927. auto divide = [](const std::string &str, char d) {
  928. std::string lhs;
  929. std::string rhs;
  930. detail::divide(str, d,
  931. [&](const char *lhs_data, std::size_t lhs_size,
  932. const char *rhs_data, std::size_t rhs_size) {
  933. lhs.assign(lhs_data, lhs_size);
  934. rhs.assign(rhs_data, rhs_size);
  935. });
  936. return std::make_pair(std::move(lhs), std::move(rhs));
  937. };
  938. {
  939. const auto res = divide("", '=');
  940. EXPECT_EQ(res.first, "");
  941. EXPECT_EQ(res.second, "");
  942. }
  943. {
  944. const auto res = divide("=", '=');
  945. EXPECT_EQ(res.first, "");
  946. EXPECT_EQ(res.second, "");
  947. }
  948. {
  949. const auto res = divide(" ", '=');
  950. EXPECT_EQ(res.first, " ");
  951. EXPECT_EQ(res.second, "");
  952. }
  953. {
  954. const auto res = divide("a", '=');
  955. EXPECT_EQ(res.first, "a");
  956. EXPECT_EQ(res.second, "");
  957. }
  958. {
  959. const auto res = divide("a=", '=');
  960. EXPECT_EQ(res.first, "a");
  961. EXPECT_EQ(res.second, "");
  962. }
  963. {
  964. const auto res = divide("=b", '=');
  965. EXPECT_EQ(res.first, "");
  966. EXPECT_EQ(res.second, "b");
  967. }
  968. {
  969. const auto res = divide("a=b", '=');
  970. EXPECT_EQ(res.first, "a");
  971. EXPECT_EQ(res.second, "b");
  972. }
  973. {
  974. const auto res = divide("a=b=", '=');
  975. EXPECT_EQ(res.first, "a");
  976. EXPECT_EQ(res.second, "b=");
  977. }
  978. {
  979. const auto res = divide("a=b=c", '=');
  980. EXPECT_EQ(res.first, "a");
  981. EXPECT_EQ(res.second, "b=c");
  982. }
  983. }
  984. TEST(SplitTest, ParseQueryString) {
  985. string s = "key1=val1&key2=val2&key3=val3";
  986. Params dic;
  987. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  988. [&](const char *b, const char *e) {
  989. string key, val;
  990. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  991. if (key.empty()) {
  992. key.assign(b2, e2);
  993. } else {
  994. val.assign(b2, e2);
  995. }
  996. });
  997. dic.emplace(key, val);
  998. });
  999. EXPECT_EQ("val1", dic.find("key1")->second);
  1000. EXPECT_EQ("val2", dic.find("key2")->second);
  1001. EXPECT_EQ("val3", dic.find("key3")->second);
  1002. }
  1003. TEST(SplitTest, ParseInvalidQueryTests) {
  1004. {
  1005. string s = " ";
  1006. Params dict;
  1007. detail::parse_query_text(s, dict);
  1008. EXPECT_TRUE(dict.empty());
  1009. }
  1010. {
  1011. string s = " = =";
  1012. Params dict;
  1013. detail::parse_query_text(s, dict);
  1014. EXPECT_TRUE(dict.empty());
  1015. }
  1016. }
  1017. TEST(ParseQueryTest, ParseQueryString) {
  1018. {
  1019. std::string s = "key1=val1&key2=val2&key3=val3";
  1020. Params dic;
  1021. detail::parse_query_text(s, dic);
  1022. EXPECT_EQ("val1", dic.find("key1")->second);
  1023. EXPECT_EQ("val2", dic.find("key2")->second);
  1024. EXPECT_EQ("val3", dic.find("key3")->second);
  1025. }
  1026. {
  1027. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1028. Params dic;
  1029. detail::parse_query_text(s, dic);
  1030. EXPECT_EQ("", dic.find("key1")->second);
  1031. EXPECT_EQ("val1", dic.find("key2")->second);
  1032. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1033. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1034. }
  1035. }
  1036. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1037. Params dic;
  1038. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1039. dic.emplace("key1", "val1");
  1040. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1041. dic.emplace("key2", "val2");
  1042. dic.emplace("key3", "val3");
  1043. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1044. }
  1045. // Joins every entry of a Headers or Params into "key=value " so a whole
  1046. // traversal can be compared in one assertion. Both are instantiations of the
  1047. // same insertion-ordered container, so one helper serves both.
  1048. template <typename Map> static std::string entries_to_string(const Map &m) {
  1049. std::string s;
  1050. for (const auto &entry : m) {
  1051. s += entry.first + "=" + entry.second + " ";
  1052. }
  1053. return s;
  1054. }
  1055. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1056. // Params used to be a std::multimap, which sorted by name and handed the
  1057. // caller's query back alphabetised. A client signing its query string could
  1058. // not reproduce the order it asked for.
  1059. Params dic;
  1060. dic.emplace("zulu", "1");
  1061. dic.emplace("alpha", "2");
  1062. dic.emplace("mike", "3");
  1063. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1064. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1065. }
  1066. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1067. Params dic;
  1068. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1069. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1070. }
  1071. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1072. Request req;
  1073. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1074. req.params);
  1075. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1076. EXPECT_EQ("first", req.get_param_value("tag"));
  1077. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1078. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1079. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1080. EXPECT_EQ("", req.get_param_value("tag", 3));
  1081. }
  1082. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1083. // Params shares its container with Headers, which matches field names
  1084. // case-insensitively. Parameter names must not pick that up.
  1085. Params dic;
  1086. dic.emplace("Key", "upper");
  1087. dic.emplace("key", "lower");
  1088. EXPECT_EQ(2U, dic.size());
  1089. EXPECT_EQ(1U, dic.count("Key"));
  1090. EXPECT_EQ(1U, dic.count("key"));
  1091. EXPECT_EQ("upper", dic.find("Key")->second);
  1092. EXPECT_EQ("lower", dic.find("key")->second);
  1093. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1094. }
  1095. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1096. Server svr;
  1097. std::string order;
  1098. svr.Get("/order", [&](const Request &req, Response &res) {
  1099. order = entries_to_string(req.params);
  1100. res.set_content("ok", "text/plain");
  1101. });
  1102. auto port = svr.bind_to_any_port(HOST);
  1103. thread t = thread([&] { svr.listen_after_bind(); });
  1104. auto se = detail::scope_exit([&] {
  1105. svr.stop();
  1106. t.join();
  1107. ASSERT_FALSE(svr.is_running());
  1108. });
  1109. svr.wait_until_ready();
  1110. Client cli(HOST, port);
  1111. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1112. ASSERT_TRUE(res);
  1113. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1114. }
  1115. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1116. Server svr;
  1117. std::string field_order, file_order;
  1118. svr.Post("/order", [&](const Request &req, Response &res) {
  1119. for (const auto &field : req.form.fields) {
  1120. field_order += field.first + "=" + field.second.content + " ";
  1121. }
  1122. for (const auto &file : req.form.files) {
  1123. file_order += file.first + "=" + file.second.filename + " ";
  1124. }
  1125. res.set_content("ok", "text/plain");
  1126. });
  1127. auto port = svr.bind_to_any_port(HOST);
  1128. thread t = thread([&] { svr.listen_after_bind(); });
  1129. auto se = detail::scope_exit([&] {
  1130. svr.stop();
  1131. t.join();
  1132. ASSERT_FALSE(svr.is_running());
  1133. });
  1134. svr.wait_until_ready();
  1135. UploadFormDataItems items = {
  1136. {"zulu", "1", "", ""},
  1137. {"alpha", "2", "", ""},
  1138. {"mike", "3", "", ""},
  1139. {"zebra", "z", "z.txt", "text/plain"},
  1140. {"apple", "a", "a.txt", "text/plain"},
  1141. };
  1142. Client cli(HOST, port);
  1143. auto res = cli.Post("/order", items);
  1144. ASSERT_TRUE(res);
  1145. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1146. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1147. }
  1148. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1149. Server svr;
  1150. std::vector<std::string> values;
  1151. std::string first, second, out_of_range, order;
  1152. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1153. values = req.form.get_fields("tag");
  1154. first = req.form.get_field("tag", 0);
  1155. second = req.form.get_field("tag", 1);
  1156. out_of_range = req.form.get_field("tag", 2);
  1157. for (const auto &field : req.form.fields) {
  1158. order += field.first + "=" + field.second.content + " ";
  1159. }
  1160. res.set_content("ok", "text/plain");
  1161. });
  1162. auto port = svr.bind_to_any_port(HOST);
  1163. thread t = thread([&] { svr.listen_after_bind(); });
  1164. auto se = detail::scope_exit([&] {
  1165. svr.stop();
  1166. t.join();
  1167. ASSERT_FALSE(svr.is_running());
  1168. });
  1169. svr.wait_until_ready();
  1170. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1171. // not adjacent in the container.
  1172. UploadFormDataItems items = {
  1173. {"tag", "first", "", ""},
  1174. {"other", "x", "", ""},
  1175. {"tag", "second", "", ""},
  1176. };
  1177. Client cli(HOST, port);
  1178. auto res = cli.Post("/repeated", items);
  1179. ASSERT_TRUE(res);
  1180. ASSERT_EQ(2U, values.size());
  1181. EXPECT_EQ("first", values[0]);
  1182. EXPECT_EQ("second", values[1]);
  1183. EXPECT_EQ("first", first);
  1184. EXPECT_EQ("second", second);
  1185. // std::multimap already kept entries sharing a name in insertion order, so
  1186. // everything above passes without this change too. The whole traversal is
  1187. // what tells the two apart: sorting by name would hoist "other" to the front
  1188. // and the two "tag" parts would end up adjacent.
  1189. EXPECT_EQ("tag=first other=x tag=second ", order);
  1190. // Advancing past the last entry of a name used to run off the container;
  1191. // the container's saturating increment makes it return the default instead.
  1192. EXPECT_EQ("", out_of_range);
  1193. }
  1194. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1195. // Server::read_content() keeps a FormFields::iterator alive across the
  1196. // content callbacks that fill the part it points at. The container is
  1197. // vector-backed, so a later emplace can reallocate and invalidate an older
  1198. // iterator; 64 parts grow the vector through seven reallocations, which
  1199. // checks that every part's content still lands in its own entry.
  1200. const size_t part_count = 64;
  1201. // One formula for both the parts sent and the values expected back, so the
  1202. // two cannot drift apart.
  1203. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1204. auto content_of = [](size_t i) {
  1205. return std::string(64, static_cast<char>('a' + (i % 26)));
  1206. };
  1207. Server svr;
  1208. std::vector<std::pair<std::string, std::string>> received;
  1209. svr.Post("/many", [&](const Request &req, Response &res) {
  1210. for (const auto &field : req.form.fields) {
  1211. received.emplace_back(field.first, field.second.content);
  1212. }
  1213. res.set_content("ok", "text/plain");
  1214. });
  1215. auto port = svr.bind_to_any_port(HOST);
  1216. thread t = thread([&] { svr.listen_after_bind(); });
  1217. auto se = detail::scope_exit([&] {
  1218. svr.stop();
  1219. t.join();
  1220. ASSERT_FALSE(svr.is_running());
  1221. });
  1222. svr.wait_until_ready();
  1223. UploadFormDataItems items;
  1224. for (size_t i = 0; i < part_count; i++) {
  1225. items.push_back({name_of(i), content_of(i), "", ""});
  1226. }
  1227. Client cli(HOST, port);
  1228. auto res = cli.Post("/many", items);
  1229. ASSERT_TRUE(res);
  1230. ASSERT_EQ(part_count, received.size());
  1231. for (size_t i = 0; i < part_count; i++) {
  1232. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1233. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1234. }
  1235. }
  1236. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1237. string content_type = "multipart/form-data; boundary=something";
  1238. string boundary;
  1239. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1240. EXPECT_TRUE(ret);
  1241. EXPECT_EQ(boundary, "something");
  1242. }
  1243. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1244. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1245. string boundary;
  1246. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1247. EXPECT_TRUE(ret);
  1248. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1249. }
  1250. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1251. string content_type =
  1252. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1253. string boundary;
  1254. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1255. EXPECT_TRUE(ret);
  1256. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1257. }
  1258. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1259. string content_type =
  1260. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1261. string boundary;
  1262. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1263. EXPECT_TRUE(ret);
  1264. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1265. }
  1266. TEST(GetHeaderValueTest, DefaultValue) {
  1267. Headers headers = {{"Dummy", "Dummy"}};
  1268. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1269. EXPECT_STREQ("text/plain", val);
  1270. }
  1271. TEST(GetHeaderValueTest, DefaultValueInt) {
  1272. Headers headers = {{"Dummy", "Dummy"}};
  1273. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1274. EXPECT_EQ(100ull, val);
  1275. }
  1276. TEST(GetHeaderValueTest, RegularValue) {
  1277. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1278. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1279. EXPECT_STREQ("text/html", val);
  1280. }
  1281. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1282. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1283. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1284. EXPECT_STREQ("text/html", val);
  1285. }
  1286. TEST(GetHeaderValueTest, SetContent) {
  1287. Response res;
  1288. res.set_content("html", "text/html");
  1289. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1290. res.set_content("text", "text/plain");
  1291. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1292. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1293. }
  1294. TEST(GetHeaderValueTest, RegularValueInt) {
  1295. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1296. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1297. EXPECT_EQ(100ull, val);
  1298. }
  1299. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1300. Headers headers = {{"Content-Length", "x"}};
  1301. auto is_invalid_value = false;
  1302. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1303. is_invalid_value);
  1304. EXPECT_EQ(0ull, val);
  1305. EXPECT_TRUE(is_invalid_value);
  1306. }
  1307. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1308. // An all-digit value that overflows size_t must be reported as invalid, not
  1309. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1310. // a large length to a small one on 32-bit builds, leaving the framing length
  1311. // wrong while is_invalid_value stayed false.
  1312. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1313. auto is_invalid_value = false;
  1314. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1315. is_invalid_value);
  1316. EXPECT_TRUE(is_invalid_value);
  1317. // A well-formed length is unaffected.
  1318. Headers ok = {{"Content-Length", "1234"}};
  1319. is_invalid_value = false;
  1320. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1321. is_invalid_value);
  1322. EXPECT_EQ(1234ull, val);
  1323. EXPECT_FALSE(is_invalid_value);
  1324. }
  1325. TEST(GetHeaderValueTest, Range) {
  1326. {
  1327. Headers headers = {make_range_header({{1, -1}})};
  1328. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1329. EXPECT_STREQ("bytes=1-", val);
  1330. }
  1331. {
  1332. Headers headers = {make_range_header({{-1, 1}})};
  1333. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1334. EXPECT_STREQ("bytes=-1", val);
  1335. }
  1336. {
  1337. Headers headers = {make_range_header({{1, 10}})};
  1338. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1339. EXPECT_STREQ("bytes=1-10", val);
  1340. }
  1341. {
  1342. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1343. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1344. EXPECT_STREQ("bytes=1-10, 100-", val);
  1345. }
  1346. {
  1347. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1348. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1349. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1350. }
  1351. {
  1352. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1353. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1354. EXPECT_STREQ("bytes=0-0, -1", val);
  1355. }
  1356. }
  1357. TEST(BearerTokenAuthTest, SchemeValidation) {
  1358. // A value shorter than "Bearer " must not throw from the fixed-length
  1359. // substr, and a non-Bearer scheme must not be reported as a token.
  1360. struct {
  1361. const char *value;
  1362. const char *expected;
  1363. } cases[] = {
  1364. {"x", ""},
  1365. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1366. {"Bearer abc123", "abc123"},
  1367. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1368. };
  1369. for (const auto &c : cases) {
  1370. Request req;
  1371. req.set_header("Authorization", c.value);
  1372. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1373. }
  1374. }
  1375. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1376. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1377. // to depend on the standard library (libstdc++ handed back duplicates in
  1378. // reverse insertion order, libc++ in insertion order).
  1379. Request req;
  1380. req.set_header("Accept-Encoding", "gzip");
  1381. req.set_header("Accept-Encoding", "deflate");
  1382. req.set_header("Accept-Encoding", "br");
  1383. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1384. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1385. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1386. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1387. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1388. }
  1389. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1390. Request req;
  1391. req.set_header("X-Test", "only");
  1392. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1393. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1394. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1395. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1396. }
  1397. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1398. Headers headers;
  1399. headers.emplace("Host", "example.com");
  1400. headers.emplace("Accept-Encoding", "gzip");
  1401. headers.emplace("User-Agent", "test");
  1402. headers.emplace("Accept-Encoding", "deflate");
  1403. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1404. "Accept-Encoding=deflate ",
  1405. entries_to_string(headers));
  1406. }
  1407. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1408. Headers headers = {{"Content-Type", "text/html"},
  1409. {"CONTENT-TYPE", "text/xml"}};
  1410. EXPECT_EQ(2U, headers.count("content-type"));
  1411. auto it = headers.find("content-type");
  1412. ASSERT_TRUE(it != headers.end());
  1413. EXPECT_EQ("text/html", it->second);
  1414. }
  1415. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1416. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1417. // drop only those fields and leave everything positioned between them.
  1418. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1419. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1420. auto rng = headers.equal_range("a");
  1421. headers.erase(rng.first, rng.second);
  1422. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1423. }
  1424. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1425. Headers headers = {
  1426. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1427. EXPECT_EQ(3U, headers.erase("A"));
  1428. EXPECT_EQ(0U, headers.count("A"));
  1429. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1430. }
  1431. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1432. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1433. headers.emplace_front("Host", "example.com");
  1434. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1435. entries_to_string(headers));
  1436. }
  1437. TEST(ParseHeaderValueTest, Range) {
  1438. {
  1439. Ranges ranges;
  1440. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1441. EXPECT_TRUE(ret);
  1442. EXPECT_EQ(1u, ranges.size());
  1443. EXPECT_EQ(1u, ranges[0].first);
  1444. EXPECT_EQ(-1, ranges[0].second);
  1445. }
  1446. {
  1447. Ranges ranges;
  1448. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1449. EXPECT_TRUE(ret);
  1450. EXPECT_EQ(1u, ranges.size());
  1451. EXPECT_EQ(-1, ranges[0].first);
  1452. EXPECT_EQ(1u, ranges[0].second);
  1453. }
  1454. {
  1455. Ranges ranges;
  1456. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1457. EXPECT_TRUE(ret);
  1458. EXPECT_EQ(1u, ranges.size());
  1459. EXPECT_EQ(1u, ranges[0].first);
  1460. EXPECT_EQ(10u, ranges[0].second);
  1461. }
  1462. {
  1463. Ranges ranges;
  1464. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1465. EXPECT_FALSE(ret);
  1466. }
  1467. {
  1468. Ranges ranges;
  1469. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1470. EXPECT_TRUE(ret);
  1471. EXPECT_EQ(2u, ranges.size());
  1472. EXPECT_EQ(1u, ranges[0].first);
  1473. EXPECT_EQ(10u, ranges[0].second);
  1474. EXPECT_EQ(100u, ranges[1].first);
  1475. EXPECT_EQ(-1, ranges[1].second);
  1476. }
  1477. {
  1478. Ranges ranges;
  1479. auto ret =
  1480. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1481. EXPECT_TRUE(ret);
  1482. EXPECT_EQ(3u, ranges.size());
  1483. EXPECT_EQ(1u, ranges[0].first);
  1484. EXPECT_EQ(10u, ranges[0].second);
  1485. EXPECT_EQ(100u, ranges[1].first);
  1486. EXPECT_EQ(200u, ranges[1].second);
  1487. EXPECT_EQ(300u, ranges[2].first);
  1488. EXPECT_EQ(400u, ranges[2].second);
  1489. }
  1490. {
  1491. Ranges ranges;
  1492. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1493. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1494. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1495. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1496. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1497. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1498. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1499. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1500. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1501. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1502. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1503. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1504. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1505. EXPECT_TRUE(ranges.empty());
  1506. }
  1507. }
  1508. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1509. Request req;
  1510. req.set_header("Accept-Encoding", "gzip");
  1511. Response res;
  1512. res.set_header("Content-Type", "text/plain");
  1513. auto ret = detail::encoding_type(req, res);
  1514. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1515. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1516. #else
  1517. EXPECT_TRUE(ret == detail::EncodingType::None);
  1518. #endif
  1519. }
  1520. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1521. Request req;
  1522. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1523. Response res;
  1524. res.set_header("Content-Type", "text/plain");
  1525. auto ret = detail::encoding_type(req, res);
  1526. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1527. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1528. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1529. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1530. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1531. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1532. #else
  1533. EXPECT_TRUE(ret == detail::EncodingType::None);
  1534. #endif
  1535. }
  1536. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1537. Request req;
  1538. req.set_header("Accept-Encoding",
  1539. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1540. Response res;
  1541. res.set_header("Content-Type", "text/plain");
  1542. auto ret = detail::encoding_type(req, res);
  1543. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1544. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1545. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1546. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1547. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1548. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1549. #else
  1550. EXPECT_TRUE(ret == detail::EncodingType::None);
  1551. #endif
  1552. }
  1553. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1554. // All supported encodings rejected with q=0 should return None
  1555. Request req;
  1556. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1557. Response res;
  1558. res.set_header("Content-Type", "text/plain");
  1559. auto ret = detail::encoding_type(req, res);
  1560. EXPECT_TRUE(ret == detail::EncodingType::None);
  1561. }
  1562. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1563. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1564. Request req;
  1565. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1566. Response res;
  1567. res.set_header("Content-Type", "text/plain");
  1568. auto ret = detail::encoding_type(req, res);
  1569. EXPECT_TRUE(ret == detail::EncodingType::None);
  1570. }
  1571. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1572. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1573. Request req;
  1574. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1575. Response res;
  1576. res.set_header("Content-Type", "text/plain");
  1577. auto ret = detail::encoding_type(req, res);
  1578. EXPECT_TRUE(ret == detail::EncodingType::None);
  1579. }
  1580. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1581. // RFC 7231: Accept-Encoding values are case-insensitive
  1582. Request req;
  1583. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1584. Response res;
  1585. res.set_header("Content-Type", "text/plain");
  1586. auto ret = detail::encoding_type(req, res);
  1587. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1588. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1589. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1590. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1591. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1592. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1593. #else
  1594. EXPECT_TRUE(ret == detail::EncodingType::None);
  1595. #endif
  1596. }
  1597. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1598. // q value should determine priority, not hardcoded order
  1599. Request req;
  1600. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1601. Response res;
  1602. res.set_header("Content-Type", "text/plain");
  1603. auto ret = detail::encoding_type(req, res);
  1604. // gzip has highest q=1.0, so it should be selected even though
  1605. // br and zstd are also supported
  1606. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1607. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1608. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1609. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1610. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1611. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1612. #else
  1613. EXPECT_TRUE(ret == detail::EncodingType::None);
  1614. #endif
  1615. }
  1616. TEST(BufferStreamTest, read) {
  1617. detail::BufferStream strm1;
  1618. Stream &strm = strm1;
  1619. EXPECT_EQ(5, strm.write("hello"));
  1620. char buf[512];
  1621. EXPECT_EQ(2, strm.read(buf, 2));
  1622. EXPECT_EQ('h', buf[0]);
  1623. EXPECT_EQ('e', buf[1]);
  1624. EXPECT_EQ(2, strm.read(buf, 2));
  1625. EXPECT_EQ('l', buf[0]);
  1626. EXPECT_EQ('l', buf[1]);
  1627. EXPECT_EQ(1, strm.read(buf, 1));
  1628. EXPECT_EQ('o', buf[0]);
  1629. EXPECT_EQ(0, strm.read(buf, 1));
  1630. }
  1631. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1632. auto host = "www.httpwatch.com";
  1633. auto ip = hosted_at(host);
  1634. EXPECT_EQ("23.96.13.243", ip);
  1635. std::vector<std::string> addrs;
  1636. hosted_at(host, addrs);
  1637. EXPECT_EQ(1u, addrs.size());
  1638. }
  1639. #if 0 // It depends on each test environment...
  1640. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1641. auto host = "www.youtube.com";
  1642. std::vector<std::string> addrs;
  1643. hosted_at(host, addrs);
  1644. EXPECT_EQ(20u, addrs.size());
  1645. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1646. EXPECT_TRUE(it != addrs.end());
  1647. }
  1648. #endif
  1649. class ChunkedEncodingTest : public ::testing::Test {
  1650. protected:
  1651. ChunkedEncodingTest()
  1652. : cli_(HOST, PORT)
  1653. #ifdef CPPHTTPLIB_SSL_ENABLED
  1654. ,
  1655. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1656. #endif
  1657. {
  1658. cli_.set_connection_timeout(2);
  1659. #ifdef CPPHTTPLIB_SSL_ENABLED
  1660. cli_.enable_server_certificate_verification(false);
  1661. #endif
  1662. }
  1663. virtual void SetUp() {
  1664. read_file("./image.jpg", image_data_);
  1665. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1666. res.set_content("Hello World!", "text/plain");
  1667. });
  1668. svr_.Get(
  1669. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1670. res.set_chunked_content_provider(
  1671. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1672. size_t remaining = image_data_.size() - offset;
  1673. if (remaining == 0) {
  1674. sink.done();
  1675. } else {
  1676. constexpr size_t CHUNK_SIZE = 1024;
  1677. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1678. sink.write(&image_data_[offset], send_size);
  1679. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1680. }
  1681. return true;
  1682. });
  1683. });
  1684. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1685. svr_.wait_until_ready();
  1686. }
  1687. virtual void TearDown() {
  1688. svr_.stop();
  1689. if (!request_threads_.empty()) {
  1690. std::this_thread::sleep_for(std::chrono::seconds(1));
  1691. for (auto &t : request_threads_) {
  1692. t.join();
  1693. }
  1694. }
  1695. t_.join();
  1696. }
  1697. #ifdef CPPHTTPLIB_SSL_ENABLED
  1698. SSLClient cli_;
  1699. SSLServer svr_;
  1700. #else
  1701. Client cli_;
  1702. Server svr_;
  1703. #endif
  1704. thread t_;
  1705. std::vector<thread> request_threads_;
  1706. std::string image_data_;
  1707. };
  1708. TEST_F(ChunkedEncodingTest, NormalGet) {
  1709. auto res = cli_.Get("/chunked");
  1710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1711. std::string out;
  1712. read_file("./image.jpg", out);
  1713. EXPECT_EQ(StatusCode::OK_200, res->status);
  1714. EXPECT_EQ(out, res->body);
  1715. }
  1716. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1717. std::string body;
  1718. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1719. body.append(data, data_length);
  1720. return true;
  1721. });
  1722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1723. std::string out;
  1724. read_file("./image.jpg", out);
  1725. EXPECT_EQ(StatusCode::OK_200, res->status);
  1726. EXPECT_EQ(out, body);
  1727. }
  1728. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1729. std::string body;
  1730. auto res = cli_.Get(
  1731. "/chunked",
  1732. [&](const Response &response) {
  1733. EXPECT_EQ(StatusCode::OK_200, response.status);
  1734. return true;
  1735. },
  1736. [&](const char *data, size_t data_length) {
  1737. body.append(data, data_length);
  1738. return true;
  1739. });
  1740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1741. std::string out;
  1742. read_file("./image.jpg", out);
  1743. EXPECT_EQ(StatusCode::OK_200, res->status);
  1744. EXPECT_EQ(out, body);
  1745. }
  1746. TEST(RangeTest, FromHTTPBin_Online) {
  1747. auto host = "httpbingo.org";
  1748. auto path = std::string{"/range/32"};
  1749. #ifdef CPPHTTPLIB_SSL_ENABLED
  1750. auto port = 443;
  1751. SSLClient cli(host, port);
  1752. #else
  1753. auto port = 80;
  1754. Client cli(host, port);
  1755. #endif
  1756. cli.set_connection_timeout(5);
  1757. {
  1758. auto res = cli.Get(path);
  1759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1760. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1761. EXPECT_EQ(StatusCode::OK_200, res->status);
  1762. }
  1763. {
  1764. Headers headers = {make_range_header({{1, -1}})};
  1765. auto res = cli.Get(path, headers);
  1766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1767. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1768. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1769. }
  1770. {
  1771. Headers headers = {make_range_header({{1, 10}})};
  1772. auto res = cli.Get(path, headers);
  1773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1774. EXPECT_EQ("bcdefghijk", res->body);
  1775. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1776. }
  1777. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1778. // entire resource, while the original httpbin returned 200. Both are
  1779. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1780. {
  1781. Headers headers = {make_range_header({{0, 31}})};
  1782. auto res = cli.Get(path, headers);
  1783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1784. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1785. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1786. res->status == StatusCode::PartialContent_206);
  1787. }
  1788. {
  1789. Headers headers = {make_range_header({{0, -1}})};
  1790. auto res = cli.Get(path, headers);
  1791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1792. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1793. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1794. res->status == StatusCode::PartialContent_206);
  1795. }
  1796. // go-httpbin returns 206 with clamped range for over-range requests,
  1797. // while the original httpbin returned 416. Both behaviors are observed
  1798. // in real servers, so we only verify the request succeeds.
  1799. {
  1800. Headers headers = {make_range_header({{0, 32}})};
  1801. auto res = cli.Get(path, headers);
  1802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1803. }
  1804. }
  1805. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1806. auto host = "unresolvableaddress.local";
  1807. auto path = std::string{"/"};
  1808. #ifdef CPPHTTPLIB_SSL_ENABLED
  1809. auto port = 443;
  1810. SSLClient cli(host, port);
  1811. #else
  1812. auto port = 80;
  1813. Client cli(host, port);
  1814. #endif
  1815. cli.set_connection_timeout(1);
  1816. {
  1817. auto res = cli.Get(path);
  1818. ASSERT_FALSE(res);
  1819. }
  1820. std::this_thread::sleep_for(std::chrono::seconds(8));
  1821. }
  1822. #if defined(__linux__) && defined(__GLIBC__) && \
  1823. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1824. // Forward declaration: in split builds split.py strips `inline` and moves the
  1825. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1826. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1827. // against the symbol in both header-only and split builds.
  1828. namespace httplib {
  1829. namespace detail {
  1830. int getaddrinfo_with_timeout(const char *node, const char *service,
  1831. const struct addrinfo *hints,
  1832. struct addrinfo **res, time_t timeout_sec);
  1833. } // namespace detail
  1834. } // namespace httplib
  1835. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1836. //
  1837. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1838. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1839. // gai_suspend() call hits the connection timeout the function calls
  1840. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1841. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1842. // still alive and still references the now-destroyed stack frame.
  1843. //
  1844. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1845. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1846. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1847. // and runs them in a container.
  1848. namespace {
  1849. bool should_run_issue_2431_tests() {
  1850. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1851. return v && *v && std::string(v) != "0";
  1852. }
  1853. std::string unique_unresolvable_host(int n) {
  1854. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1855. // glibc still asks the configured nameserver — which is exactly the path
  1856. // we want to exercise. A unique label per call avoids the resolver cache.
  1857. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1858. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1859. std::to_string(n) + ".invalid";
  1860. }
  1861. } // namespace
  1862. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1863. if (!should_run_issue_2431_tests()) {
  1864. GTEST_SKIP()
  1865. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1866. }
  1867. for (int i = 0; i < 8; ++i) {
  1868. struct addrinfo hints;
  1869. memset(&hints, 0, sizeof(hints));
  1870. hints.ai_family = AF_UNSPEC;
  1871. hints.ai_socktype = SOCK_STREAM;
  1872. auto host = unique_unresolvable_host(i);
  1873. struct addrinfo *result = nullptr;
  1874. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1875. &result, /*timeout_sec=*/1);
  1876. if (rc == 0 && result) { freeaddrinfo(result); }
  1877. }
  1878. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1879. // stack region they still believe holds their gaicb.
  1880. std::this_thread::sleep_for(std::chrono::seconds(3));
  1881. }
  1882. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1883. if (!should_run_issue_2431_tests()) {
  1884. GTEST_SKIP()
  1885. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1886. }
  1887. std::atomic<bool> stop{false};
  1888. std::vector<std::thread> threads;
  1889. for (int t = 0; t < 8; ++t) {
  1890. threads.emplace_back([t, &stop] {
  1891. int i = 0;
  1892. while (!stop.load(std::memory_order_relaxed)) {
  1893. struct addrinfo hints;
  1894. memset(&hints, 0, sizeof(hints));
  1895. hints.ai_family = AF_UNSPEC;
  1896. hints.ai_socktype = SOCK_STREAM;
  1897. auto host = unique_unresolvable_host(t * 100000 + i++);
  1898. struct addrinfo *result = nullptr;
  1899. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1900. &result, /*timeout_sec=*/1);
  1901. if (rc == 0 && result) { freeaddrinfo(result); }
  1902. }
  1903. });
  1904. }
  1905. std::this_thread::sleep_for(std::chrono::seconds(8));
  1906. stop.store(true, std::memory_order_relaxed);
  1907. for (auto &th : threads) {
  1908. th.join();
  1909. }
  1910. std::this_thread::sleep_for(std::chrono::seconds(3));
  1911. }
  1912. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1913. if (!should_run_issue_2431_tests()) {
  1914. GTEST_SKIP()
  1915. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1916. }
  1917. std::atomic<bool> stop{false};
  1918. std::vector<std::thread> threads;
  1919. for (int t = 0; t < 8; ++t) {
  1920. threads.emplace_back([t, &stop] {
  1921. int i = 0;
  1922. while (!stop.load(std::memory_order_relaxed)) {
  1923. auto host = unique_unresolvable_host(t * 100000 + i++);
  1924. Client cli(host, 80);
  1925. cli.set_connection_timeout(1, 0);
  1926. cli.set_read_timeout(1, 0);
  1927. cli.set_write_timeout(1, 0);
  1928. (void)cli.Get("/");
  1929. }
  1930. });
  1931. }
  1932. std::this_thread::sleep_for(std::chrono::seconds(8));
  1933. stop.store(true, std::memory_order_relaxed);
  1934. for (auto &th : threads) {
  1935. th.join();
  1936. }
  1937. std::this_thread::sleep_for(std::chrono::seconds(3));
  1938. }
  1939. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1940. TEST(ConnectionErrorTest, InvalidHost) {
  1941. auto host = "-abcde.com";
  1942. #ifdef CPPHTTPLIB_SSL_ENABLED
  1943. auto port = 443;
  1944. SSLClient cli(host, port);
  1945. #else
  1946. auto port = 80;
  1947. Client cli(host, port);
  1948. #endif
  1949. cli.set_connection_timeout(std::chrono::seconds(2));
  1950. auto res = cli.Get("/");
  1951. ASSERT_TRUE(!res);
  1952. EXPECT_EQ(Error::Connection, res.error());
  1953. }
  1954. TEST(ConnectionErrorTest, InvalidHost2) {
  1955. auto host = "httpcan.org/";
  1956. #ifdef CPPHTTPLIB_SSL_ENABLED
  1957. SSLClient cli(host);
  1958. #else
  1959. Client cli(host);
  1960. #endif
  1961. cli.set_connection_timeout(std::chrono::seconds(2));
  1962. auto res = cli.Get("/");
  1963. ASSERT_TRUE(!res);
  1964. EXPECT_EQ(Error::Connection, res.error());
  1965. }
  1966. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1967. auto host = "httpcan.org/";
  1968. #ifdef CPPHTTPLIB_SSL_ENABLED
  1969. SSLClient cli(host);
  1970. #else
  1971. Client cli(host);
  1972. #endif
  1973. cli.set_connection_timeout(std::chrono::seconds(2));
  1974. auto res = cli.Get("/");
  1975. ASSERT_TRUE(!res);
  1976. stringstream s;
  1977. s << "error code: " << res.error();
  1978. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1979. }
  1980. TEST(ConnectionErrorTest, InvalidPort) {
  1981. auto host = "localhost";
  1982. auto port = 44380;
  1983. #ifdef CPPHTTPLIB_SSL_ENABLED
  1984. SSLClient cli(host, port);
  1985. #else
  1986. Client cli(host, port);
  1987. #endif
  1988. cli.set_connection_timeout(std::chrono::seconds(2));
  1989. auto res = cli.Get("/");
  1990. ASSERT_TRUE(!res);
  1991. EXPECT_TRUE(Error::Connection == res.error() ||
  1992. Error::ConnectionTimeout == res.error());
  1993. }
  1994. TEST(ConnectionErrorTest, Timeout_Online) {
  1995. auto host = "google.com";
  1996. #ifdef CPPHTTPLIB_SSL_ENABLED
  1997. auto port = 44380;
  1998. SSLClient cli(host, port);
  1999. #else
  2000. auto port = 8080;
  2001. Client cli(host, port);
  2002. #endif
  2003. cli.set_connection_timeout(std::chrono::seconds(2));
  2004. // only probe one address type so that the error reason
  2005. // correlates to the timed-out IPv4, not the unsupported
  2006. // IPv6 connection attempt
  2007. cli.set_address_family(AF_INET);
  2008. auto res = cli.Get("/");
  2009. ASSERT_TRUE(!res);
  2010. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2011. }
  2012. TEST(CancelTest, NoCancel_Online) {
  2013. auto host = "httpbingo.org";
  2014. auto path = std::string{"/range/32"};
  2015. #ifdef CPPHTTPLIB_SSL_ENABLED
  2016. auto port = 443;
  2017. SSLClient cli(host, port);
  2018. #else
  2019. auto port = 80;
  2020. Client cli(host, port);
  2021. #endif
  2022. cli.set_connection_timeout(std::chrono::seconds(5));
  2023. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2025. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2026. EXPECT_EQ(StatusCode::OK_200, res->status);
  2027. }
  2028. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2029. // Use /bytes with a large payload so that the DownloadProgress callback
  2030. // (which only fires for Content-Length responses) is invoked before the
  2031. // entire body is received, giving cancellation a chance to fire.
  2032. auto host = "httpbingo.org";
  2033. auto path = std::string{"/bytes/524288"};
  2034. #ifdef CPPHTTPLIB_SSL_ENABLED
  2035. auto port = 443;
  2036. SSLClient cli(host, port);
  2037. #else
  2038. auto port = 80;
  2039. Client cli(host, port);
  2040. #endif
  2041. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2042. cli.set_connection_timeout(std::chrono::seconds(5));
  2043. ASSERT_TRUE(!res);
  2044. EXPECT_EQ(Error::Canceled, res.error());
  2045. }
  2046. TEST(CancelTest, WithCancelLargePayload_Online) {
  2047. auto host = "httpbingo.org";
  2048. auto path = std::string{"/bytes/524288"};
  2049. #ifdef CPPHTTPLIB_SSL_ENABLED
  2050. auto port = 443;
  2051. SSLClient cli(host, port);
  2052. #else
  2053. auto port = 80;
  2054. Client cli(host, port);
  2055. #endif
  2056. cli.set_connection_timeout(std::chrono::seconds(5));
  2057. uint32_t count = 0;
  2058. auto res =
  2059. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2060. ASSERT_TRUE(!res);
  2061. EXPECT_EQ(Error::Canceled, res.error());
  2062. }
  2063. TEST(CancelTest, NoCancelPost) {
  2064. Server svr;
  2065. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2066. res.set_content("Hello World!", "text/plain");
  2067. });
  2068. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2069. auto se = detail::scope_exit([&] {
  2070. svr.stop();
  2071. thread.join();
  2072. ASSERT_FALSE(svr.is_running());
  2073. });
  2074. svr.wait_until_ready();
  2075. Client cli(HOST, PORT);
  2076. cli.set_connection_timeout(std::chrono::seconds(5));
  2077. auto res =
  2078. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2079. "application/json", [](uint64_t, uint64_t) { return true; });
  2080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2081. EXPECT_EQ("Hello World!", res->body);
  2082. EXPECT_EQ(StatusCode::OK_200, res->status);
  2083. }
  2084. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2085. Server svr;
  2086. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2087. res.set_content("Hello World!", "text/plain");
  2088. });
  2089. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2090. auto se = detail::scope_exit([&] {
  2091. svr.stop();
  2092. thread.join();
  2093. ASSERT_FALSE(svr.is_running());
  2094. });
  2095. svr.wait_until_ready();
  2096. Client cli(HOST, PORT);
  2097. cli.set_connection_timeout(std::chrono::seconds(5));
  2098. auto res =
  2099. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2100. "application/json", [](uint64_t, uint64_t) { return false; });
  2101. ASSERT_TRUE(!res);
  2102. EXPECT_EQ(Error::Canceled, res.error());
  2103. }
  2104. TEST(CancelTest, WithCancelLargePayloadPost) {
  2105. Server svr;
  2106. svr.set_payload_max_length(200 * 1024 * 1024);
  2107. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2108. res.set_content(LARGE_DATA, "text/plain");
  2109. });
  2110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2111. auto se = detail::scope_exit([&] {
  2112. svr.stop();
  2113. thread.join();
  2114. ASSERT_FALSE(svr.is_running());
  2115. });
  2116. svr.wait_until_ready();
  2117. Client cli(HOST, PORT);
  2118. cli.set_payload_max_length(200 * 1024 * 1024);
  2119. cli.set_connection_timeout(std::chrono::seconds(5));
  2120. auto res =
  2121. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2122. "application/json", [](uint64_t, uint64_t) { return false; });
  2123. ASSERT_TRUE(!res);
  2124. EXPECT_EQ(Error::Canceled, res.error());
  2125. }
  2126. TEST(CancelTest, NoCancelPut) {
  2127. Server svr;
  2128. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2129. res.set_content("Hello World!", "text/plain");
  2130. });
  2131. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2132. auto se = detail::scope_exit([&] {
  2133. svr.stop();
  2134. thread.join();
  2135. ASSERT_FALSE(svr.is_running());
  2136. });
  2137. svr.wait_until_ready();
  2138. Client cli(HOST, PORT);
  2139. cli.set_connection_timeout(std::chrono::seconds(5));
  2140. auto res =
  2141. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2142. "application/json", [](uint64_t, uint64_t) { return true; });
  2143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2144. EXPECT_EQ("Hello World!", res->body);
  2145. EXPECT_EQ(StatusCode::OK_200, res->status);
  2146. }
  2147. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2148. Server svr;
  2149. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2150. res.set_content("Hello World!", "text/plain");
  2151. });
  2152. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2153. auto se = detail::scope_exit([&] {
  2154. svr.stop();
  2155. thread.join();
  2156. ASSERT_FALSE(svr.is_running());
  2157. });
  2158. svr.wait_until_ready();
  2159. Client cli(HOST, PORT);
  2160. cli.set_connection_timeout(std::chrono::seconds(5));
  2161. auto res =
  2162. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2163. "application/json", [](uint64_t, uint64_t) { return false; });
  2164. ASSERT_TRUE(!res);
  2165. EXPECT_EQ(Error::Canceled, res.error());
  2166. }
  2167. TEST(CancelTest, WithCancelLargePayloadPut) {
  2168. Server svr;
  2169. svr.set_payload_max_length(200 * 1024 * 1024);
  2170. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2171. res.set_content(LARGE_DATA, "text/plain");
  2172. });
  2173. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2174. auto se = detail::scope_exit([&] {
  2175. svr.stop();
  2176. thread.join();
  2177. ASSERT_FALSE(svr.is_running());
  2178. });
  2179. svr.wait_until_ready();
  2180. Client cli(HOST, PORT);
  2181. cli.set_payload_max_length(200 * 1024 * 1024);
  2182. cli.set_connection_timeout(std::chrono::seconds(5));
  2183. auto res =
  2184. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2185. "application/json", [](uint64_t, uint64_t) { return false; });
  2186. ASSERT_TRUE(!res);
  2187. EXPECT_EQ(Error::Canceled, res.error());
  2188. }
  2189. TEST(CancelTest, NoCancelPatch) {
  2190. Server svr;
  2191. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2192. res.set_content("Hello World!", "text/plain");
  2193. });
  2194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2195. auto se = detail::scope_exit([&] {
  2196. svr.stop();
  2197. thread.join();
  2198. ASSERT_FALSE(svr.is_running());
  2199. });
  2200. svr.wait_until_ready();
  2201. Client cli(HOST, PORT);
  2202. cli.set_connection_timeout(std::chrono::seconds(5));
  2203. auto res =
  2204. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2205. "application/json", [](uint64_t, uint64_t) { return true; });
  2206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2207. EXPECT_EQ("Hello World!", res->body);
  2208. EXPECT_EQ(StatusCode::OK_200, res->status);
  2209. }
  2210. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2211. Server svr;
  2212. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2213. res.set_content("Hello World!", "text/plain");
  2214. });
  2215. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2216. auto se = detail::scope_exit([&] {
  2217. svr.stop();
  2218. thread.join();
  2219. ASSERT_FALSE(svr.is_running());
  2220. });
  2221. svr.wait_until_ready();
  2222. Client cli(HOST, PORT);
  2223. cli.set_connection_timeout(std::chrono::seconds(5));
  2224. auto res =
  2225. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2226. "application/json", [](uint64_t, uint64_t) { return false; });
  2227. ASSERT_TRUE(!res);
  2228. EXPECT_EQ(Error::Canceled, res.error());
  2229. }
  2230. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2231. Server svr;
  2232. svr.set_payload_max_length(200 * 1024 * 1024);
  2233. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2234. res.set_content(LARGE_DATA, "text/plain");
  2235. });
  2236. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2237. auto se = detail::scope_exit([&] {
  2238. svr.stop();
  2239. thread.join();
  2240. ASSERT_FALSE(svr.is_running());
  2241. });
  2242. svr.wait_until_ready();
  2243. Client cli(HOST, PORT);
  2244. cli.set_payload_max_length(200 * 1024 * 1024);
  2245. cli.set_connection_timeout(std::chrono::seconds(5));
  2246. auto res =
  2247. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2248. "application/json", [](uint64_t, uint64_t) { return false; });
  2249. ASSERT_TRUE(!res);
  2250. EXPECT_EQ(Error::Canceled, res.error());
  2251. }
  2252. TEST(CancelTest, NoCancelDelete) {
  2253. Server svr;
  2254. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2255. res.set_content("Hello World!", "text/plain");
  2256. });
  2257. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2258. auto se = detail::scope_exit([&] {
  2259. svr.stop();
  2260. thread.join();
  2261. ASSERT_FALSE(svr.is_running());
  2262. });
  2263. svr.wait_until_ready();
  2264. Client cli(HOST, PORT);
  2265. cli.set_connection_timeout(std::chrono::seconds(5));
  2266. auto res =
  2267. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2268. "application/json", [](uint64_t, uint64_t) { return true; });
  2269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2270. EXPECT_EQ("Hello World!", res->body);
  2271. EXPECT_EQ(StatusCode::OK_200, res->status);
  2272. }
  2273. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2274. Server svr;
  2275. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2276. res.set_content("Hello World!", "text/plain");
  2277. });
  2278. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2279. auto se = detail::scope_exit([&] {
  2280. svr.stop();
  2281. thread.join();
  2282. ASSERT_FALSE(svr.is_running());
  2283. });
  2284. svr.wait_until_ready();
  2285. Client cli(HOST, PORT);
  2286. cli.set_connection_timeout(std::chrono::seconds(5));
  2287. auto res =
  2288. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2289. "application/json", [](uint64_t, uint64_t) { return false; });
  2290. ASSERT_TRUE(!res);
  2291. EXPECT_EQ(Error::Canceled, res.error());
  2292. }
  2293. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2294. Server svr;
  2295. svr.set_payload_max_length(200 * 1024 * 1024);
  2296. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2297. res.set_content(LARGE_DATA, "text/plain");
  2298. });
  2299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2300. auto se = detail::scope_exit([&] {
  2301. svr.stop();
  2302. thread.join();
  2303. ASSERT_FALSE(svr.is_running());
  2304. });
  2305. svr.wait_until_ready();
  2306. Client cli(HOST, PORT);
  2307. cli.set_payload_max_length(200 * 1024 * 1024);
  2308. cli.set_connection_timeout(std::chrono::seconds(5));
  2309. auto res =
  2310. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2311. "application/json", [](uint64_t, uint64_t) { return false; });
  2312. ASSERT_TRUE(!res);
  2313. EXPECT_EQ(Error::Canceled, res.error());
  2314. }
  2315. static std::string remove_whitespace(const std::string &input) {
  2316. std::string output;
  2317. output.reserve(input.size());
  2318. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2319. [](unsigned char c) { return !std::isspace(c); });
  2320. return output;
  2321. }
  2322. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2323. auto host = "httpbingo.org";
  2324. auto path = std::string{"/basic-auth/hello/world"};
  2325. #ifdef CPPHTTPLIB_SSL_ENABLED
  2326. auto port = 443;
  2327. SSLClient cli(host, port);
  2328. #else
  2329. auto port = 80;
  2330. Client cli(host, port);
  2331. #endif
  2332. {
  2333. auto res = cli.Get(path);
  2334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2335. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2336. }
  2337. {
  2338. auto res = cli.Get(
  2339. path, Headers{make_basic_authentication_header("hello", "world")});
  2340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2341. auto body = remove_whitespace(res->body);
  2342. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2343. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2344. EXPECT_EQ(StatusCode::OK_200, res->status);
  2345. }
  2346. {
  2347. cli.set_basic_auth("hello", "world");
  2348. auto res = cli.Get(path);
  2349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2350. auto body = remove_whitespace(res->body);
  2351. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2352. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2353. EXPECT_EQ(StatusCode::OK_200, res->status);
  2354. }
  2355. {
  2356. cli.set_basic_auth("hello", "bad");
  2357. auto res = cli.Get(path);
  2358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2359. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2360. }
  2361. {
  2362. cli.set_basic_auth("bad", "world");
  2363. auto res = cli.Get(path);
  2364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2365. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2366. }
  2367. }
  2368. #ifdef CPPHTTPLIB_SSL_ENABLED
  2369. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2370. auto host = "httpbingo.org";
  2371. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2372. auto paths = std::vector<std::string>{
  2373. "/digest-auth/auth/hello/world/MD5",
  2374. "/digest-auth/auth/hello/world/SHA-256",
  2375. };
  2376. auto port = 443;
  2377. SSLClient cli(host, port);
  2378. {
  2379. auto res = cli.Get(unauth_path);
  2380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2381. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2382. }
  2383. {
  2384. cli.set_digest_auth("hello", "world");
  2385. for (const auto &path : paths) {
  2386. auto res = cli.Get(path.c_str());
  2387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2388. auto body = remove_whitespace(res->body);
  2389. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2390. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2391. EXPECT_EQ(StatusCode::OK_200, res->status);
  2392. }
  2393. cli.set_digest_auth("hello", "bad");
  2394. for (const auto &path : paths) {
  2395. auto res = cli.Get(path.c_str());
  2396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2397. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2398. }
  2399. }
  2400. }
  2401. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2402. // comma-separated list of challenges, and each challenge may itself carry a
  2403. // comma-separated auth-param list, so a server can legally offer Basic
  2404. // before Digest, either as two field lines or packed into one. Runs one 401
  2405. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2406. // value() joins them in receipt order) and checks that the retry carries a
  2407. // well-formed Digest Authorization header naming expected_realm.
  2408. static void
  2409. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2410. const std::string &expected_realm) {
  2411. std::atomic<int> hits{0};
  2412. Server svr;
  2413. svr.Get("/x", [&](const Request &req, Response &res) {
  2414. if (++hits == 1) {
  2415. res.status = StatusCode::Unauthorized_401;
  2416. for (const auto &challenge : challenges) {
  2417. res.set_header("WWW-Authenticate", challenge);
  2418. }
  2419. } else {
  2420. auto authorization = req.get_header_value("Authorization");
  2421. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2422. EXPECT_NE(std::string::npos,
  2423. authorization.find("realm=\"" + expected_realm + "\""));
  2424. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2425. res.set_content("ok", "text/plain");
  2426. }
  2427. });
  2428. auto port = svr.bind_to_any_port(HOST);
  2429. std::thread t([&]() { svr.listen_after_bind(); });
  2430. auto se = detail::scope_exit([&] {
  2431. svr.stop();
  2432. t.join();
  2433. });
  2434. svr.wait_until_ready();
  2435. Client cli(HOST, port);
  2436. cli.set_digest_auth("hello", "world");
  2437. auto res = cli.Get("/x");
  2438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2439. EXPECT_EQ(2, hits.load());
  2440. }
  2441. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2442. static const char *kDigestChallenge =
  2443. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2444. "algorithm=MD5";
  2445. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2446. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2447. "testrealm");
  2448. }
  2449. // Same challenge list with the schemes in the opposite order, to make sure
  2450. // the fix above didn't just special-case "Basic first".
  2451. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2452. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2453. "testrealm");
  2454. }
  2455. // A comma inside a quoted auth-param value must not be mistaken for the
  2456. // separator between two challenges (or two auth-params).
  2457. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2458. run_digest_challenge_list_test(
  2459. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2460. "algorithm=MD5"},
  2461. "test,realm");
  2462. }
  2463. #endif
  2464. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2465. auto host = "google.com";
  2466. auto another_host = "example.com";
  2467. auto wrong_ip = "0.0.0.0";
  2468. #ifdef CPPHTTPLIB_SSL_ENABLED
  2469. SSLClient cli(host);
  2470. #else
  2471. Client cli(host);
  2472. #endif
  2473. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2476. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2477. }
  2478. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2479. auto host = "google.com";
  2480. auto wrong_ip = "0.0.0.0";
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. SSLClient cli(host);
  2483. #else
  2484. Client cli(host);
  2485. #endif
  2486. cli.set_hostname_addr_map({{host, wrong_ip}});
  2487. auto res = cli.Get("/");
  2488. ASSERT_TRUE(!res);
  2489. EXPECT_EQ(Error::Connection, res.error());
  2490. }
  2491. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2492. // A mapped value that is not an IP literal must be resolved. "localhost"
  2493. // resolves from the hosts file, so this test needs no external DNS.
  2494. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2495. auto host = "target.invalid";
  2496. Server svr;
  2497. std::string received_host;
  2498. svr.Get("/hi", [&](const Request &req, Response &res) {
  2499. received_host = req.get_header_value("Host");
  2500. res.set_content("Hello World!", "text/plain");
  2501. });
  2502. auto port = svr.bind_to_any_port(HOST);
  2503. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2504. auto se = detail::scope_exit([&] {
  2505. svr.stop();
  2506. thread.join();
  2507. ASSERT_FALSE(svr.is_running());
  2508. });
  2509. svr.wait_until_ready();
  2510. Client cli(host, port);
  2511. cli.set_hostname_addr_map({{host, HOST}});
  2512. auto res = cli.Get("/hi");
  2513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2514. EXPECT_EQ(StatusCode::OK_200, res->status);
  2515. // The mapping only redirects the connection; the identity stays host_.
  2516. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2517. }
  2518. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2519. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2520. auto host = "target.invalid";
  2521. Server svr;
  2522. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2523. res.set_content("Hello World!", "text/plain");
  2524. });
  2525. auto port = svr.bind_to_any_port("127.0.0.1");
  2526. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2527. auto se = detail::scope_exit([&] {
  2528. svr.stop();
  2529. thread.join();
  2530. ASSERT_FALSE(svr.is_running());
  2531. });
  2532. svr.wait_until_ready();
  2533. Client cli(host, port);
  2534. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2535. auto res = cli.Get("/hi");
  2536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. }
  2539. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2540. // An empty mapped value must leave host_ as the connection target. Without
  2541. // that guard the empty value would become the host argument, getaddrinfo
  2542. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2543. // loopback - silently connecting somewhere the caller never asked for.
  2544. // The server listens on loopback, so such a fallback would succeed and is
  2545. // therefore observable as a failure of this test.
  2546. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2547. Server svr;
  2548. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2549. res.set_content("Hello World!", "text/plain");
  2550. });
  2551. auto port = svr.bind_to_any_port(HOST);
  2552. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2553. auto se = detail::scope_exit([&] {
  2554. svr.stop();
  2555. thread.join();
  2556. ASSERT_FALSE(svr.is_running());
  2557. });
  2558. svr.wait_until_ready();
  2559. Client cli(blackhole, port);
  2560. cli.set_hostname_addr_map({{blackhole, ""}});
  2561. cli.set_connection_timeout(1);
  2562. auto res = cli.Get("/hi");
  2563. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2564. }
  2565. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2566. auto host = "httpbingo.org";
  2567. auto path = std::string{"/absolute-redirect/3"};
  2568. #ifdef CPPHTTPLIB_SSL_ENABLED
  2569. SSLClient cli(host);
  2570. #else
  2571. Client cli(host);
  2572. #endif
  2573. cli.set_follow_location(true);
  2574. auto res = cli.Get(path);
  2575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2576. EXPECT_EQ(StatusCode::OK_200, res->status);
  2577. }
  2578. TEST(RedirectTest, Redirect_Online) {
  2579. auto host = "httpbingo.org";
  2580. auto path = std::string{"/redirect/3"};
  2581. #ifdef CPPHTTPLIB_SSL_ENABLED
  2582. SSLClient cli(host);
  2583. #else
  2584. Client cli(host);
  2585. #endif
  2586. cli.set_follow_location(true);
  2587. auto res = cli.Get(path);
  2588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2589. EXPECT_EQ(StatusCode::OK_200, res->status);
  2590. }
  2591. TEST(RelativeRedirectTest, Redirect_Online) {
  2592. auto host = "httpbingo.org";
  2593. auto path = std::string{"/relative-redirect/3"};
  2594. #ifdef CPPHTTPLIB_SSL_ENABLED
  2595. SSLClient cli(host);
  2596. #else
  2597. Client cli(host);
  2598. #endif
  2599. cli.set_follow_location(true);
  2600. auto res = cli.Get(path);
  2601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2602. EXPECT_EQ(StatusCode::OK_200, res->status);
  2603. }
  2604. TEST(TooManyRedirectTest, Redirect_Online) {
  2605. auto host = "httpbingo.org";
  2606. auto path = std::string{"/redirect/21"};
  2607. #ifdef CPPHTTPLIB_SSL_ENABLED
  2608. SSLClient cli(host);
  2609. #else
  2610. Client cli(host);
  2611. #endif
  2612. cli.set_follow_location(true);
  2613. auto res = cli.Get(path);
  2614. ASSERT_TRUE(!res);
  2615. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2616. }
  2617. #ifdef CPPHTTPLIB_SSL_ENABLED
  2618. TEST(YahooRedirectTest, Redirect_Online) {
  2619. Client cli("yahoo.com");
  2620. auto res = cli.Get("/");
  2621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2622. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2623. cli.set_follow_location(true);
  2624. res = cli.Get("/");
  2625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2626. EXPECT_EQ(StatusCode::OK_200, res->status);
  2627. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2628. }
  2629. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2630. #define REDIR_HOST "httpbingo.org"
  2631. #define REDIR_PATH "/redirect-to"
  2632. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2633. SSLClient cli(REDIR_HOST);
  2634. cli.set_follow_location(true);
  2635. auto res =
  2636. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2638. EXPECT_EQ(StatusCode::OK_200, res->status);
  2639. }
  2640. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2641. SSLClient cli(REDIR_HOST);
  2642. cli.set_follow_location(true);
  2643. Params params;
  2644. params.emplace("url", "http://example.com");
  2645. params.emplace("status_code", "302");
  2646. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2648. EXPECT_EQ(StatusCode::OK_200, res->status);
  2649. }
  2650. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2651. SSLClient cli(REDIR_HOST);
  2652. cli.set_follow_location(true);
  2653. Params params;
  2654. params.emplace("url", "http://example.com");
  2655. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2657. EXPECT_EQ(StatusCode::OK_200, res->status);
  2658. }
  2659. TEST(UrlWithSpace, Redirect_Online) {
  2660. SSLClient cli("edge.forgecdn.net");
  2661. cli.set_follow_location(true);
  2662. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2664. EXPECT_EQ(StatusCode::OK_200, res->status);
  2665. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2666. }
  2667. #endif
  2668. #if !defined(_WIN32) && !defined(_WIN64)
  2669. TEST(ReceiveSignals, Signal) {
  2670. auto setupSignalHandlers = []() {
  2671. struct sigaction act;
  2672. sigemptyset(&act.sa_mask);
  2673. act.sa_flags = SA_SIGINFO;
  2674. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2675. switch (sig) {
  2676. case SIGINT:
  2677. default: break;
  2678. }
  2679. };
  2680. ::sigaction(SIGINT, &act, nullptr);
  2681. };
  2682. Server svr;
  2683. int port = 0;
  2684. auto thread = std::thread([&]() {
  2685. setupSignalHandlers();
  2686. port = svr.bind_to_any_port(HOST);
  2687. svr.listen_after_bind();
  2688. });
  2689. auto se = detail::scope_exit([&] {
  2690. svr.stop();
  2691. thread.join();
  2692. ASSERT_FALSE(svr.is_running());
  2693. });
  2694. svr.wait_until_ready();
  2695. ASSERT_TRUE(svr.is_running());
  2696. pthread_kill(thread.native_handle(), SIGINT);
  2697. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2698. ASSERT_TRUE(svr.is_running());
  2699. }
  2700. #endif
  2701. TEST(RedirectToDifferentPort, Redirect) {
  2702. Server svr1;
  2703. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2704. res.set_content("Hello World!", "text/plain");
  2705. });
  2706. int svr1_port = 0;
  2707. auto thread1 = std::thread([&]() {
  2708. svr1_port = svr1.bind_to_any_port(HOST);
  2709. svr1.listen_after_bind();
  2710. });
  2711. Server svr2;
  2712. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2713. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2714. });
  2715. int svr2_port = 0;
  2716. auto thread2 = std::thread([&]() {
  2717. svr2_port = svr2.bind_to_any_port(HOST);
  2718. svr2.listen_after_bind();
  2719. });
  2720. auto se = detail::scope_exit([&] {
  2721. svr2.stop();
  2722. thread2.join();
  2723. svr1.stop();
  2724. thread1.join();
  2725. ASSERT_FALSE(svr2.is_running());
  2726. ASSERT_FALSE(svr1.is_running());
  2727. });
  2728. svr1.wait_until_ready();
  2729. svr2.wait_until_ready();
  2730. Client cli("localhost", svr2_port);
  2731. cli.set_follow_location(true);
  2732. auto res = cli.Get("/2");
  2733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2734. EXPECT_EQ(StatusCode::OK_200, res->status);
  2735. EXPECT_EQ("Hello World!", res->body);
  2736. }
  2737. static void
  2738. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2739. Server svr1;
  2740. std::string captured_authorization;
  2741. svr1.Get("/target", [&](const Request &req, Response &res) {
  2742. captured_authorization = req.get_header_value("Authorization");
  2743. res.set_content("OK", "text/plain");
  2744. });
  2745. int svr1_port = 0;
  2746. auto thread1 = std::thread([&]() {
  2747. svr1_port = svr1.bind_to_any_port(HOST);
  2748. svr1.listen_after_bind();
  2749. });
  2750. Server svr2;
  2751. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2752. res.set_redirect(
  2753. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2754. });
  2755. int svr2_port = 0;
  2756. auto thread2 = std::thread([&]() {
  2757. svr2_port = svr2.bind_to_any_port(HOST);
  2758. svr2.listen_after_bind();
  2759. });
  2760. auto se = detail::scope_exit([&] {
  2761. svr2.stop();
  2762. thread2.join();
  2763. svr1.stop();
  2764. thread1.join();
  2765. ASSERT_FALSE(svr2.is_running());
  2766. ASSERT_FALSE(svr1.is_running());
  2767. });
  2768. svr1.wait_until_ready();
  2769. svr2.wait_until_ready();
  2770. Client cli("localhost", svr2_port);
  2771. cli.set_follow_location(true);
  2772. set_auth(cli);
  2773. auto res = cli.Get("/redir");
  2774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2775. EXPECT_EQ(StatusCode::OK_200, res->status);
  2776. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2777. EXPECT_TRUE(captured_authorization.empty());
  2778. }
  2779. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2780. TestDoNotForwardCredentialsOnRedirect(
  2781. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2782. }
  2783. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2784. TestDoNotForwardCredentialsOnRedirect(
  2785. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2786. }
  2787. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2788. Server svr1;
  2789. std::string captured_cookie;
  2790. bool target_hit = false;
  2791. svr1.Get("/target", [&](const Request &req, Response &res) {
  2792. captured_cookie = req.get_header_value("Cookie");
  2793. target_hit = true;
  2794. res.set_content("OK", "text/plain");
  2795. });
  2796. int svr1_port = 0;
  2797. auto thread1 = std::thread([&]() {
  2798. svr1_port = svr1.bind_to_any_port(HOST);
  2799. svr1.listen_after_bind();
  2800. });
  2801. Server svr2;
  2802. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2803. res.set_redirect(
  2804. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2805. });
  2806. int svr2_port = 0;
  2807. auto thread2 = std::thread([&]() {
  2808. svr2_port = svr2.bind_to_any_port(HOST);
  2809. svr2.listen_after_bind();
  2810. });
  2811. auto se = detail::scope_exit([&] {
  2812. svr2.stop();
  2813. thread2.join();
  2814. svr1.stop();
  2815. thread1.join();
  2816. ASSERT_FALSE(svr2.is_running());
  2817. ASSERT_FALSE(svr1.is_running());
  2818. });
  2819. svr1.wait_until_ready();
  2820. svr2.wait_until_ready();
  2821. Client cli("localhost", svr2_port);
  2822. cli.set_follow_location(true);
  2823. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2824. auto res = cli.Get("/redir", headers);
  2825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2826. EXPECT_EQ(StatusCode::OK_200, res->status);
  2827. EXPECT_TRUE(target_hit);
  2828. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2829. EXPECT_TRUE(captured_cookie.empty());
  2830. }
  2831. TEST(RedirectToSamePort, ForwardCookie) {
  2832. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2833. // header so that ordinary session flows keep working.
  2834. Server svr;
  2835. std::string captured_cookie;
  2836. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2837. res.set_redirect("/target", 302);
  2838. });
  2839. svr.Get("/target", [&](const Request &req, Response &res) {
  2840. captured_cookie = req.get_header_value("Cookie");
  2841. res.set_content("OK", "text/plain");
  2842. });
  2843. auto port = svr.bind_to_any_port(HOST);
  2844. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2845. auto se = detail::scope_exit([&] {
  2846. svr.stop();
  2847. thread.join();
  2848. ASSERT_FALSE(svr.is_running());
  2849. });
  2850. svr.wait_until_ready();
  2851. Client cli(HOST, port);
  2852. cli.set_follow_location(true);
  2853. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2854. auto res = cli.Get("/redir", headers);
  2855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2856. EXPECT_EQ(StatusCode::OK_200, res->status);
  2857. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2858. }
  2859. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2860. Server svr;
  2861. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2862. // Port number that overflows int — should not crash
  2863. res.set_redirect("http://localhost:99999999999999999999/target");
  2864. });
  2865. auto port = svr.bind_to_any_port(HOST);
  2866. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2867. auto se = detail::scope_exit([&] {
  2868. svr.stop();
  2869. thread.join();
  2870. ASSERT_FALSE(svr.is_running());
  2871. });
  2872. svr.wait_until_ready();
  2873. Client cli(HOST, port);
  2874. cli.set_follow_location(true);
  2875. auto res = cli.Get("/redir");
  2876. // Should fail gracefully, not crash (no valid response due to bad port)
  2877. EXPECT_FALSE(res);
  2878. }
  2879. TEST(RedirectFromPageWithContent, Redirect) {
  2880. Server svr;
  2881. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2882. res.set_content("___", "text/plain");
  2883. res.set_redirect("/2");
  2884. });
  2885. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2886. res.set_content("Hello World!", "text/plain");
  2887. });
  2888. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2889. auto se = detail::scope_exit([&] {
  2890. svr.stop();
  2891. th.join();
  2892. ASSERT_FALSE(svr.is_running());
  2893. });
  2894. svr.wait_until_ready();
  2895. {
  2896. Client cli("localhost", PORT);
  2897. cli.set_follow_location(true);
  2898. std::string body;
  2899. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2900. body.append(data, data_length);
  2901. return true;
  2902. });
  2903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2904. EXPECT_EQ(StatusCode::OK_200, res->status);
  2905. EXPECT_EQ("Hello World!", body);
  2906. }
  2907. {
  2908. Client cli("localhost", PORT);
  2909. std::string body;
  2910. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2911. body.append(data, data_length);
  2912. return true;
  2913. });
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::Found_302, res->status);
  2916. EXPECT_EQ("___", body);
  2917. }
  2918. }
  2919. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2920. Server svr;
  2921. auto port_str = std::to_string(PORT);
  2922. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2923. auto expected_host = "[::1]:" + port_str;
  2924. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2925. res.set_content("___", "text/plain");
  2926. // res.set_redirect("/2");
  2927. res.set_redirect(redirect_url);
  2928. });
  2929. svr.Get("/2", [&](const Request &req, Response &res) {
  2930. auto host_header = req.headers.find("Host");
  2931. ASSERT_TRUE(host_header != req.headers.end());
  2932. EXPECT_EQ(expected_host, host_header->second);
  2933. res.set_content("Hello World!", "text/plain");
  2934. });
  2935. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2936. auto se = detail::scope_exit([&] {
  2937. svr.stop();
  2938. th.join();
  2939. ASSERT_FALSE(svr.is_running());
  2940. });
  2941. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2942. // actually starts anything, so the condition !svr.is_running() will
  2943. // always remain true, and the loop never stops.
  2944. // This basically counts how many milliseconds have passed since the
  2945. // call to svr.listen(), and if after 5 seconds nothing started yet
  2946. // aborts the test.
  2947. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2948. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2949. ASSERT_LT(milliseconds, 5000U);
  2950. }
  2951. {
  2952. Client cli("::1", PORT);
  2953. cli.set_follow_location(true);
  2954. std::string body;
  2955. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2956. body.append(data, data_length);
  2957. return true;
  2958. });
  2959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2960. EXPECT_EQ(StatusCode::OK_200, res->status);
  2961. EXPECT_EQ("Hello World!", body);
  2962. }
  2963. {
  2964. Client cli("::1", PORT);
  2965. std::string body;
  2966. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2967. body.append(data, data_length);
  2968. return true;
  2969. });
  2970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2971. EXPECT_EQ(StatusCode::Found_302, res->status);
  2972. EXPECT_EQ("___", body);
  2973. }
  2974. }
  2975. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2976. Server svr;
  2977. svr.Get("/foo", [](const Request &req, Response &res) {
  2978. auto a = req.params.find("a");
  2979. if (a != req.params.end()) {
  2980. res.set_content((*a).second, "text/plain");
  2981. res.status = StatusCode::OK_200;
  2982. } else {
  2983. res.status = StatusCode::BadRequest_400;
  2984. }
  2985. });
  2986. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2987. auto se = detail::scope_exit([&] {
  2988. svr.stop();
  2989. thread.join();
  2990. ASSERT_FALSE(svr.is_running());
  2991. });
  2992. svr.wait_until_ready();
  2993. {
  2994. Client cli(HOST, PORT);
  2995. cli.set_path_encode(false);
  2996. auto res = cli.Get("/foo?a=explicitly+encoded");
  2997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2998. EXPECT_EQ(StatusCode::OK_200, res->status);
  2999. // This expects it back with a space, as the `+` won't have been
  3000. // url-encoded, and server-side the params get decoded turning `+`
  3001. // into spaces.
  3002. EXPECT_EQ("explicitly encoded", res->body);
  3003. }
  3004. }
  3005. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3006. // When path encoding is disabled the client must transmit the supplied
  3007. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3008. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3009. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3010. // than a space (0x20). Assert on the raw wire target to catch this.
  3011. Server svr;
  3012. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3013. svr.Get("/foo", [&](const Request &req, Response &res) {
  3014. EXPECT_EQ(expected_target, req.target);
  3015. res.status = StatusCode::OK_200;
  3016. });
  3017. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3018. auto se = detail::scope_exit([&] {
  3019. svr.stop();
  3020. thread.join();
  3021. ASSERT_FALSE(svr.is_running());
  3022. });
  3023. svr.wait_until_ready();
  3024. {
  3025. Client cli(HOST, PORT);
  3026. cli.set_path_encode(false);
  3027. auto res = cli.Get(expected_target.c_str());
  3028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3029. EXPECT_EQ(StatusCode::OK_200, res->status);
  3030. }
  3031. }
  3032. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3033. // `open_stream()` used to skip the path encoding that the buffered send
  3034. // path applies, so the same `path` produced different bytes in the request
  3035. // line depending on which API was used. Assert the two agree.
  3036. Server svr;
  3037. std::string target;
  3038. svr.Get(".*", [&](const Request &req, Response &res) {
  3039. target = req.target;
  3040. res.status = StatusCode::OK_200;
  3041. });
  3042. auto port = svr.bind_to_any_port(HOST);
  3043. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3044. auto se = detail::scope_exit([&] {
  3045. svr.stop();
  3046. thread.join();
  3047. ASSERT_FALSE(svr.is_running());
  3048. });
  3049. svr.wait_until_ready();
  3050. struct {
  3051. const char *path;
  3052. const char *expected;
  3053. } cases[] = {
  3054. {"/a b?x=1", "/a%20b?x=1"},
  3055. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3056. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3057. };
  3058. for (const auto &c : cases) {
  3059. Client cli(HOST, port);
  3060. target.clear();
  3061. auto res = cli.Get(c.path);
  3062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3063. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3064. auto buffered_target = target;
  3065. target.clear();
  3066. auto handle = cli.open_stream("GET", c.path);
  3067. EXPECT_TRUE(handle.is_valid())
  3068. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3069. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3070. }
  3071. }
  3072. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3073. // The `set_path_encode(false)` contract — transmit the supplied target
  3074. // verbatim — must hold for the streaming API too.
  3075. Server svr;
  3076. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3077. std::string target;
  3078. svr.Get("/foo", [&](const Request &req, Response &res) {
  3079. target = req.target;
  3080. res.status = StatusCode::OK_200;
  3081. });
  3082. auto port = svr.bind_to_any_port(HOST);
  3083. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3084. auto se = detail::scope_exit([&] {
  3085. svr.stop();
  3086. thread.join();
  3087. ASSERT_FALSE(svr.is_running());
  3088. });
  3089. svr.wait_until_ready();
  3090. {
  3091. Client cli(HOST, port);
  3092. cli.set_path_encode(false);
  3093. auto handle = cli.open_stream("GET", expected_target);
  3094. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3095. EXPECT_EQ(expected_target, target);
  3096. }
  3097. }
  3098. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3099. // With path encoding enabled a CR/LF in the target is percent-encoded
  3100. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3101. // write_request_line still backstops `set_path_encode(false)`, which is
  3102. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3103. Server svr;
  3104. // Captured before routing: the decoded path contains a newline, which a
  3105. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3106. std::string target;
  3107. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3108. target = req.target;
  3109. res.status = StatusCode::OK_200;
  3110. return Server::HandlerResponse::Handled;
  3111. });
  3112. auto port = svr.bind_to_any_port(HOST);
  3113. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3114. auto se = detail::scope_exit([&] {
  3115. svr.stop();
  3116. thread.join();
  3117. ASSERT_FALSE(svr.is_running());
  3118. });
  3119. svr.wait_until_ready();
  3120. {
  3121. Client cli(HOST, port);
  3122. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3123. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3124. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3125. }
  3126. }
  3127. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3128. // Nothing may reach the wire: a raw CR/LF target would split the request
  3129. // line and inject headers.
  3130. Server svr;
  3131. // Pre-routing so that "not called" means nothing reached the server at all,
  3132. // rather than merely failing to match a handler pattern.
  3133. auto handler_called = false;
  3134. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3135. handler_called = true;
  3136. res.status = StatusCode::OK_200;
  3137. return Server::HandlerResponse::Handled;
  3138. });
  3139. auto port = svr.bind_to_any_port(HOST);
  3140. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3141. auto se = detail::scope_exit([&] {
  3142. svr.stop();
  3143. thread.join();
  3144. ASSERT_FALSE(svr.is_running());
  3145. });
  3146. svr.wait_until_ready();
  3147. {
  3148. Client cli(HOST, port);
  3149. cli.set_path_encode(false);
  3150. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3151. EXPECT_FALSE(handle.is_valid());
  3152. EXPECT_EQ(Error::Write, handle.error);
  3153. EXPECT_FALSE(handler_called);
  3154. }
  3155. }
  3156. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3157. // Which of the two branches runs is decided by whether the query component
  3158. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3159. // an empty query and must still fall back to building one from
  3160. // `req.params`, while a non-empty query must win over `req.params`.
  3161. Server svr;
  3162. std::string target;
  3163. svr.Get("/foo", [&](const Request &req, Response &res) {
  3164. target = req.target;
  3165. res.status = StatusCode::OK_200;
  3166. });
  3167. auto port = svr.bind_to_any_port(HOST);
  3168. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3169. auto se = detail::scope_exit([&] {
  3170. svr.stop();
  3171. thread.join();
  3172. ASSERT_FALSE(svr.is_running());
  3173. });
  3174. svr.wait_until_ready();
  3175. {
  3176. // Trailing `?` -> empty query component -> `req.params` is used.
  3177. Client cli(HOST, port);
  3178. Request req;
  3179. req.method = "GET";
  3180. req.path = "/foo?";
  3181. req.params.emplace("a", "1");
  3182. target.clear();
  3183. auto res = cli.send(req);
  3184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3185. EXPECT_EQ("/foo?a=1", target);
  3186. }
  3187. {
  3188. // Non-empty query in `req.path` -> `req.params` is not appended.
  3189. Client cli(HOST, port);
  3190. Request req;
  3191. req.method = "GET";
  3192. req.path = "/foo?b=2";
  3193. req.params.emplace("a", "1");
  3194. target.clear();
  3195. auto res = cli.send(req);
  3196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3197. EXPECT_EQ("/foo?b=2", target);
  3198. }
  3199. }
  3200. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3201. Server svr;
  3202. svr.Get("/", [](const Request &req, Response &) {
  3203. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3204. });
  3205. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3206. auto se = detail::scope_exit([&] {
  3207. svr.stop();
  3208. thread.join();
  3209. ASSERT_FALSE(svr.is_running());
  3210. });
  3211. svr.wait_until_ready();
  3212. {
  3213. Client cli(HOST, PORT);
  3214. cli.set_path_encode(false);
  3215. auto res = cli.Get("/?something=%0A");
  3216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3217. EXPECT_EQ(StatusCode::OK_200, res->status);
  3218. }
  3219. }
  3220. TEST(BindServerTest, BindDualStack) {
  3221. Server svr;
  3222. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3223. res.set_content("Hello World!", "text/plain");
  3224. });
  3225. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3226. auto se = detail::scope_exit([&] {
  3227. svr.stop();
  3228. thread.join();
  3229. ASSERT_FALSE(svr.is_running());
  3230. });
  3231. svr.wait_until_ready();
  3232. {
  3233. Client cli("127.0.0.1", PORT);
  3234. auto res = cli.Get("/1");
  3235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3236. EXPECT_EQ(StatusCode::OK_200, res->status);
  3237. EXPECT_EQ("Hello World!", res->body);
  3238. }
  3239. {
  3240. Client cli("::1", PORT);
  3241. auto res = cli.Get("/1");
  3242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3243. EXPECT_EQ(StatusCode::OK_200, res->status);
  3244. EXPECT_EQ("Hello World!", res->body);
  3245. }
  3246. }
  3247. TEST(BindServerTest, BindAndListenSeparately) {
  3248. Server svr;
  3249. int port = svr.bind_to_any_port("0.0.0.0");
  3250. ASSERT_TRUE(svr.is_valid());
  3251. ASSERT_TRUE(port > 0);
  3252. svr.stop();
  3253. }
  3254. // Reports whether anything is still listening on a loopback port. A plain
  3255. // connect() is used instead of a Client request because a socket left bound by
  3256. // mistake accepts the connection into its backlog and never answers, which
  3257. // would hang the test instead of failing it.
  3258. static bool is_loopback_port_accepting(int port) {
  3259. sockaddr_in addr{};
  3260. addr.sin_family = AF_INET;
  3261. addr.sin_port = htons(static_cast<uint16_t>(port));
  3262. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3263. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3264. EXPECT_NE(sock, INVALID_SOCKET);
  3265. if (sock == INVALID_SOCKET) { return false; }
  3266. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3267. static_cast<socklen_t>(sizeof(addr)));
  3268. detail::close_socket(sock);
  3269. return ret == 0;
  3270. }
  3271. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3272. Server svr;
  3273. auto port = svr.bind_to_any_port("127.0.0.1");
  3274. ASSERT_TRUE(port > 0);
  3275. svr.stop();
  3276. // bind_to_any_port() already called listen(2), so until stop() closed the
  3277. // descriptor the port kept accepting connections into the backlog. ASSERT
  3278. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3279. // below blocks forever in the accept loop.
  3280. ASSERT_FALSE(is_loopback_port_accepting(port));
  3281. // Nothing is left to accept on, so listen_after_bind() must report failure
  3282. // instead of returning success without ever serving.
  3283. EXPECT_FALSE(svr.listen_after_bind());
  3284. // The failed listen marks the server decommissioned, so a waiter returns
  3285. // instead of spinning forever.
  3286. svr.wait_until_ready();
  3287. }
  3288. #ifdef CPPHTTPLIB_SSL_ENABLED
  3289. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3290. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3291. CLIENT_CA_CERT_DIR);
  3292. int port = svr.bind_to_any_port("0.0.0.0");
  3293. ASSERT_TRUE(svr.is_valid());
  3294. ASSERT_TRUE(port > 0);
  3295. svr.stop();
  3296. }
  3297. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3298. // or a rejected CustomRoute() registration would not stop the server binding.
  3299. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3300. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3301. CLIENT_CA_CERT_DIR);
  3302. ASSERT_TRUE(svr.is_valid());
  3303. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3304. EXPECT_FALSE(svr.is_valid());
  3305. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3306. }
  3307. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3308. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3309. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3310. int port = svr.bind_to_any_port("0.0.0.0");
  3311. ASSERT_TRUE(svr.is_valid());
  3312. ASSERT_TRUE(port > 0);
  3313. svr.stop();
  3314. }
  3315. TEST(BindServerTest, UpdateCertsPem) {
  3316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3317. int port = svr.bind_to_any_port("0.0.0.0");
  3318. ASSERT_TRUE(svr.is_valid());
  3319. ASSERT_TRUE(port > 0);
  3320. // Read PEM files
  3321. std::string cert_pem, key_pem, ca_pem;
  3322. read_file(SERVER_CERT_FILE, cert_pem);
  3323. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3324. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3325. // Update server certificates using PEM API
  3326. ASSERT_TRUE(
  3327. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3328. ASSERT_TRUE(svr.is_valid());
  3329. svr.stop();
  3330. }
  3331. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3332. // Start server with client CA (enables client auth)
  3333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3334. ASSERT_TRUE(svr.is_valid());
  3335. bool handler_called = false;
  3336. svr.Get("/test", [&](const Request &req, Response &res) {
  3337. handler_called = true;
  3338. // Verify client certificate is present
  3339. auto cert = req.peer_cert();
  3340. EXPECT_TRUE(static_cast<bool>(cert));
  3341. res.set_content("ok", "text/plain");
  3342. });
  3343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3344. auto se = detail::scope_exit([&] {
  3345. svr.stop();
  3346. t.join();
  3347. ASSERT_FALSE(svr.is_running());
  3348. });
  3349. svr.wait_until_ready();
  3350. // Read PEM files
  3351. std::string cert_pem, key_pem, ca_pem;
  3352. read_file(SERVER_CERT_FILE, cert_pem);
  3353. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3354. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3355. // Update server certificates and client CA using PEM API while server running
  3356. ASSERT_TRUE(
  3357. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3358. // Connect with client certificate
  3359. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3360. cli.enable_server_certificate_verification(false);
  3361. cli.set_connection_timeout(30);
  3362. auto res = cli.Get("/test");
  3363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3364. ASSERT_EQ(StatusCode::OK_200, res->status);
  3365. ASSERT_TRUE(handler_called);
  3366. EXPECT_EQ("ok", res->body);
  3367. }
  3368. #endif
  3369. TEST(ErrorHandlerTest, ContentLength) {
  3370. Server svr;
  3371. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3372. res.status = StatusCode::OK_200;
  3373. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3374. "text/html"); // <= Content-Length still 13
  3375. });
  3376. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3377. res.set_content("Hello World!\n", "text/plain");
  3378. res.status = 524;
  3379. });
  3380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3381. auto se = detail::scope_exit([&] {
  3382. svr.stop();
  3383. thread.join();
  3384. ASSERT_FALSE(svr.is_running());
  3385. });
  3386. svr.wait_until_ready();
  3387. {
  3388. Client cli(HOST, PORT);
  3389. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3391. EXPECT_EQ(StatusCode::OK_200, res->status);
  3392. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3393. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3394. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3395. }
  3396. }
  3397. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3398. TEST(ExceptionTest, WithoutExceptionHandler) {
  3399. Server svr;
  3400. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3401. throw std::runtime_error("exception...");
  3402. });
  3403. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3404. throw std::runtime_error("exception\r\n...");
  3405. });
  3406. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3407. auto se = detail::scope_exit([&] {
  3408. svr.stop();
  3409. listen_thread.join();
  3410. ASSERT_FALSE(svr.is_running());
  3411. });
  3412. svr.wait_until_ready();
  3413. Client cli("localhost", PORT);
  3414. {
  3415. auto res = cli.Get("/exception");
  3416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3417. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3418. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3419. }
  3420. {
  3421. auto res = cli.Get("/unknown");
  3422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3423. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3424. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3425. }
  3426. }
  3427. TEST(ExceptionTest, WithExceptionHandler) {
  3428. Server svr;
  3429. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3430. std::exception_ptr ep) {
  3431. EXPECT_FALSE(ep == nullptr);
  3432. try {
  3433. std::rethrow_exception(ep);
  3434. } catch (std::exception &e) {
  3435. EXPECT_EQ("abc", std::string(e.what()));
  3436. } catch (...) {}
  3437. res.status = StatusCode::InternalServerError_500;
  3438. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3439. "text/html"); // <= Content-Length still 13 at this point
  3440. });
  3441. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3442. res.set_content("Hello World!\n", "text/plain");
  3443. throw std::runtime_error("abc");
  3444. });
  3445. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3446. auto se = detail::scope_exit([&] {
  3447. svr.stop();
  3448. thread.join();
  3449. ASSERT_FALSE(svr.is_running());
  3450. });
  3451. svr.wait_until_ready();
  3452. for (size_t i = 0; i < 10; i++) {
  3453. Client cli(HOST, PORT);
  3454. for (size_t j = 0; j < 100; j++) {
  3455. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3457. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3458. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3459. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3460. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3461. }
  3462. cli.set_keep_alive(true);
  3463. for (size_t j = 0; j < 100; j++) {
  3464. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3466. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3467. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3468. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3469. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3470. }
  3471. }
  3472. }
  3473. TEST(ExceptionTest, AndErrorHandler) {
  3474. Server svr;
  3475. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3476. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3477. });
  3478. svr.set_exception_handler(
  3479. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3480. EXPECT_FALSE(ep == nullptr);
  3481. try {
  3482. std::rethrow_exception(ep);
  3483. } catch (std::exception &e) {
  3484. res.set_content(e.what(), "text/html");
  3485. } catch (...) {}
  3486. res.status = StatusCode::InternalServerError_500;
  3487. });
  3488. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3489. throw std::runtime_error("EXCEPTION");
  3490. });
  3491. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3492. res.set_content("ERROR", "text/html");
  3493. res.status = StatusCode::InternalServerError_500;
  3494. });
  3495. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3496. auto se = detail::scope_exit([&] {
  3497. svr.stop();
  3498. thread.join();
  3499. ASSERT_FALSE(svr.is_running());
  3500. });
  3501. svr.wait_until_ready();
  3502. Client cli(HOST, PORT);
  3503. {
  3504. auto res = cli.Get("/exception");
  3505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3506. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3507. EXPECT_EQ("EXCEPTION", res->body);
  3508. }
  3509. {
  3510. auto res = cli.Get("/error");
  3511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3512. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3513. EXPECT_EQ("ERROR", res->body);
  3514. }
  3515. {
  3516. auto res = cli.Get("/invalid");
  3517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3518. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3519. EXPECT_EQ("NOT_FOUND", res->body);
  3520. }
  3521. }
  3522. #endif
  3523. TEST(NoContentTest, ContentLength) {
  3524. Server svr;
  3525. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3526. res.status = StatusCode::NoContent_204;
  3527. });
  3528. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3529. auto se = detail::scope_exit([&] {
  3530. svr.stop();
  3531. thread.join();
  3532. ASSERT_FALSE(svr.is_running());
  3533. });
  3534. svr.wait_until_ready();
  3535. {
  3536. Client cli(HOST, PORT);
  3537. auto res = cli.Get("/hi");
  3538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3539. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3540. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3541. }
  3542. }
  3543. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3544. #ifdef CPPHTTPLIB_SSL_ENABLED
  3545. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3546. ASSERT_TRUE(svr.is_valid());
  3547. #else
  3548. Server svr;
  3549. #endif
  3550. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3551. if (req.path == "/routing_handler") {
  3552. res.set_header("PRE_ROUTING", "on");
  3553. res.set_content("Routing Handler", "text/plain");
  3554. return httplib::Server::HandlerResponse::Handled;
  3555. }
  3556. return httplib::Server::HandlerResponse::Unhandled;
  3557. });
  3558. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3559. res.set_content("Error", "text/html");
  3560. });
  3561. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3562. if (req.path == "/routing_handler") {
  3563. res.set_header("POST_ROUTING", "on");
  3564. }
  3565. });
  3566. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3567. res.set_content("Hello World!\n", "text/plain");
  3568. });
  3569. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3570. auto se = detail::scope_exit([&] {
  3571. svr.stop();
  3572. thread.join();
  3573. ASSERT_FALSE(svr.is_running());
  3574. });
  3575. svr.wait_until_ready();
  3576. {
  3577. #ifdef CPPHTTPLIB_SSL_ENABLED
  3578. SSLClient cli(HOST, PORT);
  3579. cli.enable_server_certificate_verification(false);
  3580. #else
  3581. Client cli(HOST, PORT);
  3582. #endif
  3583. auto res = cli.Get("/routing_handler");
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ(StatusCode::OK_200, res->status);
  3586. EXPECT_EQ("Routing Handler", res->body);
  3587. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3588. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3589. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3590. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3591. }
  3592. {
  3593. #ifdef CPPHTTPLIB_SSL_ENABLED
  3594. SSLClient cli(HOST, PORT);
  3595. cli.enable_server_certificate_verification(false);
  3596. #else
  3597. Client cli(HOST, PORT);
  3598. #endif
  3599. auto res = cli.Get("/hi");
  3600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3601. EXPECT_EQ(StatusCode::OK_200, res->status);
  3602. EXPECT_EQ("Hello World!\n", res->body);
  3603. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3604. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3605. }
  3606. {
  3607. #ifdef CPPHTTPLIB_SSL_ENABLED
  3608. SSLClient cli(HOST, PORT);
  3609. cli.enable_server_certificate_verification(false);
  3610. #else
  3611. Client cli(HOST, PORT);
  3612. #endif
  3613. auto res = cli.Get("/aaa");
  3614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3615. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3616. EXPECT_EQ("Error", res->body);
  3617. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3618. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3619. }
  3620. }
  3621. TEST(RequestHandlerTest, PreRequestHandler) {
  3622. auto route_path = "/user/:user";
  3623. Server svr;
  3624. svr.Get("/hi", [](const Request &, Response &res) {
  3625. res.set_content("hi", "text/plain");
  3626. });
  3627. svr.Get(route_path, [](const Request &req, Response &res) {
  3628. res.set_content(req.path_params.at("user"), "text/plain");
  3629. });
  3630. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3631. if (req.matched_route == route_path) {
  3632. auto user = req.path_params.at("user");
  3633. if (user != "john") {
  3634. res.status = StatusCode::Forbidden_403;
  3635. res.set_content("error", "text/html");
  3636. return Server::HandlerResponse::Handled;
  3637. }
  3638. }
  3639. return Server::HandlerResponse::Unhandled;
  3640. });
  3641. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3642. auto se = detail::scope_exit([&] {
  3643. svr.stop();
  3644. thread.join();
  3645. ASSERT_FALSE(svr.is_running());
  3646. });
  3647. svr.wait_until_ready();
  3648. Client cli(HOST, PORT);
  3649. {
  3650. auto res = cli.Get("/hi");
  3651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3652. EXPECT_EQ(StatusCode::OK_200, res->status);
  3653. EXPECT_EQ("hi", res->body);
  3654. }
  3655. {
  3656. auto res = cli.Get("/user/john");
  3657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3658. EXPECT_EQ(StatusCode::OK_200, res->status);
  3659. EXPECT_EQ("john", res->body);
  3660. }
  3661. {
  3662. auto res = cli.Get("/user/invalid-user");
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3665. EXPECT_EQ("error", res->body);
  3666. }
  3667. }
  3668. // The pre-request handler must run before the request body is read, so a
  3669. // rejected request never forces the server to buffer a (potentially large)
  3670. // body. Here the posted body is larger than the payload limit: if the body
  3671. // were read first the server would answer 413, but because the pre-request
  3672. // handler runs first it answers 403 and the body is never read.
  3673. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3674. Server svr;
  3675. svr.set_payload_max_length(8);
  3676. auto handler_ran = false;
  3677. svr.Post("/reject", [&](const Request &req, Response &res) {
  3678. handler_ran = true;
  3679. res.set_content(req.body, "text/plain");
  3680. });
  3681. svr.Post("/accept", [](const Request &req, Response &res) {
  3682. res.set_content(req.body, "text/plain");
  3683. });
  3684. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3685. if (req.matched_route == "/reject") {
  3686. res.status = StatusCode::Forbidden_403;
  3687. res.set_content("denied", "text/plain");
  3688. return Server::HandlerResponse::Handled;
  3689. }
  3690. return Server::HandlerResponse::Unhandled;
  3691. });
  3692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3693. auto se = detail::scope_exit([&] {
  3694. svr.stop();
  3695. thread.join();
  3696. ASSERT_FALSE(svr.is_running());
  3697. });
  3698. svr.wait_until_ready();
  3699. Client cli(HOST, PORT);
  3700. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3701. // rejects with 403 before the body is read, so 413 is never reached.
  3702. {
  3703. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3705. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3706. EXPECT_EQ("denied", res->body);
  3707. EXPECT_FALSE(handler_ran);
  3708. }
  3709. // An approved route still reads the body and enforces the payload limit.
  3710. {
  3711. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3713. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3714. }
  3715. }
  3716. TEST(UserDataTest, BasicOperations) {
  3717. httplib::UserData ud;
  3718. // Initially empty
  3719. EXPECT_FALSE(ud.has("key"));
  3720. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3721. // set and get
  3722. ud.set("key", 42);
  3723. EXPECT_TRUE(ud.has("key"));
  3724. auto *p = ud.get<int>("key");
  3725. ASSERT_NE(nullptr, p);
  3726. EXPECT_EQ(42, *p);
  3727. // Type mismatch → nullptr
  3728. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3729. // Overwrite with different type
  3730. ud.set("key", std::string("hello"));
  3731. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3732. auto *s = ud.get<std::string>("key");
  3733. ASSERT_NE(nullptr, s);
  3734. EXPECT_EQ("hello", *s);
  3735. // erase
  3736. ud.erase("key");
  3737. EXPECT_FALSE(ud.has("key"));
  3738. // clear
  3739. ud.set("a", 1);
  3740. ud.set("b", 2);
  3741. ud.clear();
  3742. EXPECT_FALSE(ud.has("a"));
  3743. EXPECT_FALSE(ud.has("b"));
  3744. }
  3745. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3746. struct AuthCtx {
  3747. std::string user_id;
  3748. };
  3749. Server svr;
  3750. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3751. res.user_data.set("auth", AuthCtx{"alice"});
  3752. return Server::HandlerResponse::Unhandled;
  3753. });
  3754. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3755. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3756. ASSERT_NE(nullptr, ctx);
  3757. res.set_content("Hello " + ctx->user_id, "text/plain");
  3758. });
  3759. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3760. auto se = detail::scope_exit([&] {
  3761. svr.stop();
  3762. thread.join();
  3763. ASSERT_FALSE(svr.is_running());
  3764. });
  3765. svr.wait_until_ready();
  3766. Client cli(HOST, PORT);
  3767. auto res = cli.Get("/me");
  3768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3769. EXPECT_EQ(StatusCode::OK_200, res->status);
  3770. EXPECT_EQ("Hello alice", res->body);
  3771. }
  3772. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3773. struct RoleCtx {
  3774. std::string role;
  3775. };
  3776. Server svr;
  3777. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3778. res.user_data.set("role", RoleCtx{"admin"});
  3779. return Server::HandlerResponse::Unhandled;
  3780. });
  3781. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3782. auto *ctx = res.user_data.get<RoleCtx>("role");
  3783. ASSERT_NE(nullptr, ctx);
  3784. res.set_content(ctx->role, "text/plain");
  3785. });
  3786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3787. auto se = detail::scope_exit([&] {
  3788. svr.stop();
  3789. thread.join();
  3790. ASSERT_FALSE(svr.is_running());
  3791. });
  3792. svr.wait_until_ready();
  3793. Client cli(HOST, PORT);
  3794. auto res = cli.Get("/role");
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. EXPECT_EQ("admin", res->body);
  3798. }
  3799. TEST(InvalidFormatTest, StatusCode) {
  3800. Server svr;
  3801. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3802. res.set_content("Hello World!\n", "text/plain");
  3803. res.status = 9999; // Status should be a three-digit code...
  3804. });
  3805. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3806. auto se = detail::scope_exit([&] {
  3807. svr.stop();
  3808. thread.join();
  3809. ASSERT_FALSE(svr.is_running());
  3810. });
  3811. svr.wait_until_ready();
  3812. {
  3813. Client cli(HOST, PORT);
  3814. auto res = cli.Get("/hi");
  3815. ASSERT_FALSE(res);
  3816. }
  3817. }
  3818. TEST(URLFragmentTest, WithFragment) {
  3819. Server svr;
  3820. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3821. EXPECT_TRUE(req.target == "/hi");
  3822. });
  3823. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3824. auto se = detail::scope_exit([&] {
  3825. svr.stop();
  3826. thread.join();
  3827. ASSERT_FALSE(svr.is_running());
  3828. });
  3829. svr.wait_until_ready();
  3830. {
  3831. Client cli(HOST, PORT);
  3832. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3833. EXPECT_TRUE(res);
  3834. EXPECT_EQ(StatusCode::OK_200, res->status);
  3835. res = cli.Get("/hi%23key1=val1=key2=val2");
  3836. EXPECT_TRUE(res);
  3837. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3838. }
  3839. }
  3840. TEST(HeaderWriter, SetHeaderWriter) {
  3841. Server svr;
  3842. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3843. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3844. return detail::write_headers(strm, hdrs);
  3845. });
  3846. svr.Get("/hi", [](const Request &req, Response &res) {
  3847. auto it = req.headers.find("CustomClientHeader");
  3848. EXPECT_TRUE(it != req.headers.end());
  3849. EXPECT_EQ(it->second, "CustomClientValue");
  3850. res.set_content("Hello World!\n", "text/plain");
  3851. });
  3852. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3853. auto se = detail::scope_exit([&] {
  3854. svr.stop();
  3855. thread.join();
  3856. ASSERT_FALSE(svr.is_running());
  3857. });
  3858. svr.wait_until_ready();
  3859. {
  3860. Client cli(HOST, PORT);
  3861. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3862. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3863. return detail::write_headers(strm, hdrs);
  3864. });
  3865. auto res = cli.Get("/hi");
  3866. EXPECT_TRUE(res);
  3867. EXPECT_EQ(StatusCode::OK_200, res->status);
  3868. auto it = res->headers.find("CustomServerHeader");
  3869. EXPECT_TRUE(it != res->headers.end());
  3870. EXPECT_EQ(it->second, "CustomServerValue");
  3871. }
  3872. }
  3873. class ServerTest : public ::testing::Test {
  3874. protected:
  3875. ServerTest()
  3876. : cli_(HOST, PORT)
  3877. #ifdef CPPHTTPLIB_SSL_ENABLED
  3878. ,
  3879. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3880. #endif
  3881. {
  3882. #ifdef CPPHTTPLIB_SSL_ENABLED
  3883. cli_.enable_server_certificate_verification(false);
  3884. #endif
  3885. // Allow LARGE_DATA (100MB) responses
  3886. cli_.set_payload_max_length(200 * 1024 * 1024);
  3887. }
  3888. virtual void SetUp() {
  3889. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3890. svr_.set_payload_max_length(200 * 1024 * 1024);
  3891. svr_.set_mount_point("/", "./www");
  3892. svr_.set_mount_point("/mount", "./www2");
  3893. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3894. svr_.Get("/hi",
  3895. [&](const Request & /*req*/, Response &res) {
  3896. res.set_content("Hello World!", "text/plain");
  3897. })
  3898. .Get("/file_content",
  3899. [&](const Request & /*req*/, Response &res) {
  3900. res.set_file_content("./www/dir/test.html");
  3901. })
  3902. .Get("/file_content_with_content_type",
  3903. [&](const Request & /*req*/, Response &res) {
  3904. res.set_file_content("./www/file", "text/plain");
  3905. })
  3906. .Get("/invalid_file_content",
  3907. [&](const Request & /*req*/, Response &res) {
  3908. res.set_file_content("./www/dir/invalid_file_path");
  3909. })
  3910. .Get("/http_response_splitting",
  3911. [&](const Request & /*req*/, Response &res) {
  3912. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3913. EXPECT_EQ(0U, res.headers.size());
  3914. EXPECT_FALSE(res.has_header("a"));
  3915. res.set_header("a", "1\nSet-Cookie: a=1");
  3916. EXPECT_EQ(0U, res.headers.size());
  3917. EXPECT_FALSE(res.has_header("a"));
  3918. res.set_header("a", "1\rSet-Cookie: a=1");
  3919. EXPECT_EQ(0U, res.headers.size());
  3920. EXPECT_FALSE(res.has_header("a"));
  3921. res.set_header("a\r\nb", "0");
  3922. EXPECT_EQ(0U, res.headers.size());
  3923. EXPECT_FALSE(res.has_header("a"));
  3924. res.set_header("a\rb", "0");
  3925. EXPECT_EQ(0U, res.headers.size());
  3926. EXPECT_FALSE(res.has_header("a"));
  3927. res.set_header("a\nb", "0");
  3928. EXPECT_EQ(0U, res.headers.size());
  3929. EXPECT_FALSE(res.has_header("a"));
  3930. res.set_redirect("1\r\nSet-Cookie: a=1");
  3931. EXPECT_EQ(0U, res.headers.size());
  3932. EXPECT_FALSE(res.has_header("Location"));
  3933. })
  3934. .Get("/slow",
  3935. [&](const Request & /*req*/, Response &res) {
  3936. std::this_thread::sleep_for(std::chrono::seconds(4));
  3937. res.set_content("slow", "text/plain");
  3938. })
  3939. #if 0
  3940. .Post("/slowpost",
  3941. [&](const Request & /*req*/, Response &res) {
  3942. std::this_thread::sleep_for(std::chrono::seconds(2));
  3943. res.set_content("slow", "text/plain");
  3944. })
  3945. #endif
  3946. .Get("/remote_addr",
  3947. [&](const Request &req, Response &res) {
  3948. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3949. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3950. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3951. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3952. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3953. #endif
  3954. res.set_content(req.remote_addr, "text/plain");
  3955. })
  3956. .Get("/local_addr",
  3957. [&](const Request &req, Response &res) {
  3958. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3959. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3960. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3961. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3962. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3963. #endif
  3964. auto local_addr = req.local_addr;
  3965. auto local_port = std::to_string(req.local_port);
  3966. res.set_content(local_addr.append(":").append(local_port),
  3967. "text/plain");
  3968. })
  3969. .Get("/endwith%",
  3970. [&](const Request & /*req*/, Response &res) {
  3971. res.set_content("Hello World!", "text/plain");
  3972. })
  3973. .Get("/a\\+\\+b",
  3974. [&](const Request &req, Response &res) {
  3975. ASSERT_TRUE(req.has_param("a +b"));
  3976. auto val = req.get_param_value("a +b");
  3977. res.set_content(val, "text/plain");
  3978. })
  3979. .Get("/", [&](const Request & /*req*/,
  3980. Response &res) { res.set_redirect("/hi"); })
  3981. .Post("/1",
  3982. [](const Request & /*req*/, Response &res) {
  3983. res.set_redirect("/2", StatusCode::SeeOther_303);
  3984. })
  3985. .Get("/2",
  3986. [](const Request & /*req*/, Response &res) {
  3987. res.set_content("redirected.", "text/plain");
  3988. res.status = StatusCode::OK_200;
  3989. })
  3990. .Post("/person",
  3991. [&](const Request &req, Response &res) {
  3992. if (req.has_param("name") && req.has_param("note")) {
  3993. persons_[req.get_param_value("name")] =
  3994. req.get_param_value("note");
  3995. } else {
  3996. res.status = StatusCode::BadRequest_400;
  3997. }
  3998. })
  3999. .Put("/person",
  4000. [&](const Request &req, Response &res) {
  4001. if (req.has_param("name") && req.has_param("note")) {
  4002. persons_[req.get_param_value("name")] =
  4003. req.get_param_value("note");
  4004. } else {
  4005. res.status = StatusCode::BadRequest_400;
  4006. }
  4007. })
  4008. .Get("/person/(.*)",
  4009. [&](const Request &req, Response &res) {
  4010. string name = req.matches[1];
  4011. if (persons_.find(name) != persons_.end()) {
  4012. auto note = persons_[name];
  4013. res.set_content(note, "text/plain");
  4014. } else {
  4015. res.status = StatusCode::NotFound_404;
  4016. }
  4017. })
  4018. .Delete("/person",
  4019. [&](const Request &req, Response &res) {
  4020. if (req.has_param("name")) {
  4021. string name = req.get_param_value("name");
  4022. if (persons_.find(name) != persons_.end()) {
  4023. persons_.erase(name);
  4024. res.set_content("DELETED", "text/plain");
  4025. } else {
  4026. res.status = StatusCode::NotFound_404;
  4027. }
  4028. } else {
  4029. res.status = StatusCode::BadRequest_400;
  4030. }
  4031. })
  4032. .Post("/x-www-form-urlencoded-json",
  4033. [&](const Request &req, Response &res) {
  4034. auto json = req.get_param_value("json");
  4035. ASSERT_EQ(JSON_DATA, json);
  4036. res.set_content(json, "appliation/json");
  4037. res.status = StatusCode::OK_200;
  4038. })
  4039. .Get("/streamed-chunked",
  4040. [&](const Request & /*req*/, Response &res) {
  4041. res.set_chunked_content_provider(
  4042. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4043. sink.os << "123";
  4044. sink.os << "456";
  4045. sink.os << "789";
  4046. sink.done();
  4047. return true;
  4048. });
  4049. })
  4050. .Get("/streamed-chunked-with-prohibited-trailer",
  4051. [&](const Request & /*req*/, Response &res) {
  4052. auto i = new int(0);
  4053. // Declare both a prohibited trailer (Content-Length) and an
  4054. // allowed one
  4055. res.set_header("Trailer", "Content-Length, X-Allowed");
  4056. res.set_chunked_content_provider(
  4057. "text/plain",
  4058. [i](size_t /*offset*/, DataSink &sink) {
  4059. switch (*i) {
  4060. case 0: sink.os << "123"; break;
  4061. case 1: sink.os << "456"; break;
  4062. case 2: sink.os << "789"; break;
  4063. case 3: {
  4064. sink.done_with_trailer(
  4065. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4066. } break;
  4067. }
  4068. (*i)++;
  4069. return true;
  4070. },
  4071. [i](bool success) {
  4072. EXPECT_TRUE(success);
  4073. delete i;
  4074. });
  4075. })
  4076. .Get("/streamed-chunked2",
  4077. [&](const Request & /*req*/, Response &res) {
  4078. auto i = new int(0);
  4079. res.set_chunked_content_provider(
  4080. "text/plain",
  4081. [i](size_t /*offset*/, DataSink &sink) {
  4082. switch (*i) {
  4083. case 0: sink.os << "123"; break;
  4084. case 1: sink.os << "456"; break;
  4085. case 2: sink.os << "789"; break;
  4086. case 3: sink.done(); break;
  4087. }
  4088. (*i)++;
  4089. return true;
  4090. },
  4091. [i](bool success) {
  4092. EXPECT_TRUE(success);
  4093. delete i;
  4094. });
  4095. })
  4096. .Get("/streamed-chunked-with-trailer",
  4097. [&](const Request & /*req*/, Response &res) {
  4098. auto i = new int(0);
  4099. res.set_header("Trailer", "Dummy1, Dummy2");
  4100. res.set_chunked_content_provider(
  4101. "text/plain",
  4102. [i](size_t /*offset*/, DataSink &sink) {
  4103. switch (*i) {
  4104. case 0: sink.os << "123"; break;
  4105. case 1: sink.os << "456"; break;
  4106. case 2: sink.os << "789"; break;
  4107. case 3: {
  4108. sink.done_with_trailer(
  4109. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4110. } break;
  4111. }
  4112. (*i)++;
  4113. return true;
  4114. },
  4115. [i](bool success) {
  4116. EXPECT_TRUE(success);
  4117. delete i;
  4118. });
  4119. })
  4120. .Get("/streamed",
  4121. [&](const Request & /*req*/, Response &res) {
  4122. res.set_content_provider(
  4123. 6, "text/plain",
  4124. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4125. sink.os << (offset < 3 ? "a" : "b");
  4126. return true;
  4127. });
  4128. })
  4129. .Get("/streamed-without-length",
  4130. [&](const Request & /*req*/, Response &res) {
  4131. auto data = new std::string("abcdefg");
  4132. res.set_content_provider(
  4133. "text/plain",
  4134. [data](size_t offset, DataSink &sink) {
  4135. if (offset < data->size()) {
  4136. sink.os << data->substr(offset);
  4137. }
  4138. sink.done();
  4139. return true;
  4140. },
  4141. [data](bool success) {
  4142. EXPECT_TRUE(success);
  4143. delete data;
  4144. });
  4145. })
  4146. .Get("/streamed-with-range",
  4147. [&](const Request &req, Response &res) {
  4148. auto data = new std::string("abcdefg");
  4149. // An explicit status keeps the server from picking the 206 it
  4150. // would otherwise choose for a ranged request, so the response
  4151. // is not a partial representation.
  4152. auto status = req.get_param_value("status");
  4153. if (status == "200") {
  4154. res.status = StatusCode::OK_200;
  4155. } else if (status == "403") {
  4156. res.status = StatusCode::Forbidden_403;
  4157. }
  4158. res.set_content_provider(
  4159. data->size(), "text/plain",
  4160. [data](size_t offset, size_t length, DataSink &sink) {
  4161. size_t DATA_CHUNK_SIZE = 4;
  4162. const auto &d = *data;
  4163. auto out_len =
  4164. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4165. auto ret =
  4166. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4167. EXPECT_TRUE(ret);
  4168. return true;
  4169. },
  4170. [data, &req](bool success) {
  4171. EXPECT_EQ(success, !req.has_param("error"));
  4172. delete data;
  4173. });
  4174. })
  4175. .Get("/streamed-cancel",
  4176. [&](const Request & /*req*/, Response &res) {
  4177. res.set_content_provider(
  4178. size_t(-1), "text/plain",
  4179. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4180. sink.os << "data_chunk";
  4181. return true;
  4182. });
  4183. })
  4184. .Get("/regex-with-delimiter",
  4185. [&](const Request &req, Response & /*res*/) {
  4186. ASSERT_TRUE(req.has_param("key"));
  4187. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4188. })
  4189. .Get("/with-range",
  4190. [&](const Request & /*req*/, Response &res) {
  4191. res.set_content("abcdefg", "text/plain");
  4192. })
  4193. .Get("/test-start-time",
  4194. [&](const Request &req, Response & /*res*/) {
  4195. EXPECT_NE(req.start_time_,
  4196. std::chrono::steady_clock::time_point::min());
  4197. })
  4198. .Get("/with-range-customized-response",
  4199. [&](const Request & /*req*/, Response &res) {
  4200. res.status = StatusCode::BadRequest_400;
  4201. res.set_content(JSON_DATA, "application/json");
  4202. })
  4203. .Post("/chunked",
  4204. [&](const Request &req, Response & /*res*/) {
  4205. EXPECT_EQ(req.body, "dechunked post body");
  4206. })
  4207. .Post("/large-chunked",
  4208. [&](const Request &req, Response & /*res*/) {
  4209. std::string expected(6 * 30 * 1024u, 'a');
  4210. EXPECT_EQ(req.body, expected);
  4211. })
  4212. .Post("/multipart",
  4213. [&](const Request &req, Response & /*res*/) {
  4214. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4215. req.form.get_field_count("text2") +
  4216. req.form.get_field_count("file3") +
  4217. req.form.get_field_count("file4"));
  4218. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4219. req.form.get_file_count("file2"));
  4220. ASSERT_TRUE(!req.form.has_file("???"));
  4221. ASSERT_TRUE(!req.form.has_field("???"));
  4222. ASSERT_TRUE(req.body.empty());
  4223. {
  4224. const auto &text = req.form.get_field("text1");
  4225. EXPECT_EQ("text default", text);
  4226. }
  4227. {
  4228. const auto &text = req.form.get_field("text2");
  4229. EXPECT_EQ("aωb", text);
  4230. }
  4231. {
  4232. const auto &file = req.form.get_file("file1");
  4233. EXPECT_EQ("hello.txt", file.filename);
  4234. EXPECT_EQ("text/plain", file.content_type);
  4235. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4236. }
  4237. {
  4238. const auto &file = req.form.get_file("file2");
  4239. EXPECT_EQ("world.json", file.filename);
  4240. EXPECT_EQ("application/json", file.content_type);
  4241. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4242. }
  4243. {
  4244. const auto &text = req.form.get_field("file3");
  4245. EXPECT_EQ(0u, text.size());
  4246. }
  4247. {
  4248. const auto &text = req.form.get_field("file4");
  4249. EXPECT_EQ(0u, text.size());
  4250. }
  4251. })
  4252. .Post("/multipart/multi_file_values",
  4253. [&](const Request &req, Response & /*res*/) {
  4254. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4255. req.form.get_field_count("multi_text1"));
  4256. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4257. ASSERT_TRUE(!req.form.has_file("???"));
  4258. ASSERT_TRUE(!req.form.has_field("???"));
  4259. ASSERT_TRUE(req.body.empty());
  4260. {
  4261. const auto &text = req.form.get_field("text");
  4262. EXPECT_EQ("default text", text);
  4263. }
  4264. {
  4265. const auto &text1_values = req.form.get_fields("multi_text1");
  4266. EXPECT_EQ(2u, text1_values.size());
  4267. EXPECT_EQ("aaaaa", text1_values[0]);
  4268. EXPECT_EQ("bbbbb", text1_values[1]);
  4269. }
  4270. {
  4271. const auto &file1_values = req.form.get_files("multi_file1");
  4272. EXPECT_EQ(2u, file1_values.size());
  4273. auto file1 = file1_values[0];
  4274. EXPECT_EQ(file1.filename, "hello.txt");
  4275. EXPECT_EQ(file1.content_type, "text/plain");
  4276. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4277. auto file2 = file1_values[1];
  4278. EXPECT_EQ(file2.filename, "world.json");
  4279. EXPECT_EQ(file2.content_type, "application/json");
  4280. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4281. }
  4282. })
  4283. .Post("/empty",
  4284. [&](const Request &req, Response &res) {
  4285. EXPECT_EQ(req.body, "");
  4286. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4287. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4288. res.set_content("empty", "text/plain");
  4289. })
  4290. .Post("/empty-no-content-type",
  4291. [&](const Request &req, Response &res) {
  4292. EXPECT_EQ(req.body, "");
  4293. EXPECT_FALSE(req.has_header("Content-Type"));
  4294. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4295. res.set_content("empty-no-content-type", "text/plain");
  4296. })
  4297. .Post("/path-only",
  4298. [&](const Request &req, Response &res) {
  4299. EXPECT_EQ(req.body, "");
  4300. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4301. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4302. res.set_content("path-only", "text/plain");
  4303. })
  4304. .Post("/path-headers-only",
  4305. [&](const Request &req, Response &res) {
  4306. EXPECT_EQ(req.body, "");
  4307. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4308. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4309. EXPECT_EQ("world", req.get_header_value("hello"));
  4310. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4311. res.set_content("path-headers-only", "text/plain");
  4312. })
  4313. .Post("/post-large",
  4314. [&](const Request &req, Response &res) {
  4315. EXPECT_EQ(req.body, LARGE_DATA);
  4316. res.set_content(req.body, "text/plain");
  4317. })
  4318. .Post("/post-loopback",
  4319. [&](const Request &, Response &res,
  4320. ContentReader const &content_reader) {
  4321. std::string body;
  4322. content_reader([&](const char *data, size_t data_length) {
  4323. body.append(data, data_length);
  4324. return true;
  4325. });
  4326. res.set_content(body, "text/plain");
  4327. })
  4328. .Put("/put-loopback",
  4329. [&](const Request &, Response &res,
  4330. ContentReader const &content_reader) {
  4331. std::string body;
  4332. content_reader([&](const char *data, size_t data_length) {
  4333. body.append(data, data_length);
  4334. return true;
  4335. });
  4336. res.set_content(body, "text/plain");
  4337. })
  4338. .Patch("/patch-loopback",
  4339. [&](const Request &, Response &res,
  4340. ContentReader const &content_reader) {
  4341. std::string body;
  4342. content_reader([&](const char *data, size_t data_length) {
  4343. body.append(data, data_length);
  4344. return true;
  4345. });
  4346. res.set_content(body, "text/plain");
  4347. })
  4348. .Put("/empty-no-content-type",
  4349. [&](const Request &req, Response &res) {
  4350. EXPECT_EQ(req.body, "");
  4351. EXPECT_FALSE(req.has_header("Content-Type"));
  4352. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4353. res.set_content("empty-no-content-type", "text/plain");
  4354. })
  4355. .Put("/put",
  4356. [&](const Request &req, Response &res) {
  4357. EXPECT_EQ(req.body, "PUT");
  4358. res.set_content(req.body, "text/plain");
  4359. })
  4360. .Put("/put-large",
  4361. [&](const Request &req, Response &res) {
  4362. EXPECT_EQ(req.body, LARGE_DATA);
  4363. res.set_content(req.body, "text/plain");
  4364. })
  4365. .Patch("/patch",
  4366. [&](const Request &req, Response &res) {
  4367. EXPECT_EQ(req.body, "PATCH");
  4368. res.set_content(req.body, "text/plain");
  4369. })
  4370. .Delete("/delete",
  4371. [&](const Request & /*req*/, Response &res) {
  4372. res.set_content("DELETE", "text/plain");
  4373. })
  4374. .Delete("/delete-body",
  4375. [&](const Request &req, Response &res) {
  4376. EXPECT_EQ(req.body, "content");
  4377. res.set_content(req.body, "text/plain");
  4378. })
  4379. .Options(R"(\*)",
  4380. [&](const Request & /*req*/, Response &res) {
  4381. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4382. })
  4383. .CustomRoute("PROPFIND", "/dav/:id",
  4384. [&](const Request &req, Response &res) {
  4385. res.set_header("x-body-size",
  4386. std::to_string(req.body.size()));
  4387. res.set_header("x-matched-route", req.matched_route);
  4388. res.set_header("x-dav-id", req.path_params.at("id"));
  4389. res.status = StatusCode::MultiStatus_207;
  4390. res.set_content(req.body, "application/xml");
  4391. })
  4392. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4393. [&](const Request &req, Response &res) {
  4394. res.set_header("x-dav-match", req.matches[1]);
  4395. res.status = StatusCode::MultiStatus_207;
  4396. })
  4397. .CustomRoute("MKCOL", "/dav-mkcol",
  4398. [&](const Request &req, Response &res) {
  4399. EXPECT_TRUE(req.body.empty());
  4400. res.status = StatusCode::Created_201;
  4401. })
  4402. .CustomRoute(
  4403. "REPORT", "/dav-report",
  4404. [&](const Request & /*req*/, Response &res,
  4405. const ContentReader &content_reader) {
  4406. std::string body;
  4407. content_reader([&](const char *data, size_t data_length) {
  4408. body.append(data, data_length);
  4409. return true;
  4410. });
  4411. res.set_header("x-body-size", std::to_string(body.size()));
  4412. res.status = StatusCode::MultiStatus_207;
  4413. res.set_content(body, "application/xml");
  4414. })
  4415. .Get("/request-target",
  4416. [&](const Request &req, Response & /*res*/) {
  4417. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4418. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4419. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4420. })
  4421. .Get("/long-query-value",
  4422. [&](const Request &req, Response & /*res*/) {
  4423. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4424. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4425. })
  4426. .Get("/too-long-query-value",
  4427. [&](const Request &req, Response & /*res*/) {
  4428. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4429. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4430. })
  4431. .Get("/array-param",
  4432. [&](const Request &req, Response & /*res*/) {
  4433. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4434. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4435. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4436. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4437. })
  4438. .Get("/array-param-values",
  4439. [&](const Request &req, Response & /*res*/) {
  4440. auto values = req.get_param_values("array");
  4441. EXPECT_EQ(3u, values.size());
  4442. EXPECT_EQ("value1", values[0]);
  4443. EXPECT_EQ("value2", values[1]);
  4444. EXPECT_EQ("value3", values[2]);
  4445. auto empty = req.get_param_values("nonexistent");
  4446. EXPECT_TRUE(empty.empty());
  4447. })
  4448. .Post("/validate-no-multiple-headers",
  4449. [&](const Request &req, Response & /*res*/) {
  4450. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4451. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4452. })
  4453. .Post("/content_receiver",
  4454. [&](const Request &req, Response &res,
  4455. const ContentReader &content_reader) {
  4456. if (req.is_multipart_form_data()) {
  4457. std::vector<FormData> items;
  4458. content_reader(
  4459. [&](const FormData &file) {
  4460. items.push_back(file);
  4461. return true;
  4462. },
  4463. [&](const char *data, size_t data_length) {
  4464. items.back().content.append(data, data_length);
  4465. return true;
  4466. });
  4467. EXPECT_EQ(5u, items.size());
  4468. {
  4469. const auto &file = get_file_value(items, "text1");
  4470. EXPECT_TRUE(file.filename.empty());
  4471. EXPECT_EQ("text default", file.content);
  4472. }
  4473. {
  4474. const auto &file = get_file_value(items, "text2");
  4475. EXPECT_TRUE(file.filename.empty());
  4476. EXPECT_EQ("aωb", file.content);
  4477. }
  4478. {
  4479. const auto &file = get_file_value(items, "file1");
  4480. EXPECT_EQ("hello.txt", file.filename);
  4481. EXPECT_EQ("text/plain", file.content_type);
  4482. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4483. }
  4484. {
  4485. const auto &file = get_file_value(items, "file2");
  4486. EXPECT_EQ("world.json", file.filename);
  4487. EXPECT_EQ("application/json", file.content_type);
  4488. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4489. }
  4490. {
  4491. const auto &file = get_file_value(items, "file3");
  4492. EXPECT_TRUE(file.filename.empty());
  4493. EXPECT_EQ("application/octet-stream", file.content_type);
  4494. EXPECT_EQ(0u, file.content.size());
  4495. }
  4496. } else {
  4497. std::string body;
  4498. content_reader([&](const char *data, size_t data_length) {
  4499. EXPECT_EQ(7U, data_length);
  4500. body.append(data, data_length);
  4501. return true;
  4502. });
  4503. EXPECT_EQ(body, "content");
  4504. res.set_content(body, "text/plain");
  4505. }
  4506. })
  4507. .Put("/content_receiver",
  4508. [&](const Request & /*req*/, Response &res,
  4509. const ContentReader &content_reader) {
  4510. std::string body;
  4511. content_reader([&](const char *data, size_t data_length) {
  4512. body.append(data, data_length);
  4513. return true;
  4514. });
  4515. EXPECT_EQ(body, "content");
  4516. res.set_content(body, "text/plain");
  4517. })
  4518. .Patch("/content_receiver",
  4519. [&](const Request & /*req*/, Response &res,
  4520. const ContentReader &content_reader) {
  4521. std::string body;
  4522. content_reader([&](const char *data, size_t data_length) {
  4523. body.append(data, data_length);
  4524. return true;
  4525. });
  4526. EXPECT_EQ(body, "content");
  4527. res.set_content(body, "text/plain");
  4528. })
  4529. .Post("/query-string-and-body",
  4530. [&](const Request &req, Response & /*res*/) {
  4531. ASSERT_TRUE(req.has_param("key"));
  4532. EXPECT_EQ(req.get_param_value("key"), "value");
  4533. EXPECT_EQ(req.body, "content");
  4534. })
  4535. .Get("/last-request",
  4536. [&](const Request &req, Response & /*res*/) {
  4537. EXPECT_EQ("close", req.get_header_value("Connection"));
  4538. })
  4539. .Get(R"(/redirect/(\d+))",
  4540. [&](const Request &req, Response &res) {
  4541. auto num = std::stoi(req.matches[1]) + 1;
  4542. std::string url = "/redirect/" + std::to_string(num);
  4543. res.set_redirect(url);
  4544. })
  4545. .Post("/binary",
  4546. [&](const Request &req, Response &res) {
  4547. EXPECT_EQ(4U, req.body.size());
  4548. EXPECT_EQ("application/octet-stream",
  4549. req.get_header_value("Content-Type"));
  4550. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4551. res.set_content(req.body, "application/octet-stream");
  4552. })
  4553. .Put("/binary",
  4554. [&](const Request &req, Response &res) {
  4555. EXPECT_EQ(4U, req.body.size());
  4556. EXPECT_EQ("application/octet-stream",
  4557. req.get_header_value("Content-Type"));
  4558. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4559. res.set_content(req.body, "application/octet-stream");
  4560. })
  4561. .Patch("/binary",
  4562. [&](const Request &req, Response &res) {
  4563. EXPECT_EQ(4U, req.body.size());
  4564. EXPECT_EQ("application/octet-stream",
  4565. req.get_header_value("Content-Type"));
  4566. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4567. res.set_content(req.body, "application/octet-stream");
  4568. })
  4569. .Delete("/binary",
  4570. [&](const Request &req, Response &res) {
  4571. EXPECT_EQ(4U, req.body.size());
  4572. EXPECT_EQ("application/octet-stream",
  4573. req.get_header_value("Content-Type"));
  4574. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4575. res.set_content(req.body, "application/octet-stream");
  4576. })
  4577. .Get("/issue1772",
  4578. [&](const Request & /*req*/, Response &res) {
  4579. res.status = 401;
  4580. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4581. })
  4582. .Delete("/issue609",
  4583. [](const httplib::Request &, httplib::Response &res,
  4584. const httplib::ContentReader &) {
  4585. res.set_content("ok", "text/plain");
  4586. })
  4587. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4588. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4589. .Get("/compress",
  4590. [&](const Request & /*req*/, Response &res) {
  4591. res.set_content(
  4592. "12345678901234567890123456789012345678901234567890123456789"
  4593. "01234567890123456789012345678901234567890",
  4594. "text/plain");
  4595. })
  4596. .Get("/compress-with-charset",
  4597. [&](const Request & /*req*/, Response &res) {
  4598. res.set_content(
  4599. "12345678901234567890123456789012345678901234567890123456789"
  4600. "01234567890123456789012345678901234567890",
  4601. "application/json; charset=utf-8");
  4602. })
  4603. .Get("/nocompress",
  4604. [&](const Request & /*req*/, Response &res) {
  4605. res.set_content(
  4606. "12345678901234567890123456789012345678901234567890123456789"
  4607. "01234567890123456789012345678901234567890",
  4608. "application/octet-stream");
  4609. })
  4610. .Post("/compress-multipart",
  4611. [&](const Request &req, Response & /*res*/) {
  4612. EXPECT_EQ(2u, req.form.fields.size());
  4613. ASSERT_TRUE(!req.form.has_field("???"));
  4614. {
  4615. const auto &text = req.form.get_field("key1");
  4616. EXPECT_EQ("test", text);
  4617. }
  4618. {
  4619. const auto &text = req.form.get_field("key2");
  4620. EXPECT_EQ("--abcdefg123", text);
  4621. }
  4622. })
  4623. #endif
  4624. ;
  4625. persons_["john"] = "programmer";
  4626. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4627. svr_.wait_until_ready();
  4628. }
  4629. virtual void TearDown() {
  4630. svr_.stop();
  4631. if (!request_threads_.empty()) {
  4632. std::this_thread::sleep_for(std::chrono::seconds(1));
  4633. for (auto &t : request_threads_) {
  4634. t.join();
  4635. }
  4636. }
  4637. t_.join();
  4638. }
  4639. map<string, string> persons_;
  4640. #ifdef CPPHTTPLIB_SSL_ENABLED
  4641. SSLClient cli_;
  4642. SSLServer svr_;
  4643. #else
  4644. Client cli_;
  4645. Server svr_;
  4646. #endif
  4647. thread t_;
  4648. std::vector<thread> request_threads_;
  4649. };
  4650. TEST_F(ServerTest, GetMethod200) {
  4651. auto res = cli_.Get("/hi");
  4652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4653. EXPECT_EQ("HTTP/1.1", res->version);
  4654. EXPECT_EQ(StatusCode::OK_200, res->status);
  4655. EXPECT_EQ("OK", res->reason);
  4656. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4657. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4658. EXPECT_EQ("Hello World!", res->body);
  4659. }
  4660. TEST_F(ServerTest, GetEmptyFile) {
  4661. auto res = cli_.Get("/empty_file");
  4662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4663. EXPECT_EQ(StatusCode::OK_200, res->status);
  4664. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4665. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4666. EXPECT_EQ("", res->body);
  4667. }
  4668. TEST_F(ServerTest, GetFileContent) {
  4669. auto res = cli_.Get("/file_content");
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. EXPECT_EQ(StatusCode::OK_200, res->status);
  4672. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4673. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4674. EXPECT_EQ("test.html", res->body);
  4675. }
  4676. TEST_F(ServerTest, GetFileContentWithRange) {
  4677. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4679. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4680. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4681. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4682. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4683. EXPECT_EQ("est", res->body);
  4684. }
  4685. TEST_F(ServerTest, GetFileContentWithContentType) {
  4686. auto res = cli_.Get("/file_content_with_content_type");
  4687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4688. EXPECT_EQ(StatusCode::OK_200, res->status);
  4689. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4690. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4691. EXPECT_EQ("file\n", res->body);
  4692. }
  4693. TEST_F(ServerTest, GetInvalidFileContent) {
  4694. auto res = cli_.Get("/invalid_file_content");
  4695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4696. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4697. }
  4698. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4699. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4701. EXPECT_EQ("HTTP/1.1", res->version);
  4702. EXPECT_EQ(StatusCode::OK_200, res->status);
  4703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4704. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4705. EXPECT_EQ("Hello World!", res->body);
  4706. }
  4707. TEST_F(ServerTest, GetMethod302) {
  4708. auto res = cli_.Get("/");
  4709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4710. EXPECT_EQ(StatusCode::Found_302, res->status);
  4711. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4712. }
  4713. TEST_F(ServerTest, GetMethod302Redirect) {
  4714. cli_.set_follow_location(true);
  4715. auto res = cli_.Get("/");
  4716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4717. EXPECT_EQ(StatusCode::OK_200, res->status);
  4718. EXPECT_EQ("Hello World!", res->body);
  4719. EXPECT_EQ("/hi", res->location);
  4720. }
  4721. TEST_F(ServerTest, GetMethod404) {
  4722. auto res = cli_.Get("/invalid");
  4723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4724. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4725. }
  4726. TEST_F(ServerTest, HeadMethod200) {
  4727. auto res = cli_.Head("/hi");
  4728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4731. EXPECT_TRUE(res->body.empty());
  4732. }
  4733. TEST_F(ServerTest, HeadMethod200Static) {
  4734. auto res = cli_.Head("/mount/dir/index.html");
  4735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4736. EXPECT_EQ(StatusCode::OK_200, res->status);
  4737. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4738. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4739. EXPECT_TRUE(res->body.empty());
  4740. }
  4741. TEST_F(ServerTest, HeadMethod404) {
  4742. auto res = cli_.Head("/invalid");
  4743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4744. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4745. EXPECT_TRUE(res->body.empty());
  4746. }
  4747. TEST_F(ServerTest, GetMethodPersonJohn) {
  4748. auto res = cli_.Get("/person/john");
  4749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4750. EXPECT_EQ(StatusCode::OK_200, res->status);
  4751. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4752. EXPECT_EQ("programmer", res->body);
  4753. }
  4754. TEST_F(ServerTest, PostMethod1) {
  4755. auto res = cli_.Get("/person/john1");
  4756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4757. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4758. res = cli_.Post("/person", "name=john1&note=coder",
  4759. "application/x-www-form-urlencoded");
  4760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4761. ASSERT_EQ(StatusCode::OK_200, res->status);
  4762. res = cli_.Get("/person/john1");
  4763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4764. ASSERT_EQ(StatusCode::OK_200, res->status);
  4765. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4766. ASSERT_EQ("coder", res->body);
  4767. }
  4768. TEST_F(ServerTest, PostMethod2) {
  4769. auto res = cli_.Get("/person/john2");
  4770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4771. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4772. Params params;
  4773. params.emplace("name", "john2");
  4774. params.emplace("note", "coder");
  4775. res = cli_.Post("/person", params);
  4776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4777. ASSERT_EQ(StatusCode::OK_200, res->status);
  4778. res = cli_.Get("/person/john2");
  4779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4780. ASSERT_EQ(StatusCode::OK_200, res->status);
  4781. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4782. ASSERT_EQ("coder", res->body);
  4783. }
  4784. TEST_F(ServerTest, PutMethod3) {
  4785. auto res = cli_.Get("/person/john3");
  4786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4787. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4788. Params params;
  4789. params.emplace("name", "john3");
  4790. params.emplace("note", "coder");
  4791. res = cli_.Put("/person", params);
  4792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4793. ASSERT_EQ(StatusCode::OK_200, res->status);
  4794. res = cli_.Get("/person/john3");
  4795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4796. ASSERT_EQ(StatusCode::OK_200, res->status);
  4797. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4798. ASSERT_EQ("coder", res->body);
  4799. }
  4800. TEST_F(ServerTest, DeleteMethod1) {
  4801. auto res = cli_.Get("/person/john4");
  4802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4803. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4804. Params params;
  4805. params.emplace("name", "john4");
  4806. params.emplace("note", "coder");
  4807. res = cli_.Post("/person", params);
  4808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4809. ASSERT_EQ(StatusCode::OK_200, res->status);
  4810. res = cli_.Get("/person/john4");
  4811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4812. ASSERT_EQ(StatusCode::OK_200, res->status);
  4813. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4814. ASSERT_EQ("coder", res->body);
  4815. Params delete_params;
  4816. delete_params.emplace("name", "john4");
  4817. res = cli_.Delete("/person", delete_params);
  4818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4819. ASSERT_EQ(StatusCode::OK_200, res->status);
  4820. ASSERT_EQ("DELETED", res->body);
  4821. res = cli_.Get("/person/john4");
  4822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4823. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4824. }
  4825. TEST_F(ServerTest, DeleteMethod2) {
  4826. auto res = cli_.Get("/person/john5");
  4827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4828. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4829. Params params;
  4830. params.emplace("name", "john5");
  4831. params.emplace("note", "developer");
  4832. res = cli_.Post("/person", params);
  4833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4834. ASSERT_EQ(StatusCode::OK_200, res->status);
  4835. res = cli_.Get("/person/john5");
  4836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4837. ASSERT_EQ(StatusCode::OK_200, res->status);
  4838. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4839. ASSERT_EQ("developer", res->body);
  4840. Params delete_params;
  4841. delete_params.emplace("name", "john5");
  4842. Headers headers;
  4843. headers.emplace("Custom-Header", "test-value");
  4844. res = cli_.Delete("/person", headers, delete_params);
  4845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4846. ASSERT_EQ(StatusCode::OK_200, res->status);
  4847. ASSERT_EQ("DELETED", res->body);
  4848. res = cli_.Get("/person/john5");
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4851. }
  4852. TEST_F(ServerTest, DeleteMethod3) {
  4853. auto res = cli_.Get("/person/john6");
  4854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4855. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4856. Params params;
  4857. params.emplace("name", "john6");
  4858. params.emplace("note", "tester");
  4859. res = cli_.Post("/person", params);
  4860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4861. ASSERT_EQ(StatusCode::OK_200, res->status);
  4862. res = cli_.Get("/person/john6");
  4863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4864. ASSERT_EQ(StatusCode::OK_200, res->status);
  4865. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4866. ASSERT_EQ("tester", res->body);
  4867. Params delete_params;
  4868. delete_params.emplace("name", "john6");
  4869. Headers headers;
  4870. headers.emplace("Custom-Header", "test-value");
  4871. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4873. ASSERT_EQ(StatusCode::OK_200, res->status);
  4874. ASSERT_EQ("DELETED", res->body);
  4875. res = cli_.Get("/person/john6");
  4876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4877. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4878. }
  4879. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4880. Params params;
  4881. params.emplace("json", JSON_DATA);
  4882. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4884. ASSERT_EQ(StatusCode::OK_200, res->status);
  4885. ASSERT_EQ(JSON_DATA, res->body);
  4886. }
  4887. TEST_F(ServerTest, PostEmptyContent) {
  4888. auto res = cli_.Post("/empty", "", "text/plain");
  4889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4890. ASSERT_EQ(StatusCode::OK_200, res->status);
  4891. ASSERT_EQ("empty", res->body);
  4892. }
  4893. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4894. auto res = cli_.Post("/empty-no-content-type");
  4895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4896. ASSERT_EQ(StatusCode::OK_200, res->status);
  4897. ASSERT_EQ("empty-no-content-type", res->body);
  4898. }
  4899. TEST_F(ServerTest, PostPathOnly) {
  4900. auto res = cli_.Post("/path-only");
  4901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4902. ASSERT_EQ(StatusCode::OK_200, res->status);
  4903. ASSERT_EQ("path-only", res->body);
  4904. }
  4905. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4906. auto res = cli_.Post("/path-headers-only",
  4907. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4909. ASSERT_EQ(StatusCode::OK_200, res->status);
  4910. ASSERT_EQ("path-headers-only", res->body);
  4911. }
  4912. TEST_F(ServerTest, PostLarge) {
  4913. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4915. ASSERT_EQ(StatusCode::OK_200, res->status);
  4916. EXPECT_EQ(LARGE_DATA, res->body);
  4917. }
  4918. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4919. auto res = cli_.Put("/empty-no-content-type");
  4920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4921. ASSERT_EQ(StatusCode::OK_200, res->status);
  4922. ASSERT_EQ("empty-no-content-type", res->body);
  4923. }
  4924. TEST_F(ServerTest, GetMethodDir) {
  4925. auto res = cli_.Get("/dir/");
  4926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4927. EXPECT_EQ(StatusCode::OK_200, res->status);
  4928. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4929. auto body = R"(<html>
  4930. <head>
  4931. </head>
  4932. <body>
  4933. <a href="/dir/test.html">Test</a>
  4934. <a href="/hi">hi</a>
  4935. </body>
  4936. </html>
  4937. )";
  4938. EXPECT_EQ(body, res->body);
  4939. }
  4940. TEST_F(ServerTest, GetMethodDirTest) {
  4941. auto res = cli_.Get("/dir/test.html");
  4942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4943. EXPECT_EQ(StatusCode::OK_200, res->status);
  4944. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4945. EXPECT_EQ("test.html", res->body);
  4946. }
  4947. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4948. auto res = cli_.Get("/dir/../dir/test.html");
  4949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4950. EXPECT_EQ(StatusCode::OK_200, res->status);
  4951. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4952. EXPECT_EQ("test.html", res->body);
  4953. }
  4954. TEST_F(ServerTest, GetMethodInvalidPath) {
  4955. auto res = cli_.Get("/dir/../test.html");
  4956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4957. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4958. }
  4959. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4960. auto res = cli_.Get("/../www/dir/test.html");
  4961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4962. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4963. }
  4964. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4965. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4967. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4968. }
  4969. TEST_F(ServerTest, GetMethodDirMountTest) {
  4970. auto res = cli_.Get("/mount/dir/test.html");
  4971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4972. EXPECT_EQ(StatusCode::OK_200, res->status);
  4973. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4974. EXPECT_EQ("test.html", res->body);
  4975. }
  4976. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4977. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4979. EXPECT_EQ(StatusCode::OK_200, res->status);
  4980. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4981. EXPECT_EQ("test.html", res->body);
  4982. }
  4983. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4984. auto res = cli_.Get("/mount/dir/../test.html");
  4985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4986. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4987. }
  4988. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4989. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4991. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4992. }
  4993. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4994. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4996. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4997. }
  4998. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4999. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5001. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5002. }
  5003. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5004. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5007. }
  5008. TEST_F(ServerTest, PostMethod303) {
  5009. auto res = cli_.Post("/1", "body", "text/plain");
  5010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5011. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5012. EXPECT_EQ("/2", res->get_header_value("Location"));
  5013. }
  5014. TEST_F(ServerTest, PostMethod303Redirect) {
  5015. cli_.set_follow_location(true);
  5016. auto res = cli_.Post("/1", "body", "text/plain");
  5017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5018. EXPECT_EQ(StatusCode::OK_200, res->status);
  5019. EXPECT_EQ("redirected.", res->body);
  5020. EXPECT_EQ("/2", res->location);
  5021. }
  5022. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5023. auto res = cli_.Get("/dir/test.abcde");
  5024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5025. EXPECT_EQ(StatusCode::OK_200, res->status);
  5026. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5027. EXPECT_EQ("abcde", res->body);
  5028. }
  5029. TEST_F(ServerTest, StaticFileRange) {
  5030. auto res =
  5031. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5033. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5034. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5035. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5036. EXPECT_EQ(true, res->has_header("Content-Range"));
  5037. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5038. EXPECT_EQ(std::string("cd"), res->body);
  5039. }
  5040. TEST_F(ServerTest, StaticFileRanges) {
  5041. auto res = cli_.Get("/dir/test.abcde",
  5042. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5044. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5045. EXPECT_TRUE(
  5046. res->get_header_value("Content-Type")
  5047. .find(
  5048. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5049. 0);
  5050. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5051. }
  5052. TEST_F(ServerTest, StaticFileRangeHead) {
  5053. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5055. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5056. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5057. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5058. EXPECT_EQ(true, res->has_header("Content-Range"));
  5059. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5060. }
  5061. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5062. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5065. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5066. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5067. EXPECT_EQ(true, res->has_header("Content-Range"));
  5068. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5069. res->get_header_value("Content-Range"));
  5070. EXPECT_EQ("LAST\n", res->body);
  5071. }
  5072. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5073. auto res =
  5074. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5078. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5079. EXPECT_EQ(true, res->has_header("Content-Range"));
  5080. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5081. }
  5082. TEST_F(ServerTest, StaticFileBigFile) {
  5083. auto res = cli_.Get("/dir/1MB.txt");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. EXPECT_EQ(StatusCode::OK_200, res->status);
  5086. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5087. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5088. }
  5089. TEST_F(ServerTest, InvalidBaseDirMount) {
  5090. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5091. }
  5092. TEST_F(ServerTest, Binary) {
  5093. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5094. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5095. "application/octet-stream");
  5096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5097. ASSERT_EQ(StatusCode::OK_200, res->status);
  5098. ASSERT_EQ(4U, res->body.size());
  5099. res = cli_.Put("/binary", binary.data(), binary.size(),
  5100. "application/octet-stream");
  5101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5102. ASSERT_EQ(StatusCode::OK_200, res->status);
  5103. ASSERT_EQ(4U, res->body.size());
  5104. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5105. "application/octet-stream");
  5106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5107. ASSERT_EQ(StatusCode::OK_200, res->status);
  5108. ASSERT_EQ(4U, res->body.size());
  5109. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5110. "application/octet-stream");
  5111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5112. ASSERT_EQ(StatusCode::OK_200, res->status);
  5113. ASSERT_EQ(4U, res->body.size());
  5114. }
  5115. TEST_F(ServerTest, BinaryString) {
  5116. auto binary = std::string("\x00\x01\x02\x03", 4);
  5117. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5119. ASSERT_EQ(StatusCode::OK_200, res->status);
  5120. ASSERT_EQ(4U, res->body.size());
  5121. res = cli_.Put("/binary", binary, "application/octet-stream");
  5122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5123. ASSERT_EQ(StatusCode::OK_200, res->status);
  5124. ASSERT_EQ(4U, res->body.size());
  5125. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5127. ASSERT_EQ(StatusCode::OK_200, res->status);
  5128. ASSERT_EQ(4U, res->body.size());
  5129. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5131. ASSERT_EQ(StatusCode::OK_200, res->status);
  5132. ASSERT_EQ(4U, res->body.size());
  5133. }
  5134. TEST_F(ServerTest, EmptyRequest) {
  5135. auto res = cli_.Get("");
  5136. ASSERT_TRUE(!res);
  5137. EXPECT_EQ(Error::Connection, res.error());
  5138. }
  5139. TEST_F(ServerTest, LongRequest) {
  5140. std::string request;
  5141. for (size_t i = 0; i < 545; i++) {
  5142. request += "/TooLongRequest";
  5143. }
  5144. request += "OK";
  5145. auto res = cli_.Get(request.c_str());
  5146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5147. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5148. }
  5149. TEST_F(ServerTest, TooLongRequest) {
  5150. std::string request;
  5151. for (size_t i = 0; i < 546; i++) {
  5152. request += "/TooLongRequest";
  5153. }
  5154. request += "_NG";
  5155. auto start = std::chrono::high_resolution_clock::now();
  5156. cli_.set_keep_alive(true);
  5157. auto res = cli_.Get(request.c_str());
  5158. auto end = std::chrono::high_resolution_clock::now();
  5159. auto elapsed =
  5160. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5161. .count();
  5162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5163. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5164. EXPECT_LE(elapsed, 1000);
  5165. EXPECT_EQ("close", res->get_header_value("Connection"));
  5166. EXPECT_FALSE(cli_.is_socket_open());
  5167. }
  5168. TEST_F(ServerTest, AlmostTooLongRequest) {
  5169. // test for #2046 - URI length check shouldn't include other content on req
  5170. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5171. // leading /, space, HTTP/1.1)
  5172. std::string request =
  5173. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5174. auto res = cli_.Get(request.c_str());
  5175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5176. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5177. }
  5178. TEST_F(ServerTest, LongHeader) {
  5179. Request req;
  5180. req.method = "GET";
  5181. req.path = "/hi";
  5182. std::string host_and_port;
  5183. host_and_port += HOST;
  5184. host_and_port += ":";
  5185. host_and_port += std::to_string(PORT);
  5186. req.headers.emplace("Host", host_and_port.c_str());
  5187. req.headers.emplace("Accept", "*/*");
  5188. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5189. req.headers.emplace(
  5190. "Header-Name",
  5191. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5192. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5193. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5194. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5219. "@@@@@@@@@@@@@@@@");
  5220. auto res = std::make_shared<Response>();
  5221. auto error = Error::Success;
  5222. auto ret = cli_.send(req, *res, error);
  5223. ASSERT_TRUE(ret);
  5224. EXPECT_EQ(StatusCode::OK_200, res->status);
  5225. }
  5226. TEST_F(ServerTest, LongQueryValue) {
  5227. auto start = std::chrono::high_resolution_clock::now();
  5228. cli_.set_keep_alive(true);
  5229. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5230. auto end = std::chrono::high_resolution_clock::now();
  5231. auto elapsed =
  5232. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5233. .count();
  5234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5235. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5236. EXPECT_LE(elapsed, 1000);
  5237. EXPECT_EQ("close", res->get_header_value("Connection"));
  5238. EXPECT_FALSE(cli_.is_socket_open());
  5239. }
  5240. TEST_F(ServerTest, TooLongQueryValue) {
  5241. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5242. ASSERT_FALSE(res);
  5243. EXPECT_EQ(Error::Read, res.error());
  5244. }
  5245. TEST_F(ServerTest, TooLongHeader) {
  5246. Request req;
  5247. req.method = "GET";
  5248. req.path = "/hi";
  5249. std::string host_and_port;
  5250. host_and_port += HOST;
  5251. host_and_port += ":";
  5252. host_and_port += std::to_string(PORT);
  5253. req.headers.emplace("Host", host_and_port.c_str());
  5254. req.headers.emplace("Accept", "*/*");
  5255. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5256. req.headers.emplace(
  5257. "Header-Name",
  5258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5273. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5274. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5275. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5276. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5277. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5278. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5284. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5285. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5286. "@@@@@@@@@@@@@@@@@");
  5287. auto res = std::make_shared<Response>();
  5288. auto error = Error::Success;
  5289. auto ret = cli_.send(req, *res, error);
  5290. ASSERT_TRUE(ret);
  5291. EXPECT_EQ(StatusCode::OK_200, res->status);
  5292. }
  5293. TEST_F(ServerTest, HeaderCountAtLimit) {
  5294. // Test with headers just under the 100 limit
  5295. httplib::Headers headers;
  5296. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5297. // This should keep us just under the 100 header limit
  5298. for (int i = 0; i < 95; i++) {
  5299. std::string name = "X-Test-Header-" + std::to_string(i);
  5300. std::string value = "value" + std::to_string(i);
  5301. headers.emplace(name, value);
  5302. }
  5303. // This should work fine as we're under the limit
  5304. auto res = cli_.Get("/hi", headers);
  5305. EXPECT_TRUE(res);
  5306. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5307. }
  5308. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5309. // Test with many headers to exceed the 100 limit
  5310. httplib::Headers headers;
  5311. // Add 150 headers to definitely exceed the 100 limit
  5312. for (int i = 0; i < 150; i++) {
  5313. std::string name = "X-Test-Header-" + std::to_string(i);
  5314. std::string value = "value" + std::to_string(i);
  5315. headers.emplace(name, value);
  5316. }
  5317. // This should fail due to exceeding header count limit
  5318. cli_.set_keep_alive(true);
  5319. auto res = cli_.Get("/hi", headers);
  5320. // The server should respond with 400 Bad Request
  5321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5322. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5323. EXPECT_EQ("close", res->get_header_value("Connection"));
  5324. EXPECT_FALSE(cli_.is_socket_open());
  5325. }
  5326. TEST_F(ServerTest, PercentEncoding) {
  5327. auto res = cli_.Get("/e%6edwith%");
  5328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5329. EXPECT_EQ(StatusCode::OK_200, res->status);
  5330. }
  5331. TEST_F(ServerTest, PercentEncodingUnicode) {
  5332. auto res = cli_.Get("/e%u006edwith%");
  5333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. }
  5336. TEST_F(ServerTest, InvalidPercentEncoding) {
  5337. auto res = cli_.Get("/%endwith%");
  5338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5340. }
  5341. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5342. auto res = cli_.Get("/%uendwith%");
  5343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5344. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5345. }
  5346. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5347. auto res = cli_.Get("/hello?aaa=bbb%");
  5348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5349. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5350. }
  5351. TEST_F(ServerTest, PlusSignEncoding) {
  5352. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5354. EXPECT_EQ(StatusCode::OK_200, res->status);
  5355. EXPECT_EQ("a +b", res->body);
  5356. }
  5357. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5358. // This test simulates a potential DoS attack using many headers
  5359. // to verify our security fix prevents memory exhaustion
  5360. httplib::Headers attack_headers;
  5361. // Attempt to add many headers like an attacker would (200 headers to far
  5362. // exceed limit)
  5363. for (int i = 0; i < 200; i++) {
  5364. std::string name = "X-Attack-Header-" + std::to_string(i);
  5365. std::string value = "attack_payload_" + std::to_string(i);
  5366. attack_headers.emplace(name, value);
  5367. }
  5368. // Try to POST with excessive headers
  5369. cli_.set_keep_alive(true);
  5370. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5371. // Should either fail or return 400 Bad Request due to security limit
  5372. if (res) {
  5373. // If we get a response, it should be 400 Bad Request
  5374. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5375. EXPECT_EQ("close", res->get_header_value("Connection"));
  5376. }
  5377. EXPECT_FALSE(cli_.is_socket_open());
  5378. }
  5379. TEST_F(ServerTest, MultipartFormData) {
  5380. UploadFormDataItems items = {
  5381. {"text1", "text default", "", ""},
  5382. {"text2", "aωb", "", ""},
  5383. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5384. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5385. {"file3", "", "", "application/octet-stream"},
  5386. {"file4", "", "", " application/json tmp-string "}};
  5387. auto res = cli_.Post("/multipart", items);
  5388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5389. EXPECT_EQ(StatusCode::OK_200, res->status);
  5390. }
  5391. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5392. UploadFormDataItems items = {
  5393. {"text", "default text", "", ""},
  5394. {"multi_text1", "aaaaa", "", ""},
  5395. {"multi_text1", "bbbbb", "", ""},
  5396. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5397. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5398. "application/json"},
  5399. };
  5400. auto res = cli_.Post("/multipart/multi_file_values", items);
  5401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5402. EXPECT_EQ(StatusCode::OK_200, res->status);
  5403. }
  5404. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5405. auto res = cli_.Get("/hi");
  5406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5407. EXPECT_EQ(StatusCode::OK_200, res->status);
  5408. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5409. EXPECT_EQ("Hello World!", res->body);
  5410. }
  5411. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5412. Request req;
  5413. req.method = "POST";
  5414. req.path = "/chunked";
  5415. std::string host_and_port;
  5416. host_and_port += HOST;
  5417. host_and_port += ":";
  5418. host_and_port += std::to_string(PORT);
  5419. req.headers.emplace("Host", host_and_port.c_str());
  5420. req.headers.emplace("Accept", "*/*");
  5421. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5422. req.headers.emplace("Content-Type", "text/plain");
  5423. req.headers.emplace("Content-Length", "0");
  5424. req.headers.emplace(
  5425. "Transfer-Encoding",
  5426. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5427. // Client does not chunk, so make a chunked body manually.
  5428. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5429. auto res = std::make_shared<Response>();
  5430. auto error = Error::Success;
  5431. auto ret = cli_.send(req, *res, error);
  5432. ASSERT_TRUE(ret);
  5433. EXPECT_EQ(StatusCode::OK_200, res->status);
  5434. }
  5435. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5436. // rather than treat them as valid lengths.
  5437. template <typename ClientT>
  5438. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5439. Request req;
  5440. req.method = "POST";
  5441. req.path = "/chunked";
  5442. std::string host_and_port;
  5443. host_and_port += HOST;
  5444. host_and_port += ":";
  5445. host_and_port += std::to_string(PORT);
  5446. req.headers.emplace("Host", host_and_port.c_str());
  5447. req.headers.emplace("Content-Length", "0");
  5448. req.headers.emplace("Transfer-Encoding", "chunked");
  5449. req.body = body;
  5450. auto res = std::make_shared<Response>();
  5451. auto error = Error::Success;
  5452. ASSERT_TRUE(cli.send(req, *res, error));
  5453. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5454. }
  5455. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5456. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5457. }
  5458. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5459. expect_chunked_body_rejected(
  5460. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5461. }
  5462. TEST_F(ServerTest, GetStreamed2) {
  5463. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5465. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5466. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5467. EXPECT_EQ(true, res->has_header("Content-Range"));
  5468. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5469. EXPECT_EQ(std::string("ab"), res->body);
  5470. }
  5471. TEST_F(ServerTest, GetStreamed) {
  5472. auto res = cli_.Get("/streamed");
  5473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5474. EXPECT_EQ(StatusCode::OK_200, res->status);
  5475. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5476. EXPECT_EQ(std::string("aaabbb"), res->body);
  5477. }
  5478. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5479. auto res = cli_.Get("/streamed-without-length",
  5480. Headers{make_range_header({{0, -1}})});
  5481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5482. EXPECT_EQ(StatusCode::OK_200, res->status);
  5483. EXPECT_EQ(false, res->has_header("Content-Length"));
  5484. EXPECT_EQ(false, res->has_header("Content-Range"));
  5485. EXPECT_EQ(std::string("abcdefg"), res->body);
  5486. }
  5487. TEST_F(ServerTest, GetStreamedWithRange1) {
  5488. auto res =
  5489. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5491. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5492. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5493. EXPECT_EQ(true, res->has_header("Content-Range"));
  5494. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5495. EXPECT_EQ(std::string("def"), res->body);
  5496. }
  5497. TEST_F(ServerTest, GetStreamedWithRange2) {
  5498. auto res =
  5499. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5501. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5502. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5503. EXPECT_EQ(true, res->has_header("Content-Range"));
  5504. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5505. EXPECT_EQ(std::string("bcdefg"), res->body);
  5506. }
  5507. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5508. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5510. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5511. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5512. EXPECT_EQ(true, res->has_header("Content-Range"));
  5513. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5514. EXPECT_EQ(std::string("efg"), res->body);
  5515. }
  5516. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5517. auto res =
  5518. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5520. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5521. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5522. EXPECT_EQ(false, res->has_header("Content-Range"));
  5523. EXPECT_EQ(0U, res->body.size());
  5524. }
  5525. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5526. // Only a 206 is served as a partial representation. Under any other status
  5527. // `apply_ranges()` reported the full content length, so the body must match
  5528. // that header, and the content provider must never be asked for an offset
  5529. // outside the representation.
  5530. auto check = [&](int status, const char *range) {
  5531. auto path =
  5532. std::string("/streamed-with-range?status=") + std::to_string(status);
  5533. auto ctx = path + " Range: " + range;
  5534. auto res = cli_.Get(path, Headers{{"Range", range}});
  5535. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5536. EXPECT_EQ(status, res->status) << ctx;
  5537. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5538. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5539. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5540. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5541. };
  5542. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5543. check(403, "bytes=3-5");
  5544. // The offset is far past the representation.
  5545. check(403, "bytes=100000-100200");
  5546. // `first_pos` is still -1 here, and the bounds asserts in
  5547. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5548. check(403, "bytes=-3");
  5549. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5550. // multipart branch would have written one that is empty.
  5551. check(403, "bytes=1-2, 4-5");
  5552. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5553. // covers the whole representation.
  5554. check(200, "bytes=3-5");
  5555. check(200, "bytes=1-2, 4-5");
  5556. }
  5557. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5558. auto res =
  5559. cli_.Get("/streamed-with-range",
  5560. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5561. "92233720368547758079223372036854775807"}});
  5562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5563. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5564. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5565. EXPECT_EQ(false, res->has_header("Content-Range"));
  5566. EXPECT_EQ(0U, res->body.size());
  5567. }
  5568. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5569. auto res = cli_.Get(
  5570. "/with-range",
  5571. Headers{{"Range",
  5572. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5573. {"Accept-Encoding", ""}});
  5574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5576. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5577. EXPECT_EQ(true, res->has_header("Content-Range"));
  5578. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5579. EXPECT_EQ(std::string("abcdefg"), res->body);
  5580. }
  5581. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5582. auto res = cli_.Get("/with-range", Headers{
  5583. {"Range", "bytes=0-"},
  5584. {"Accept-Encoding", ""},
  5585. });
  5586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5587. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5588. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5589. EXPECT_EQ(true, res->has_header("Content-Range"));
  5590. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5591. EXPECT_EQ(std::string("abcdefg"), res->body);
  5592. }
  5593. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5594. auto res = cli_.Get("/streamed-with-range",
  5595. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5597. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5598. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5599. EXPECT_EQ(false, res->has_header("Content-Range"));
  5600. EXPECT_EQ(267U, res->body.size());
  5601. // Check that both range contents are present
  5602. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5603. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5604. // Check that Content-Range headers are present for both ranges
  5605. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5606. std::string::npos);
  5607. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5608. std::string::npos);
  5609. }
  5610. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5611. Ranges ranges;
  5612. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5613. ranges.emplace_back(0, -1);
  5614. }
  5615. auto res = cli_.Get("/streamed-with-range?error",
  5616. Headers{{make_range_header(ranges)}});
  5617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5618. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5619. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5620. EXPECT_EQ(false, res->has_header("Content-Range"));
  5621. EXPECT_EQ(0U, res->body.size());
  5622. }
  5623. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5624. auto res = cli_.Get("/streamed-with-range",
  5625. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5627. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5628. EXPECT_EQ(5U, res->body.size());
  5629. // Check that overlapping ranges are coalesced into a single range
  5630. EXPECT_EQ("bcdef", res->body);
  5631. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5632. // Should be single range, not multipart
  5633. EXPECT_TRUE(res->has_header("Content-Range"));
  5634. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5635. }
  5636. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5637. auto res = cli_.Get("/streamed-with-range",
  5638. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5640. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5641. EXPECT_EQ(268U, res->body.size());
  5642. // Check that both range contents are present
  5643. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5644. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5645. // Check that Content-Range headers are present for both ranges
  5646. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5647. std::string::npos);
  5648. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5649. std::string::npos);
  5650. }
  5651. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5652. auto res = cli_.Get("/streamed-with-range",
  5653. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5655. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5656. EXPECT_EQ(269U, res->body.size());
  5657. // Check that both duplicate range contents are present
  5658. size_t first_abc = res->body.find("abc\r\n");
  5659. EXPECT_TRUE(first_abc != std::string::npos);
  5660. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5661. EXPECT_TRUE(second_abc != std::string::npos);
  5662. // Check that Content-Range headers are present for both ranges
  5663. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5664. EXPECT_TRUE(first_range != std::string::npos);
  5665. size_t second_range =
  5666. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5667. EXPECT_TRUE(second_range != std::string::npos);
  5668. }
  5669. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5670. auto res =
  5671. cli_.Get("/streamed-with-range?error",
  5672. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5675. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5676. EXPECT_EQ(false, res->has_header("Content-Range"));
  5677. EXPECT_EQ(0U, res->body.size());
  5678. }
  5679. TEST_F(ServerTest, GetStreamedEndless) {
  5680. uint64_t offset = 0;
  5681. auto res = cli_.Get("/streamed-cancel",
  5682. [&](const char * /*data*/, uint64_t data_length) {
  5683. if (offset < 100) {
  5684. offset += data_length;
  5685. return true;
  5686. }
  5687. return false;
  5688. });
  5689. ASSERT_TRUE(!res);
  5690. EXPECT_EQ(Error::Canceled, res.error());
  5691. }
  5692. TEST_F(ServerTest, ClientStop) {
  5693. std::atomic_size_t count{4};
  5694. std::vector<std::thread> threads;
  5695. for (auto i = count.load(); i != 0; --i) {
  5696. threads.emplace_back([&]() {
  5697. auto res = cli_.Get("/streamed-cancel",
  5698. [&](const char *, uint64_t) { return true; });
  5699. --count;
  5700. ASSERT_TRUE(!res);
  5701. EXPECT_TRUE(res.error() == Error::Canceled ||
  5702. res.error() == Error::Read || res.error() == Error::Write);
  5703. });
  5704. }
  5705. std::this_thread::sleep_for(std::chrono::seconds(2));
  5706. while (count != 0) {
  5707. cli_.stop();
  5708. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5709. }
  5710. for (auto &t : threads) {
  5711. t.join();
  5712. }
  5713. }
  5714. TEST_F(ServerTest, GetWithRange1) {
  5715. auto res = cli_.Get("/with-range", Headers{
  5716. make_range_header({{3, 5}}),
  5717. {"Accept-Encoding", ""},
  5718. });
  5719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5720. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5721. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5722. EXPECT_EQ(true, res->has_header("Content-Range"));
  5723. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5724. EXPECT_EQ(std::string("def"), res->body);
  5725. }
  5726. TEST_F(ServerTest, GetWithRange2) {
  5727. auto res = cli_.Get("/with-range", Headers{
  5728. make_range_header({{1, -1}}),
  5729. {"Accept-Encoding", ""},
  5730. });
  5731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5732. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5733. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5734. EXPECT_EQ(true, res->has_header("Content-Range"));
  5735. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5736. EXPECT_EQ(std::string("bcdefg"), res->body);
  5737. }
  5738. TEST_F(ServerTest, GetWithRange3) {
  5739. auto res = cli_.Get("/with-range", Headers{
  5740. make_range_header({{0, 0}}),
  5741. {"Accept-Encoding", ""},
  5742. });
  5743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5744. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5745. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5746. EXPECT_EQ(true, res->has_header("Content-Range"));
  5747. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5748. EXPECT_EQ(std::string("a"), res->body);
  5749. }
  5750. TEST_F(ServerTest, GetWithRange4) {
  5751. auto res = cli_.Get("/with-range", Headers{
  5752. make_range_header({{-1, 2}}),
  5753. {"Accept-Encoding", ""},
  5754. });
  5755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5756. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5757. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5758. EXPECT_EQ(true, res->has_header("Content-Range"));
  5759. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5760. EXPECT_EQ(std::string("fg"), res->body);
  5761. }
  5762. TEST_F(ServerTest, GetWithRange5) {
  5763. auto res = cli_.Get("/with-range", Headers{
  5764. make_range_header({{0, 5}}),
  5765. {"Accept-Encoding", ""},
  5766. });
  5767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5768. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5769. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5770. EXPECT_EQ(true, res->has_header("Content-Range"));
  5771. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5772. EXPECT_EQ(std::string("abcdef"), res->body);
  5773. }
  5774. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5775. auto res =
  5776. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5778. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5779. }
  5780. TEST_F(ServerTest, GetWithRangeMultipart) {
  5781. auto res =
  5782. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5785. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5786. EXPECT_EQ(false, res->has_header("Content-Range"));
  5787. EXPECT_EQ(267U, res->body.size());
  5788. }
  5789. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5790. auto res = cli_.Get("/with-range",
  5791. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5793. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5794. }
  5795. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5796. auto res = cli_.Get("/with-range-customized-response",
  5797. Headers{{make_range_header({{1, 2}})}});
  5798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5799. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5800. EXPECT_EQ(true, res->has_header("Content-Length"));
  5801. EXPECT_EQ(false, res->has_header("Content-Range"));
  5802. EXPECT_EQ(JSON_DATA, res->body);
  5803. }
  5804. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5805. auto res = cli_.Get("/with-range-customized-response",
  5806. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5808. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5809. EXPECT_EQ(true, res->has_header("Content-Length"));
  5810. EXPECT_EQ(false, res->has_header("Content-Range"));
  5811. EXPECT_EQ(JSON_DATA, res->body);
  5812. }
  5813. TEST_F(ServerTest, Issue1772) {
  5814. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5817. }
  5818. TEST_F(ServerTest, Issue609) {
  5819. auto res = cli_.Delete("/issue609");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::OK_200, res->status);
  5822. EXPECT_EQ(std::string("ok"), res->body);
  5823. }
  5824. TEST_F(ServerTest, GetStreamedChunked) {
  5825. auto res = cli_.Get("/streamed-chunked");
  5826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5827. EXPECT_EQ(StatusCode::OK_200, res->status);
  5828. EXPECT_EQ(std::string("123456789"), res->body);
  5829. }
  5830. TEST_F(ServerTest, GetStreamedChunked2) {
  5831. auto res = cli_.Get("/streamed-chunked2");
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. EXPECT_EQ(StatusCode::OK_200, res->status);
  5834. EXPECT_EQ(std::string("123456789"), res->body);
  5835. }
  5836. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5837. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5839. EXPECT_EQ(StatusCode::OK_200, res->status);
  5840. EXPECT_EQ(std::string("123456789"), res->body);
  5841. EXPECT_TRUE(res->has_header("Trailer"));
  5842. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5843. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5844. // Trailers are now stored separately from headers (security fix)
  5845. EXPECT_EQ(2U, res->trailers.size());
  5846. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5847. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5848. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5849. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5850. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5851. // Verify trailers are NOT in headers (security verification)
  5852. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5853. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5854. }
  5855. TEST_F(ServerTest, LargeChunkedPost) {
  5856. Request req;
  5857. req.method = "POST";
  5858. req.path = "/large-chunked";
  5859. std::string host_and_port;
  5860. host_and_port += HOST;
  5861. host_and_port += ":";
  5862. host_and_port += std::to_string(PORT);
  5863. req.headers.emplace("Host", host_and_port.c_str());
  5864. req.headers.emplace("Accept", "*/*");
  5865. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5866. req.headers.emplace("Content-Type", "text/plain");
  5867. req.headers.emplace("Content-Length", "0");
  5868. req.headers.emplace("Transfer-Encoding", "chunked");
  5869. std::string long_string(30 * 1024u, 'a');
  5870. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5871. // Attempt to make a large enough post to exceed OS buffers, to test that
  5872. // the server handles short reads if the full chunk data isn't available.
  5873. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5874. auto res = std::make_shared<Response>();
  5875. auto error = Error::Success;
  5876. auto ret = cli_.send(req, *res, error);
  5877. ASSERT_TRUE(ret);
  5878. EXPECT_EQ(StatusCode::OK_200, res->status);
  5879. }
  5880. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5881. auto res = cli_.Get("/remote_addr");
  5882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5883. EXPECT_EQ(StatusCode::OK_200, res->status);
  5884. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5885. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5886. }
  5887. TEST_F(ServerTest, GetMethodLocalAddr) {
  5888. auto res = cli_.Get("/local_addr");
  5889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5890. EXPECT_EQ(StatusCode::OK_200, res->status);
  5891. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5892. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5893. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5894. }
  5895. TEST_F(ServerTest, HTTPResponseSplitting) {
  5896. auto res = cli_.Get("/http_response_splitting");
  5897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5898. EXPECT_EQ(StatusCode::OK_200, res->status);
  5899. }
  5900. TEST_F(ServerTest, SlowRequest) {
  5901. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5902. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5903. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5904. }
  5905. #if 0
  5906. TEST_F(ServerTest, SlowPost) {
  5907. char buffer[64 * 1024];
  5908. memset(buffer, 0x42, sizeof(buffer));
  5909. auto res = cli_.Post(
  5910. "/slowpost", 64 * 1024 * 1024,
  5911. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5912. auto ret = sink.write(buffer, sizeof(buffer));
  5913. EXPECT_TRUE(ret);
  5914. return true;
  5915. },
  5916. "text/plain");
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::OK_200, res->status);
  5919. }
  5920. TEST_F(ServerTest, SlowPostFail) {
  5921. char buffer[64 * 1024];
  5922. memset(buffer, 0x42, sizeof(buffer));
  5923. cli_.set_write_timeout(std::chrono::seconds(0));
  5924. auto res = cli_.Post(
  5925. "/slowpost", 64 * 1024 * 1024,
  5926. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5927. sink.write(buffer, sizeof(buffer));
  5928. return true;
  5929. },
  5930. "text/plain");
  5931. ASSERT_TRUE(!res);
  5932. EXPECT_EQ(Error::Write, res.error());
  5933. }
  5934. #endif
  5935. TEST_F(ServerTest, Put) {
  5936. auto res = cli_.Put("/put", "PUT", "text/plain");
  5937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5938. EXPECT_EQ(StatusCode::OK_200, res->status);
  5939. EXPECT_EQ("PUT", res->body);
  5940. }
  5941. TEST_F(ServerTest, PutWithContentProvider) {
  5942. auto res = cli_.Put(
  5943. "/put", 3,
  5944. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5945. sink.os << "PUT";
  5946. return true;
  5947. },
  5948. "text/plain");
  5949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5950. EXPECT_EQ(StatusCode::OK_200, res->status);
  5951. EXPECT_EQ("PUT", res->body);
  5952. }
  5953. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5954. auto res = cli_.Post(
  5955. "/post", 42,
  5956. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5957. return false;
  5958. },
  5959. "text/plain");
  5960. ASSERT_TRUE(!res);
  5961. EXPECT_EQ(Error::Canceled, res.error());
  5962. }
  5963. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5964. auto res = cli_.Put(
  5965. "/put",
  5966. [](size_t /*offset*/, DataSink &sink) {
  5967. sink.os << "PUT";
  5968. sink.done();
  5969. return true;
  5970. },
  5971. "text/plain");
  5972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5973. EXPECT_EQ(StatusCode::OK_200, res->status);
  5974. EXPECT_EQ("PUT", res->body);
  5975. }
  5976. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5977. auto res = cli_.Post(
  5978. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5979. "text/plain");
  5980. ASSERT_TRUE(!res);
  5981. EXPECT_EQ(Error::Canceled, res.error());
  5982. }
  5983. TEST_F(ServerTest, PostLoopBack) {
  5984. std::string body;
  5985. auto res = cli_.Post(
  5986. "/post-loopback", 9,
  5987. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5988. EXPECT_EQ(9u, length);
  5989. sink.write("123", 3);
  5990. sink.write("456", 3);
  5991. sink.write("789", 3);
  5992. return true;
  5993. },
  5994. "text/plain",
  5995. [&body](const char *data, size_t data_length) {
  5996. body.append(data, data_length);
  5997. return true;
  5998. });
  5999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. EXPECT_EQ("123456789", body);
  6002. }
  6003. TEST_F(ServerTest, PutLoopBack) {
  6004. std::string body;
  6005. auto res = cli_.Put(
  6006. "/put-loopback", 9,
  6007. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6008. EXPECT_EQ(9u, length);
  6009. sink.write("123", 3);
  6010. sink.write("456", 3);
  6011. sink.write("789", 3);
  6012. return true;
  6013. },
  6014. "text/plain",
  6015. [&body](const char *data, size_t data_length) {
  6016. body.append(data, data_length);
  6017. return true;
  6018. });
  6019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6020. EXPECT_EQ(StatusCode::OK_200, res->status);
  6021. EXPECT_EQ("123456789", body);
  6022. }
  6023. TEST_F(ServerTest, PatchLoopBack) {
  6024. std::string body;
  6025. auto res = cli_.Patch(
  6026. "/patch-loopback", 9,
  6027. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6028. EXPECT_EQ(9u, length);
  6029. sink.write("123", 3);
  6030. sink.write("456", 3);
  6031. sink.write("789", 3);
  6032. return true;
  6033. },
  6034. "text/plain",
  6035. [&body](const char *data, size_t data_length) {
  6036. body.append(data, data_length);
  6037. return true;
  6038. });
  6039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6040. EXPECT_EQ(StatusCode::OK_200, res->status);
  6041. EXPECT_EQ("123456789", body);
  6042. }
  6043. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6044. std::string body;
  6045. auto res = cli_.Post(
  6046. "/post-loopback",
  6047. [](size_t /*offset*/, DataSink &sink) {
  6048. sink.write("123", 3);
  6049. sink.write("456", 3);
  6050. sink.write("789", 3);
  6051. sink.done();
  6052. return true;
  6053. },
  6054. "text/plain",
  6055. [&body](const char *data, size_t data_length) {
  6056. body.append(data, data_length);
  6057. return true;
  6058. });
  6059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6060. EXPECT_EQ(StatusCode::OK_200, res->status);
  6061. EXPECT_EQ("123456789", body);
  6062. }
  6063. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6064. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6065. cli_.set_compress(true);
  6066. auto res = cli_.Put(
  6067. "/put", 3,
  6068. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6069. sink.os << "PUT";
  6070. return true;
  6071. },
  6072. "text/plain");
  6073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6074. EXPECT_EQ(StatusCode::OK_200, res->status);
  6075. EXPECT_EQ("PUT", res->body);
  6076. }
  6077. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6078. cli_.set_compress(true);
  6079. auto res = cli_.Post(
  6080. "/post", 42,
  6081. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6082. return false;
  6083. },
  6084. "text/plain");
  6085. ASSERT_TRUE(!res);
  6086. EXPECT_EQ(Error::Canceled, res.error());
  6087. }
  6088. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6089. cli_.set_compress(true);
  6090. auto res = cli_.Put(
  6091. "/put",
  6092. [](size_t /*offset*/, DataSink &sink) {
  6093. sink.os << "PUT";
  6094. sink.done();
  6095. return true;
  6096. },
  6097. "text/plain");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::OK_200, res->status);
  6100. EXPECT_EQ("PUT", res->body);
  6101. }
  6102. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6103. cli_.set_compress(true);
  6104. auto res = cli_.Post(
  6105. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6106. "text/plain");
  6107. ASSERT_TRUE(!res);
  6108. EXPECT_EQ(Error::Canceled, res.error());
  6109. }
  6110. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6111. cli_.set_compress(true);
  6112. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6114. EXPECT_EQ(StatusCode::OK_200, res->status);
  6115. EXPECT_EQ(LARGE_DATA, res->body);
  6116. }
  6117. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6118. #ifdef CPPHTTPLIB_SSL_ENABLED
  6119. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6120. Client cli(s.c_str());
  6121. cli.enable_server_certificate_verification(false);
  6122. #else
  6123. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6124. Client cli(s.c_str());
  6125. #endif
  6126. cli.set_compress(true);
  6127. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6129. EXPECT_EQ(StatusCode::OK_200, res->status);
  6130. EXPECT_EQ(LARGE_DATA, res->body);
  6131. // The compressed size should be less than a 10th of the original. May vary
  6132. // depending on the zlib library.
  6133. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6134. static_cast<uint64_t>(10 * 1024 * 1024));
  6135. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6136. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6137. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6138. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6139. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6140. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6141. #endif
  6142. }
  6143. TEST_F(ServerTest, PutContentWithDeflate) {
  6144. cli_.set_compress(false);
  6145. Headers headers;
  6146. headers.emplace("Content-Encoding", "deflate");
  6147. // PUT in deflate format:
  6148. auto res = cli_.Put("/put", headers,
  6149. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6151. EXPECT_EQ(StatusCode::OK_200, res->status);
  6152. EXPECT_EQ("PUT", res->body);
  6153. }
  6154. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6155. Headers headers;
  6156. headers.emplace("Accept-Encoding", "gzip, deflate");
  6157. auto res = cli_.Get("/streamed-chunked", headers);
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. EXPECT_EQ(StatusCode::OK_200, res->status);
  6160. EXPECT_EQ(std::string("123456789"), res->body);
  6161. }
  6162. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6163. Headers headers;
  6164. headers.emplace("Accept-Encoding", "gzip, deflate");
  6165. auto res = cli_.Get("/streamed-chunked2", headers);
  6166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6167. EXPECT_EQ(StatusCode::OK_200, res->status);
  6168. EXPECT_EQ(std::string("123456789"), res->body);
  6169. }
  6170. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6171. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6173. EXPECT_EQ(StatusCode::OK_200, res->status);
  6174. }
  6175. TEST(GzipDecompressor, ChunkedDecompression) {
  6176. std::string data;
  6177. for (size_t i = 0; i < 32 * 1024; ++i) {
  6178. data.push_back(static_cast<char>('a' + i % 26));
  6179. }
  6180. std::string compressed_data;
  6181. {
  6182. httplib::detail::gzip_compressor compressor;
  6183. bool result = compressor.compress(
  6184. data.data(), data.size(),
  6185. /*last=*/true,
  6186. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6187. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6188. compressed_data_size);
  6189. return true;
  6190. });
  6191. ASSERT_TRUE(result);
  6192. }
  6193. std::string decompressed_data;
  6194. {
  6195. httplib::detail::gzip_decompressor decompressor;
  6196. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6197. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6198. size_t chunk_size = 130;
  6199. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6200. chunk_begin += chunk_size) {
  6201. size_t current_chunk_size =
  6202. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6203. bool result = decompressor.decompress(
  6204. compressed_data.data() + chunk_begin, current_chunk_size,
  6205. [&](const char *decompressed_data_chunk,
  6206. size_t decompressed_data_chunk_size) {
  6207. decompressed_data.insert(decompressed_data.size(),
  6208. decompressed_data_chunk,
  6209. decompressed_data_chunk_size);
  6210. return true;
  6211. });
  6212. ASSERT_TRUE(result);
  6213. }
  6214. }
  6215. ASSERT_EQ(data, decompressed_data);
  6216. }
  6217. TEST(GzipDecompressor, DeflateDecompression) {
  6218. std::string original_text = "Raw deflate without gzip";
  6219. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6220. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6221. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6222. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6223. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6224. std::string decompressed_data;
  6225. {
  6226. httplib::detail::gzip_decompressor decompressor;
  6227. bool result = decompressor.decompress(
  6228. compressed_data.data(), compressed_data.size(),
  6229. [&](const char *decompressed_data_chunk,
  6230. size_t decompressed_data_chunk_size) {
  6231. decompressed_data.insert(decompressed_data.size(),
  6232. decompressed_data_chunk,
  6233. decompressed_data_chunk_size);
  6234. return true;
  6235. });
  6236. ASSERT_TRUE(result);
  6237. }
  6238. ASSERT_EQ(original_text, decompressed_data);
  6239. }
  6240. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6241. std::string original_text = "Raw deflate without gzip";
  6242. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6243. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6244. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6245. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6246. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6247. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6248. std::string decompressed_data;
  6249. {
  6250. httplib::detail::gzip_decompressor decompressor;
  6251. bool result = decompressor.decompress(
  6252. compressed_data.data(), compressed_data.size(),
  6253. [&](const char *decompressed_data_chunk,
  6254. size_t decompressed_data_chunk_size) {
  6255. decompressed_data.insert(decompressed_data.size(),
  6256. decompressed_data_chunk,
  6257. decompressed_data_chunk_size);
  6258. return true;
  6259. });
  6260. ASSERT_TRUE(result);
  6261. }
  6262. ASSERT_EQ(original_text, decompressed_data);
  6263. }
  6264. #endif
  6265. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6266. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6267. Headers headers;
  6268. headers.emplace("Accept-Encoding", "br");
  6269. auto res = cli_.Get("/streamed-chunked", headers);
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. EXPECT_EQ(StatusCode::OK_200, res->status);
  6272. EXPECT_EQ(std::string("123456789"), res->body);
  6273. }
  6274. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6275. Headers headers;
  6276. headers.emplace("Accept-Encoding", "br");
  6277. auto res = cli_.Get("/streamed-chunked2", headers);
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. EXPECT_EQ(StatusCode::OK_200, res->status);
  6280. EXPECT_EQ(std::string("123456789"), res->body);
  6281. }
  6282. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6283. cli_.set_compress(true);
  6284. auto res = cli_.Put(
  6285. "/put", 3,
  6286. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6287. sink.os << "PUT";
  6288. return true;
  6289. },
  6290. "text/plain");
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. EXPECT_EQ(StatusCode::OK_200, res->status);
  6293. EXPECT_EQ("PUT", res->body);
  6294. }
  6295. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6296. cli_.set_compress(true);
  6297. auto res = cli_.Put(
  6298. "/put",
  6299. [](size_t /*offset*/, DataSink &sink) {
  6300. sink.os << "PUT";
  6301. sink.done();
  6302. return true;
  6303. },
  6304. "text/plain");
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. EXPECT_EQ(StatusCode::OK_200, res->status);
  6307. EXPECT_EQ("PUT", res->body);
  6308. }
  6309. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6310. cli_.set_compress(true);
  6311. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::OK_200, res->status);
  6314. EXPECT_EQ(LARGE_DATA, res->body);
  6315. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6316. }
  6317. #endif
  6318. TEST_F(ServerTest, Patch) {
  6319. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6321. EXPECT_EQ(StatusCode::OK_200, res->status);
  6322. EXPECT_EQ("PATCH", res->body);
  6323. }
  6324. TEST_F(ServerTest, Delete) {
  6325. auto res = cli_.Delete("/delete");
  6326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6327. EXPECT_EQ(StatusCode::OK_200, res->status);
  6328. EXPECT_EQ("DELETE", res->body);
  6329. }
  6330. TEST_F(ServerTest, DeleteContentReceiver) {
  6331. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::OK_200, res->status);
  6334. EXPECT_EQ("content", res->body);
  6335. }
  6336. TEST_F(ServerTest, Options) {
  6337. auto res = cli_.Options("*");
  6338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6339. EXPECT_EQ(StatusCode::OK_200, res->status);
  6340. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6341. EXPECT_TRUE(res->body.empty());
  6342. }
  6343. TEST_F(ServerTest, URL) {
  6344. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6346. EXPECT_EQ(StatusCode::OK_200, res->status);
  6347. }
  6348. TEST_F(ServerTest, ArrayParam) {
  6349. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. EXPECT_EQ(StatusCode::OK_200, res->status);
  6352. }
  6353. TEST_F(ServerTest, ArrayParamValues) {
  6354. auto res =
  6355. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::OK_200, res->status);
  6358. }
  6359. TEST_F(ServerTest, NoMultipleHeaders) {
  6360. Headers headers = {{"Content-Length", "5"}};
  6361. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6362. "text/plain");
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. EXPECT_EQ(StatusCode::OK_200, res->status);
  6365. }
  6366. TEST_F(ServerTest, PostContentReceiver) {
  6367. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. ASSERT_EQ(StatusCode::OK_200, res->status);
  6370. ASSERT_EQ("content", res->body);
  6371. }
  6372. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6373. UploadFormDataItems items = {
  6374. {"text1", "text default", "", ""},
  6375. {"text2", "aωb", "", ""},
  6376. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6377. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6378. {"file3", "", "", "application/octet-stream"},
  6379. };
  6380. auto res = cli_.Post("/content_receiver", items);
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. EXPECT_EQ(StatusCode::OK_200, res->status);
  6383. }
  6384. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6385. UploadFormDataItems items = {
  6386. {"text1", "text default", "", ""},
  6387. {"text2", "aωb", "", ""},
  6388. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6389. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6390. {"file3", "", "", "application/octet-stream"},
  6391. };
  6392. auto boundary = std::string("+++++");
  6393. std::string body;
  6394. for (const auto &item : items) {
  6395. body += "--" + boundary + "\r\n";
  6396. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6397. if (!item.filename.empty()) {
  6398. body += "; filename=\"" + item.filename + "\"";
  6399. }
  6400. body += "\r\n";
  6401. if (!item.content_type.empty()) {
  6402. body += "Content-Type: " + item.content_type + "\r\n";
  6403. }
  6404. body += "\r\n";
  6405. body += item.content + "\r\n";
  6406. }
  6407. body += "--" + boundary + "--\r\n";
  6408. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6409. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. EXPECT_EQ(StatusCode::OK_200, res->status);
  6412. }
  6413. TEST(MultipartFormDataTest, FieldEscaping) {
  6414. Server svr;
  6415. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6416. const ContentReader &content_reader) {
  6417. ASSERT_TRUE(req.is_multipart_form_data());
  6418. std::vector<FormData> received;
  6419. content_reader(
  6420. [&](const FormData &file) {
  6421. received.push_back(file);
  6422. return true;
  6423. },
  6424. [&](const char *data, size_t data_length) {
  6425. received.back().content.append(data, data_length);
  6426. return true;
  6427. });
  6428. // '"', CR and LF in names and filenames are escaped following the
  6429. // WHATWG HTML standard, so each part still parses as a single part
  6430. // with no injected headers. Content types get CR/LF escaped too,
  6431. // while '"' (legal there, e.g. quoted charset) is preserved.
  6432. ASSERT_EQ(4U, received.size());
  6433. EXPECT_EQ("na%22me", received[0].name);
  6434. EXPECT_EQ("quoted name", received[0].content);
  6435. EXPECT_EQ("file", received[1].name);
  6436. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6437. received[1].filename);
  6438. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6439. EXPECT_EQ("injected", received[1].content);
  6440. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6441. EXPECT_EQ("my%22file.txt", received[2].filename);
  6442. EXPECT_EQ("cr lf name", received[2].content);
  6443. EXPECT_EQ("typed", received[3].name);
  6444. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6445. received[3].content_type);
  6446. EXPECT_EQ("typed content", received[3].content);
  6447. });
  6448. auto port = svr.bind_to_any_port("localhost");
  6449. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6450. auto se = detail::scope_exit([&] {
  6451. svr.stop();
  6452. t.join();
  6453. ASSERT_FALSE(svr.is_running());
  6454. });
  6455. svr.wait_until_ready();
  6456. Client cli("localhost", port);
  6457. UploadFormDataItems items = {
  6458. {"na\"me", "quoted name", "", ""},
  6459. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6460. "application/octet-stream"},
  6461. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6462. {"typed", "typed content", "",
  6463. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6464. };
  6465. auto res = cli.Post("/post", items);
  6466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6467. EXPECT_EQ(StatusCode::OK_200, res->status);
  6468. }
  6469. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6470. const UploadFormDataItems items = {
  6471. {"name1", "Content 1", "", ""},
  6472. {"name2", "Content 2", "file2.txt", "text/plain"},
  6473. };
  6474. Server svr;
  6475. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6476. const ContentReader &content_reader) {
  6477. ASSERT_TRUE(req.is_multipart_form_data());
  6478. std::vector<FormData> received;
  6479. content_reader(
  6480. [&](const FormData &file) {
  6481. received.push_back(file);
  6482. return true;
  6483. },
  6484. [&](const char *data, size_t data_length) {
  6485. received.back().content.append(data, data_length);
  6486. return true;
  6487. });
  6488. ASSERT_EQ(2U, received.size());
  6489. EXPECT_EQ("name1", received[0].name);
  6490. EXPECT_EQ("Content 1", received[0].content);
  6491. EXPECT_EQ("name2", received[1].name);
  6492. EXPECT_EQ("Content 2", received[1].content);
  6493. EXPECT_EQ("file2.txt", received[1].filename);
  6494. EXPECT_EQ("text/plain", received[1].content_type);
  6495. });
  6496. auto port = svr.bind_to_any_port("localhost");
  6497. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6498. auto se = detail::scope_exit([&] {
  6499. svr.stop();
  6500. t.join();
  6501. ASSERT_FALSE(svr.is_running());
  6502. });
  6503. svr.wait_until_ready();
  6504. Client cli("localhost", port);
  6505. // Whole-body serialization with a generated boundary
  6506. {
  6507. MultipartFormDataWriter writer;
  6508. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6509. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6510. writer.content_type());
  6511. auto body = writer.serialize(items);
  6512. EXPECT_EQ(body.size(), writer.content_length(items));
  6513. auto res = cli.Post("/post", body, writer.content_type());
  6514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6515. EXPECT_EQ(StatusCode::OK_200, res->status);
  6516. }
  6517. // Per-part framing with a custom boundary via a content provider
  6518. {
  6519. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6520. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6521. MultipartFormDataWriter writer("custom-boundary_123");
  6522. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6523. std::string body;
  6524. for (const auto &item : items) {
  6525. body += writer.item_begin(item);
  6526. body += item.content;
  6527. body += MultipartFormDataWriter::item_end();
  6528. }
  6529. body += writer.finish();
  6530. EXPECT_EQ(body.size(), writer.content_length(items));
  6531. auto res = cli.Post(
  6532. "/post", body.size(),
  6533. [&](size_t offset, size_t length, DataSink &sink) {
  6534. sink.write(body.data() + offset, length);
  6535. return true;
  6536. },
  6537. writer.content_type());
  6538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6539. EXPECT_EQ(StatusCode::OK_200, res->status);
  6540. }
  6541. }
  6542. TEST_F(ServerTest, PostContentReceiverGzip) {
  6543. cli_.set_compress(true);
  6544. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6546. ASSERT_EQ(StatusCode::OK_200, res->status);
  6547. ASSERT_EQ("content", res->body);
  6548. }
  6549. TEST_F(ServerTest, PutContentReceiver) {
  6550. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6552. ASSERT_EQ(StatusCode::OK_200, res->status);
  6553. ASSERT_EQ("content", res->body);
  6554. }
  6555. TEST_F(ServerTest, PatchContentReceiver) {
  6556. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6558. ASSERT_EQ(StatusCode::OK_200, res->status);
  6559. ASSERT_EQ("content", res->body);
  6560. }
  6561. template <typename ClientType>
  6562. void TestWithHeadersAndContentReceiver(
  6563. ClientType &cli,
  6564. std::function<Result(ClientType &, const std::string &, const Headers &,
  6565. const std::string &, const std::string &,
  6566. ContentReceiver, DownloadProgress)>
  6567. request_func) {
  6568. Headers headers;
  6569. headers.emplace("X-Custom-Header", "test-value");
  6570. std::string received_body;
  6571. auto res = request_func(
  6572. cli, "/content_receiver", headers, "content", "application/json",
  6573. [&](const char *data, size_t data_length) {
  6574. received_body.append(data, data_length);
  6575. return true;
  6576. },
  6577. nullptr);
  6578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6579. EXPECT_EQ(StatusCode::OK_200, res->status);
  6580. EXPECT_EQ("content", received_body);
  6581. }
  6582. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6583. #ifdef CPPHTTPLIB_SSL_ENABLED
  6584. using ClientT = SSLClient;
  6585. #else
  6586. using ClientT = Client;
  6587. #endif
  6588. TestWithHeadersAndContentReceiver<ClientT>(
  6589. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6590. const std::string &body, const std::string &content_type,
  6591. ContentReceiver receiver, DownloadProgress progress) {
  6592. return cli.Post(path, headers, body, content_type, receiver, progress);
  6593. });
  6594. }
  6595. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6596. #ifdef CPPHTTPLIB_SSL_ENABLED
  6597. using ClientT = SSLClient;
  6598. #else
  6599. using ClientT = Client;
  6600. #endif
  6601. TestWithHeadersAndContentReceiver<ClientT>(
  6602. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6603. const std::string &body, const std::string &content_type,
  6604. ContentReceiver receiver, DownloadProgress progress) {
  6605. return cli.Put(path, headers, body, content_type, receiver, progress);
  6606. });
  6607. }
  6608. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6609. #ifdef CPPHTTPLIB_SSL_ENABLED
  6610. using ClientT = SSLClient;
  6611. #else
  6612. using ClientT = Client;
  6613. #endif
  6614. TestWithHeadersAndContentReceiver<ClientT>(
  6615. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6616. const std::string &body, const std::string &content_type,
  6617. ContentReceiver receiver, DownloadProgress progress) {
  6618. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6619. });
  6620. }
  6621. template <typename ClientType>
  6622. void TestWithHeadersAndContentReceiverWithProgress(
  6623. ClientType &cli,
  6624. std::function<Result(ClientType &, const std::string &, const Headers &,
  6625. const std::string &, const std::string &,
  6626. ContentReceiver, DownloadProgress)>
  6627. request_func) {
  6628. Headers headers;
  6629. headers.emplace("X-Test-Header", "progress-test");
  6630. std::string received_body;
  6631. auto progress_called = false;
  6632. auto res = request_func(
  6633. cli, "/content_receiver", headers, "content", "text/plain",
  6634. [&](const char *data, size_t data_length) {
  6635. received_body.append(data, data_length);
  6636. return true;
  6637. },
  6638. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6639. progress_called = true;
  6640. return true;
  6641. });
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::OK_200, res->status);
  6644. EXPECT_EQ("content", received_body);
  6645. EXPECT_TRUE(progress_called);
  6646. }
  6647. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6648. #ifdef CPPHTTPLIB_SSL_ENABLED
  6649. using ClientT = SSLClient;
  6650. #else
  6651. using ClientT = Client;
  6652. #endif
  6653. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6654. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6655. const std::string &body, const std::string &content_type,
  6656. ContentReceiver receiver, DownloadProgress progress) {
  6657. return cli.Post(path, headers, body, content_type, receiver, progress);
  6658. });
  6659. }
  6660. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6661. #ifdef CPPHTTPLIB_SSL_ENABLED
  6662. using ClientT = SSLClient;
  6663. #else
  6664. using ClientT = Client;
  6665. #endif
  6666. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6667. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6668. const std::string &body, const std::string &content_type,
  6669. ContentReceiver receiver, DownloadProgress progress) {
  6670. return cli.Put(path, headers, body, content_type, receiver, progress);
  6671. });
  6672. }
  6673. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6674. #ifdef CPPHTTPLIB_SSL_ENABLED
  6675. using ClientT = SSLClient;
  6676. #else
  6677. using ClientT = Client;
  6678. #endif
  6679. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6680. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6681. const std::string &body, const std::string &content_type,
  6682. ContentReceiver receiver, DownloadProgress progress) {
  6683. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6684. });
  6685. }
  6686. template <typename ClientType>
  6687. void TestWithHeadersAndContentReceiverError(
  6688. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6689. const Headers &, const std::string &,
  6690. const std::string &, ContentReceiver)>
  6691. request_func) {
  6692. Headers headers;
  6693. headers.emplace("X-Error-Test", "true");
  6694. std::string received_body;
  6695. auto receiver_failed = false;
  6696. auto res =
  6697. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6698. [&](const char *data, size_t data_length) {
  6699. received_body.append(data, data_length);
  6700. receiver_failed = true;
  6701. return false;
  6702. });
  6703. ASSERT_FALSE(res);
  6704. EXPECT_TRUE(receiver_failed);
  6705. }
  6706. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6707. #ifdef CPPHTTPLIB_SSL_ENABLED
  6708. using ClientT = SSLClient;
  6709. #else
  6710. using ClientT = Client;
  6711. #endif
  6712. TestWithHeadersAndContentReceiverError<ClientT>(
  6713. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6714. const std::string &body, const std::string &content_type,
  6715. ContentReceiver receiver) {
  6716. return cli.Post(path, headers, body, content_type, receiver);
  6717. });
  6718. }
  6719. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6720. #ifdef CPPHTTPLIB_SSL_ENABLED
  6721. using ClientT = SSLClient;
  6722. #else
  6723. using ClientT = Client;
  6724. #endif
  6725. TestWithHeadersAndContentReceiverError<ClientT>(
  6726. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6727. const std::string &body, const std::string &content_type,
  6728. ContentReceiver receiver) {
  6729. return cli.Put(path, headers, body, content_type, receiver);
  6730. });
  6731. }
  6732. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6733. #ifdef CPPHTTPLIB_SSL_ENABLED
  6734. using ClientT = SSLClient;
  6735. #else
  6736. using ClientT = Client;
  6737. #endif
  6738. TestWithHeadersAndContentReceiverError<ClientT>(
  6739. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6740. const std::string &body, const std::string &content_type,
  6741. ContentReceiver receiver) {
  6742. return cli.Patch(path, headers, body, content_type, receiver);
  6743. });
  6744. }
  6745. TEST_F(ServerTest, PostQueryStringAndBody) {
  6746. auto res =
  6747. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6749. ASSERT_EQ(StatusCode::OK_200, res->status);
  6750. }
  6751. TEST_F(ServerTest, HTTP2Magic) {
  6752. Request req;
  6753. req.method = "PRI";
  6754. req.path = "*";
  6755. req.body = "SM";
  6756. auto res = std::make_shared<Response>();
  6757. auto error = Error::Success;
  6758. auto ret = cli_.send(req, *res, error);
  6759. ASSERT_TRUE(ret);
  6760. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6761. }
  6762. TEST_F(ServerTest, KeepAlive) {
  6763. auto res = cli_.Get("/hi");
  6764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6765. EXPECT_EQ(StatusCode::OK_200, res->status);
  6766. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6767. EXPECT_EQ("Hello World!", res->body);
  6768. res = cli_.Get("/hi");
  6769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6770. EXPECT_EQ(StatusCode::OK_200, res->status);
  6771. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6772. EXPECT_EQ("Hello World!", res->body);
  6773. res = cli_.Get("/hi");
  6774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6775. EXPECT_EQ(StatusCode::OK_200, res->status);
  6776. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6777. EXPECT_EQ("Hello World!", res->body);
  6778. res = cli_.Get("/not-exist");
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6781. res = cli_.Post("/empty", "", "text/plain");
  6782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6783. EXPECT_EQ(StatusCode::OK_200, res->status);
  6784. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6785. EXPECT_EQ("empty", res->body);
  6786. EXPECT_EQ("close", res->get_header_value("Connection"));
  6787. res = cli_.Post(
  6788. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6789. "text/plain");
  6790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6791. EXPECT_EQ(StatusCode::OK_200, res->status);
  6792. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6793. EXPECT_EQ("empty", res->body);
  6794. cli_.set_keep_alive(false);
  6795. res = cli_.Get("/last-request");
  6796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6797. EXPECT_EQ(StatusCode::OK_200, res->status);
  6798. EXPECT_EQ("close", res->get_header_value("Connection"));
  6799. }
  6800. TEST_F(ServerTest, TooManyRedirect) {
  6801. cli_.set_follow_location(true);
  6802. auto res = cli_.Get("/redirect/0");
  6803. ASSERT_TRUE(!res);
  6804. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6805. }
  6806. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6807. Request req;
  6808. req.method = "FOOBAR";
  6809. req.path = "/hi";
  6810. cli_.set_keep_alive(true);
  6811. auto res = cli_.send(req);
  6812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6813. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6814. EXPECT_EQ("close", res->get_header_value("Connection"));
  6815. EXPECT_FALSE(cli_.is_socket_open());
  6816. }
  6817. TEST_F(ServerTest, CustomRouteReadsBody) {
  6818. const std::string xml =
  6819. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  6820. Request req;
  6821. req.method = "PROPFIND";
  6822. req.path = "/dav/dir";
  6823. req.set_header("Depth", "1");
  6824. req.body = xml;
  6825. auto res = cli_.send(req);
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6828. EXPECT_EQ(xml, res->body);
  6829. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  6830. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  6831. }
  6832. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  6833. Request req;
  6834. req.method = "PROPFIND";
  6835. req.path = "/dav/42";
  6836. auto res = cli_.send(req);
  6837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6838. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6839. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  6840. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  6841. }
  6842. TEST_F(ServerTest, CustomRouteRegexPattern) {
  6843. Request req;
  6844. req.method = "PROPFIND";
  6845. req.path = "/dav-re/123";
  6846. auto res = cli_.send(req);
  6847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6848. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6849. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  6850. }
  6851. TEST_F(ServerTest, CustomRouteWithoutBody) {
  6852. Request req;
  6853. req.method = "MKCOL";
  6854. req.path = "/dav-mkcol";
  6855. auto res = cli_.send(req);
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. EXPECT_EQ(StatusCode::Created_201, res->status);
  6858. }
  6859. TEST_F(ServerTest, CustomRouteWithContentReader) {
  6860. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  6861. Request req;
  6862. req.method = "REPORT";
  6863. req.path = "/dav-report";
  6864. req.body = xml;
  6865. auto res = cli_.send(req);
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6868. EXPECT_EQ(xml, res->body);
  6869. }
  6870. // A content reader route must fire even when the request carries no body,
  6871. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  6872. // Without that, a body-less PROPFIND-style request would fall through to 404.
  6873. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  6874. Request req;
  6875. req.method = "REPORT";
  6876. req.path = "/dav-report";
  6877. auto res = cli_.send(req);
  6878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6879. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6880. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  6881. }
  6882. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  6883. Request req;
  6884. req.method = "PROPFIND";
  6885. req.path = "/not-dav";
  6886. auto res = cli_.send(req);
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6889. }
  6890. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  6891. Request req;
  6892. req.method = "UNLOCK";
  6893. req.path = "/dav/dir";
  6894. cli_.set_keep_alive(true);
  6895. auto res = cli_.send(req);
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6898. EXPECT_EQ("close", res->get_header_value("Connection"));
  6899. EXPECT_FALSE(cli_.is_socket_open());
  6900. }
  6901. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  6902. // The mount point serves this path, but only for GET and HEAD.
  6903. auto get_res = cli_.Get("/dir/index.html");
  6904. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  6905. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  6906. Request req;
  6907. req.method = "PROPFIND";
  6908. req.path = "/dir/index.html";
  6909. auto res = cli_.send(req);
  6910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6911. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6912. }
  6913. TEST_F(ServerTest, CustomRouteKeepAlive) {
  6914. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  6915. cli_.set_keep_alive(true);
  6916. for (auto i = 0; i < 2; i++) {
  6917. Request req;
  6918. req.method = "PROPFIND";
  6919. req.path = "/dav/dir";
  6920. req.body = xml;
  6921. auto res = cli_.send(req);
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6924. EXPECT_EQ(xml, res->body);
  6925. EXPECT_TRUE(cli_.is_socket_open());
  6926. }
  6927. // A built-in method must still be served on the same connection.
  6928. cli_.set_keep_alive(false);
  6929. auto res = cli_.Get("/hi");
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::OK_200, res->status);
  6932. EXPECT_EQ("close", res->get_header_value("Connection"));
  6933. }
  6934. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  6935. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  6936. Request req;
  6937. req.method = "PROPFIND";
  6938. req.path = "/dav/dir";
  6939. req.set_header("Expect", "100-continue");
  6940. req.body = xml;
  6941. auto res = cli_.send(req);
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  6944. EXPECT_EQ(xml, res->body);
  6945. }
  6946. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6947. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6948. TEST_F(ServerTest, Gzip) {
  6949. Headers headers;
  6950. headers.emplace("Accept-Encoding", "gzip, deflate");
  6951. auto res = cli_.Get("/compress", headers);
  6952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6953. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6954. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6955. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6956. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6957. "7890123456789012345678901234567890",
  6958. res->body);
  6959. EXPECT_EQ(StatusCode::OK_200, res->status);
  6960. }
  6961. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6962. Headers headers;
  6963. headers.emplace("Accept-Encoding", "gzip, deflate");
  6964. auto res = cli_.Get("/compress-with-charset", headers);
  6965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6966. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6967. EXPECT_EQ("application/json; charset=utf-8",
  6968. res->get_header_value("Content-Type"));
  6969. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6970. "7890123456789012345678901234567890",
  6971. res->body);
  6972. EXPECT_EQ(StatusCode::OK_200, res->status);
  6973. }
  6974. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6975. Headers headers;
  6976. headers.emplace("Accept-Encoding", "");
  6977. auto res = cli_.Get("/compress", headers);
  6978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6979. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6980. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6981. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6982. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6983. "7890123456789012345678901234567890",
  6984. res->body);
  6985. EXPECT_EQ(StatusCode::OK_200, res->status);
  6986. }
  6987. TEST_F(ServerTest, GzipWithContentReceiver) {
  6988. Headers headers;
  6989. headers.emplace("Accept-Encoding", "gzip, deflate");
  6990. std::string body;
  6991. auto res = cli_.Get("/compress", headers,
  6992. [&](const char *data, uint64_t data_length) {
  6993. EXPECT_EQ(100U, data_length);
  6994. body.append(data, data_length);
  6995. return true;
  6996. });
  6997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6998. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6999. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7000. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7001. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7002. "7890123456789012345678901234567890",
  7003. body);
  7004. EXPECT_EQ(StatusCode::OK_200, res->status);
  7005. }
  7006. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7007. Headers headers;
  7008. headers.emplace("Accept-Encoding", "gzip, deflate");
  7009. cli_.set_decompress(false);
  7010. auto res = cli_.Get("/compress", headers);
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7013. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7014. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7015. EXPECT_EQ(33U, res->body.size());
  7016. EXPECT_EQ(StatusCode::OK_200, res->status);
  7017. }
  7018. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7019. Headers headers;
  7020. headers.emplace("Accept-Encoding", "");
  7021. std::string body;
  7022. auto res = cli_.Get("/compress", headers,
  7023. [&](const char *data, uint64_t data_length) {
  7024. EXPECT_EQ(100U, data_length);
  7025. body.append(data, data_length);
  7026. return true;
  7027. });
  7028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7029. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7030. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7031. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7032. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7033. "7890123456789012345678901234567890",
  7034. body);
  7035. EXPECT_EQ(StatusCode::OK_200, res->status);
  7036. }
  7037. TEST_F(ServerTest, NoGzip) {
  7038. Headers headers;
  7039. headers.emplace("Accept-Encoding", "gzip, deflate");
  7040. auto res = cli_.Get("/nocompress", headers);
  7041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7042. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7043. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7044. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7045. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7046. "7890123456789012345678901234567890",
  7047. res->body);
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. }
  7050. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7051. Headers headers;
  7052. headers.emplace("Accept-Encoding", "gzip, deflate");
  7053. std::string body;
  7054. auto res = cli_.Get("/nocompress", headers,
  7055. [&](const char *data, uint64_t data_length) {
  7056. EXPECT_EQ(100U, data_length);
  7057. body.append(data, data_length);
  7058. return true;
  7059. });
  7060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7061. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7062. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7063. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7064. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7065. "7890123456789012345678901234567890",
  7066. body);
  7067. EXPECT_EQ(StatusCode::OK_200, res->status);
  7068. }
  7069. TEST_F(ServerTest, MultipartFormDataGzip) {
  7070. UploadFormDataItems items = {
  7071. {"key1", "test", "", ""},
  7072. {"key2", "--abcdefg123", "", ""},
  7073. };
  7074. cli_.set_compress(true);
  7075. auto res = cli_.Post("/compress-multipart", items);
  7076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7077. EXPECT_EQ(StatusCode::OK_200, res->status);
  7078. }
  7079. #endif
  7080. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7081. TEST_F(ServerTest, Brotli) {
  7082. Headers headers;
  7083. headers.emplace("Accept-Encoding", "br");
  7084. auto res = cli_.Get("/compress", headers);
  7085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7086. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7087. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7088. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7089. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7090. "7890123456789012345678901234567890",
  7091. res->body);
  7092. EXPECT_EQ(StatusCode::OK_200, res->status);
  7093. }
  7094. #endif
  7095. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7096. TEST_F(ServerTest, Zstd) {
  7097. Headers headers;
  7098. headers.emplace("Accept-Encoding", "zstd");
  7099. auto res = cli_.Get("/compress", headers);
  7100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7101. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7102. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7103. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7104. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7105. "7890123456789012345678901234567890",
  7106. res->body);
  7107. EXPECT_EQ(StatusCode::OK_200, res->status);
  7108. }
  7109. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7110. Headers headers;
  7111. headers.emplace("Accept-Encoding", "");
  7112. auto res = cli_.Get("/compress", headers);
  7113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7114. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7115. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7116. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7117. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7118. "7890123456789012345678901234567890",
  7119. res->body);
  7120. EXPECT_EQ(StatusCode::OK_200, res->status);
  7121. }
  7122. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7123. Headers headers;
  7124. headers.emplace("Accept-Encoding", "zstd");
  7125. std::string body;
  7126. auto res = cli_.Get("/compress", headers,
  7127. [&](const char *data, uint64_t data_length) {
  7128. EXPECT_EQ(100U, data_length);
  7129. body.append(data, data_length);
  7130. return true;
  7131. });
  7132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7133. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7134. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7135. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7136. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7137. "7890123456789012345678901234567890",
  7138. body);
  7139. EXPECT_EQ(StatusCode::OK_200, res->status);
  7140. }
  7141. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7142. Headers headers;
  7143. headers.emplace("Accept-Encoding", "zstd");
  7144. cli_.set_decompress(false);
  7145. auto res = cli_.Get("/compress", headers);
  7146. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7147. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7148. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7149. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7151. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7152. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7153. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7154. EXPECT_EQ(StatusCode::OK_200, res->status);
  7155. ASSERT_EQ(26U, res->body.size());
  7156. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7157. 0);
  7158. }
  7159. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7160. Headers headers;
  7161. headers.emplace("Accept-Encoding", "");
  7162. std::string body;
  7163. auto res = cli_.Get("/compress", headers,
  7164. [&](const char *data, uint64_t data_length) {
  7165. EXPECT_EQ(100U, data_length);
  7166. body.append(data, data_length);
  7167. return true;
  7168. });
  7169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7170. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7172. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7173. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7174. "7890123456789012345678901234567890",
  7175. body);
  7176. EXPECT_EQ(StatusCode::OK_200, res->status);
  7177. }
  7178. TEST_F(ServerTest, NoZstd) {
  7179. Headers headers;
  7180. headers.emplace("Accept-Encoding", "zstd");
  7181. auto res = cli_.Get("/nocompress", headers);
  7182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7183. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7184. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7185. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7186. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7187. "7890123456789012345678901234567890",
  7188. res->body);
  7189. EXPECT_EQ(StatusCode::OK_200, res->status);
  7190. }
  7191. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7192. Headers headers;
  7193. headers.emplace("Accept-Encoding", "zstd");
  7194. std::string body;
  7195. auto res = cli_.Get("/nocompress", headers,
  7196. [&](const char *data, uint64_t data_length) {
  7197. EXPECT_EQ(100U, data_length);
  7198. body.append(data, data_length);
  7199. return true;
  7200. });
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7203. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7204. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7205. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7206. "7890123456789012345678901234567890",
  7207. body);
  7208. EXPECT_EQ(StatusCode::OK_200, res->status);
  7209. }
  7210. // TODO: How to enable zstd ??
  7211. TEST_F(ServerTest, MultipartFormDataZstd) {
  7212. UploadFormDataItems items = {
  7213. {"key1", "test", "", ""},
  7214. {"key2", "--abcdefg123", "", ""},
  7215. };
  7216. Headers headers;
  7217. headers.emplace("Accept-Encoding", "zstd");
  7218. cli_.set_compress(true);
  7219. auto res = cli_.Post("/compress-multipart", headers, items);
  7220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7221. EXPECT_EQ(StatusCode::OK_200, res->status);
  7222. }
  7223. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7224. Headers headers;
  7225. headers.emplace("Accept-Encoding", "zstd");
  7226. cli_.set_compress(true);
  7227. auto res = cli_.Put(
  7228. "/put", headers, 3,
  7229. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7230. sink.os << "PUT";
  7231. return true;
  7232. },
  7233. "text/plain");
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::OK_200, res->status);
  7236. EXPECT_EQ("PUT", res->body);
  7237. }
  7238. // Pre-compression logging tests
  7239. TEST_F(ServerTest, PreCompressionLogging) {
  7240. // Test data for compression (matches the actual /compress endpoint content)
  7241. const std::string test_content =
  7242. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7243. "3456789012345678901234567890";
  7244. // Variables to capture logging data
  7245. std::string pre_compression_body;
  7246. std::string pre_compression_content_type;
  7247. std::string pre_compression_content_encoding;
  7248. std::string post_compression_body;
  7249. std::string post_compression_content_type;
  7250. std::string post_compression_content_encoding;
  7251. // Set up pre-compression logger
  7252. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7253. const Response &res) {
  7254. pre_compression_body = res.body;
  7255. pre_compression_content_type = res.get_header_value("Content-Type");
  7256. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7257. });
  7258. // Set up post-compression logger
  7259. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7260. post_compression_body = res.body;
  7261. post_compression_content_type = res.get_header_value("Content-Type");
  7262. post_compression_content_encoding =
  7263. res.get_header_value("Content-Encoding");
  7264. });
  7265. // Test with gzip compression
  7266. Headers headers;
  7267. headers.emplace("Accept-Encoding", "gzip");
  7268. auto res = cli_.Get("/compress", headers);
  7269. // Verify response was compressed
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7273. // Verify pre-compression logger captured uncompressed content
  7274. EXPECT_EQ(test_content, pre_compression_body);
  7275. EXPECT_EQ("text/plain", pre_compression_content_type);
  7276. EXPECT_TRUE(pre_compression_content_encoding
  7277. .empty()); // No encoding header before compression
  7278. // Verify post-compression logger captured compressed content
  7279. EXPECT_NE(test_content,
  7280. post_compression_body); // Should be different after compression
  7281. EXPECT_EQ("text/plain", post_compression_content_type);
  7282. EXPECT_EQ("gzip", post_compression_content_encoding);
  7283. // Verify compressed content is smaller
  7284. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7285. }
  7286. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7287. const std::string test_content =
  7288. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7289. "3456789012345678901234567890";
  7290. std::string pre_compression_body;
  7291. std::string post_compression_body;
  7292. svr_.set_pre_compression_logger(
  7293. [&](const Request & /*req*/, const Response &res) {
  7294. pre_compression_body = res.body;
  7295. });
  7296. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7297. post_compression_body = res.body;
  7298. });
  7299. Headers headers;
  7300. headers.emplace("Accept-Encoding", "br");
  7301. auto res = cli_.Get("/compress", headers);
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7305. // Verify pre-compression content is uncompressed
  7306. EXPECT_EQ(test_content, pre_compression_body);
  7307. // Verify post-compression content is compressed
  7308. EXPECT_NE(test_content, post_compression_body);
  7309. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7310. }
  7311. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7312. const std::string test_content =
  7313. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7314. "3456789012345678901234567890";
  7315. std::string pre_compression_body;
  7316. std::string post_compression_body;
  7317. svr_.set_pre_compression_logger(
  7318. [&](const Request & /*req*/, const Response &res) {
  7319. pre_compression_body = res.body;
  7320. });
  7321. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7322. post_compression_body = res.body;
  7323. });
  7324. // Request without compression (use /nocompress endpoint)
  7325. Headers headers;
  7326. auto res = cli_.Get("/nocompress", headers);
  7327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7328. EXPECT_EQ(StatusCode::OK_200, res->status);
  7329. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7330. // Pre-compression logger should not be called when no compression is applied
  7331. EXPECT_TRUE(
  7332. pre_compression_body.empty()); // Pre-compression logger not called
  7333. EXPECT_EQ(
  7334. test_content,
  7335. post_compression_body); // Post-compression logger captures final content
  7336. }
  7337. TEST_F(ServerTest, LoggerSeesContentLength) {
  7338. size_t logged_content_length = 0;
  7339. std::string logged_content_length_header;
  7340. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7341. logged_content_length = res.content_length_;
  7342. logged_content_length_header = res.get_header_value("Content-Length");
  7343. });
  7344. auto res = cli_.Get("/nocompress");
  7345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7346. EXPECT_EQ(StatusCode::OK_200, res->status);
  7347. EXPECT_EQ(res->body.size(), logged_content_length);
  7348. EXPECT_EQ(std::to_string(logged_content_length),
  7349. logged_content_length_header);
  7350. }
  7351. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7352. const std::string test_content =
  7353. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7354. "3456789012345678901234567890";
  7355. std::string pre_compression_body;
  7356. bool pre_logger_called = false;
  7357. // Set only pre-compression logger
  7358. svr_.set_pre_compression_logger(
  7359. [&](const Request & /*req*/, const Response &res) {
  7360. pre_compression_body = res.body;
  7361. pre_logger_called = true;
  7362. });
  7363. Headers headers;
  7364. headers.emplace("Accept-Encoding", "gzip");
  7365. auto res = cli_.Get("/compress", headers);
  7366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7367. EXPECT_EQ(StatusCode::OK_200, res->status);
  7368. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7369. // Verify pre-compression logger was called
  7370. EXPECT_TRUE(pre_logger_called);
  7371. EXPECT_EQ(test_content, pre_compression_body);
  7372. }
  7373. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7374. {
  7375. // Test with Expect: 100-continue header - success case
  7376. // Server returns 100 Continue, client sends body, server returns 200 OK
  7377. Request req;
  7378. req.method = "POST";
  7379. req.path = "/post-large";
  7380. req.set_header("Expect", "100-continue");
  7381. req.body = LARGE_DATA;
  7382. Response res;
  7383. auto error = Error::Success;
  7384. cli_.set_keep_alive(true);
  7385. auto ret = cli_.send(req, res, error);
  7386. EXPECT_TRUE(ret);
  7387. EXPECT_EQ(StatusCode::OK_200, res.status);
  7388. EXPECT_EQ(LARGE_DATA, res.body);
  7389. }
  7390. {
  7391. // Test with Expect: 100-continue header - error case
  7392. // Client should not send the body when server returns an error
  7393. Request req;
  7394. req.method = "POST";
  7395. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7396. req.set_header("Expect", "100-continue");
  7397. req.body = LARGE_DATA;
  7398. Response res;
  7399. auto error = Error::Success;
  7400. auto start = std::chrono::high_resolution_clock::now();
  7401. cli_.set_keep_alive(true);
  7402. auto ret = cli_.send(req, res, error);
  7403. auto end = std::chrono::high_resolution_clock::now();
  7404. auto elapsed =
  7405. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7406. .count();
  7407. // With Expect: 100-continue, request completes successfully but with error
  7408. EXPECT_TRUE(ret);
  7409. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7410. EXPECT_EQ("close", res.get_header_value("Connection"));
  7411. EXPECT_FALSE(cli_.is_socket_open());
  7412. EXPECT_LE(elapsed, 2000);
  7413. }
  7414. {
  7415. // Send an extra GET request to ensure error recovery without hanging
  7416. Request req;
  7417. req.method = "GET";
  7418. req.path = "/hi";
  7419. auto start = std::chrono::high_resolution_clock::now();
  7420. auto res = cli_.send(req);
  7421. auto end = std::chrono::high_resolution_clock::now();
  7422. auto elapsed =
  7423. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7424. .count();
  7425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7426. EXPECT_EQ(StatusCode::OK_200, res->status);
  7427. EXPECT_EQ("Hello World!", res->body);
  7428. EXPECT_LE(elapsed, 500);
  7429. }
  7430. }
  7431. TEST(ZstdDecompressor, ChunkedDecompression) {
  7432. std::string data;
  7433. for (size_t i = 0; i < 32 * 1024; ++i) {
  7434. data.push_back(static_cast<char>('a' + i % 26));
  7435. }
  7436. std::string compressed_data;
  7437. {
  7438. httplib::detail::zstd_compressor compressor;
  7439. bool result = compressor.compress(
  7440. data.data(), data.size(),
  7441. /*last=*/true,
  7442. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7443. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7444. compressed_data_size);
  7445. return true;
  7446. });
  7447. ASSERT_TRUE(result);
  7448. }
  7449. std::string decompressed_data;
  7450. {
  7451. httplib::detail::zstd_decompressor decompressor;
  7452. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7453. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7454. size_t chunk_size = 130;
  7455. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7456. chunk_begin += chunk_size) {
  7457. size_t current_chunk_size =
  7458. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7459. bool result = decompressor.decompress(
  7460. compressed_data.data() + chunk_begin, current_chunk_size,
  7461. [&](const char *decompressed_data_chunk,
  7462. size_t decompressed_data_chunk_size) {
  7463. decompressed_data.insert(decompressed_data.size(),
  7464. decompressed_data_chunk,
  7465. decompressed_data_chunk_size);
  7466. return true;
  7467. });
  7468. ASSERT_TRUE(result);
  7469. }
  7470. }
  7471. ASSERT_EQ(data, decompressed_data);
  7472. }
  7473. TEST(ZstdDecompressor, Decompress) {
  7474. std::string original_text = "Compressed with ZSTD";
  7475. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7476. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7477. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7478. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7479. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7480. std::string decompressed_data;
  7481. {
  7482. httplib::detail::zstd_decompressor decompressor;
  7483. bool result = decompressor.decompress(
  7484. compressed_data.data(), compressed_data.size(),
  7485. [&](const char *decompressed_data_chunk,
  7486. size_t decompressed_data_chunk_size) {
  7487. decompressed_data.insert(decompressed_data.size(),
  7488. decompressed_data_chunk,
  7489. decompressed_data_chunk_size);
  7490. return true;
  7491. });
  7492. ASSERT_TRUE(result);
  7493. }
  7494. ASSERT_EQ(original_text, decompressed_data);
  7495. }
  7496. #endif
  7497. // Sends a raw request to a server listening at HOST:PORT.
  7498. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7499. std::string *resp = nullptr, int port = PORT) {
  7500. auto error = Error::Success;
  7501. auto client_sock = detail::create_client_socket(
  7502. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7503. /*connection_timeout_sec=*/5, 0,
  7504. /*read_timeout_sec=*/5, 0,
  7505. /*write_timeout_sec=*/5, 0, std::string(), error);
  7506. if (client_sock == INVALID_SOCKET) { return false; }
  7507. auto ret = detail::process_client_socket(
  7508. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7509. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7510. if (req.size() !=
  7511. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7512. return false;
  7513. }
  7514. char buf[512];
  7515. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7516. while (line_reader.getline()) {
  7517. if (resp) { *resp += line_reader.ptr(); }
  7518. }
  7519. return true;
  7520. });
  7521. detail::close_socket(client_sock);
  7522. return ret;
  7523. }
  7524. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7525. Server svr;
  7526. std::string header_value;
  7527. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7528. header_value = req.get_header_value("foo");
  7529. res.set_content("ok", "text/plain");
  7530. });
  7531. thread t = thread([&] { svr.listen(HOST, PORT); });
  7532. auto se = detail::scope_exit([&] {
  7533. svr.stop();
  7534. t.join();
  7535. ASSERT_FALSE(svr.is_running());
  7536. });
  7537. svr.wait_until_ready();
  7538. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7539. // like characters are not treated the same - use vertical tab and escape.
  7540. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7541. "foo: \t \v bar \x1B\t \r\n"
  7542. "Connection: close\r\n"
  7543. "\r\n";
  7544. std::string res;
  7545. ASSERT_TRUE(send_request(5, req, &res));
  7546. EXPECT_EQ(header_value, "");
  7547. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7548. }
  7549. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7550. Server svr;
  7551. std::string received;
  7552. svr.Get("/order", [&](const Request &req, Response &res) {
  7553. received = entries_to_string(req.headers);
  7554. res.set_content("ok", "text/plain");
  7555. });
  7556. auto port = svr.bind_to_any_port(HOST);
  7557. thread t = thread([&] { svr.listen_after_bind(); });
  7558. auto se = detail::scope_exit([&] {
  7559. svr.stop();
  7560. t.join();
  7561. ASSERT_FALSE(svr.is_running());
  7562. });
  7563. svr.wait_until_ready();
  7564. const std::string req = "GET /order HTTP/1.1\r\n"
  7565. "X-First: 1\r\n"
  7566. "X-Dup: a\r\n"
  7567. "X-Second: 2\r\n"
  7568. "X-Dup: b\r\n"
  7569. "Connection: close\r\n"
  7570. "\r\n";
  7571. std::string res;
  7572. ASSERT_TRUE(send_request(5, req, &res, port));
  7573. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7574. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7575. }
  7576. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7577. Server svr;
  7578. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7579. res.set_header("Set-Cookie", "first=1");
  7580. res.set_header("X-Between", "y");
  7581. res.set_header("Set-Cookie", "second=2");
  7582. res.set_content("ok", "text/plain");
  7583. });
  7584. auto port = svr.bind_to_any_port(HOST);
  7585. thread t = thread([&] { svr.listen_after_bind(); });
  7586. auto se = detail::scope_exit([&] {
  7587. svr.stop();
  7588. t.join();
  7589. ASSERT_FALSE(svr.is_running());
  7590. });
  7591. svr.wait_until_ready();
  7592. Client cli(HOST, port);
  7593. auto res = cli.Get("/cookies");
  7594. ASSERT_TRUE(res);
  7595. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7596. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7597. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7598. }
  7599. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7600. Server svr;
  7601. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7602. auto i = new int(0);
  7603. res.set_header("Trailer", "X-Safe, X-Reflected");
  7604. res.set_chunked_content_provider(
  7605. "text/plain",
  7606. [i](size_t /*offset*/, DataSink &sink) {
  7607. if (*i == 0) {
  7608. sink.os << "body";
  7609. } else {
  7610. Headers trailer;
  7611. // A valid trailer that must survive.
  7612. trailer.emplace("X-Safe", "safe");
  7613. // Attacker-controlled value carrying CR/LF (response splitting).
  7614. trailer.emplace("X-Reflected",
  7615. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7616. // Attacker-controlled name carrying CR/LF.
  7617. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7618. sink.done_with_trailer(trailer);
  7619. }
  7620. (*i)++;
  7621. return true;
  7622. },
  7623. [i](bool /*success*/) { delete i; });
  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. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7633. "Host: " + HOST +
  7634. "\r\n"
  7635. "Connection: close\r\n"
  7636. "\r\n";
  7637. std::string res;
  7638. ASSERT_TRUE(send_request(5, req, &res));
  7639. // The injected fields must not appear anywhere in the raw response.
  7640. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7641. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7642. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7643. // Invalid trailers are dropped entirely, matching set_header().
  7644. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7645. // The valid trailer still passes through.
  7646. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7647. }
  7648. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7649. Server svr;
  7650. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7651. // res.headers is a public field an application can populate directly,
  7652. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7653. // A valid header that must survive.
  7654. res.headers.emplace("X-Safe", "safe");
  7655. // Attacker-controlled value carrying CR/LF (response splitting).
  7656. res.headers.emplace("X-Reflected",
  7657. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7658. // Attacker-controlled name carrying CR/LF.
  7659. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7660. res.set_content("body", "text/plain");
  7661. });
  7662. thread t = thread([&] { svr.listen(HOST, PORT); });
  7663. auto se = detail::scope_exit([&] {
  7664. svr.stop();
  7665. t.join();
  7666. ASSERT_FALSE(svr.is_running());
  7667. });
  7668. svr.wait_until_ready();
  7669. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7670. "Host: " + HOST +
  7671. "\r\n"
  7672. "Connection: close\r\n"
  7673. "\r\n";
  7674. std::string res;
  7675. ASSERT_TRUE(send_request(5, req, &res));
  7676. // The injected fields must not appear anywhere in the raw response.
  7677. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7678. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7679. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7680. // Invalid headers are dropped entirely, matching set_header().
  7681. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7682. // The valid header still passes through.
  7683. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7684. }
  7685. // Forward declaration: in split builds split.py strips `inline` and moves the
  7686. // definition into httplib.cc, so detail::write_request_line is not visible from
  7687. // the public httplib.h. Re-declaring it here lets the tests link against the
  7688. // symbol in both header-only and split builds.
  7689. namespace httplib {
  7690. namespace detail {
  7691. ssize_t write_request_line(Stream &strm, const std::string &method,
  7692. const std::string &path);
  7693. } // namespace detail
  7694. } // namespace httplib
  7695. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7696. // A well-formed target is written verbatim.
  7697. {
  7698. detail::BufferStream strm;
  7699. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7700. EXPECT_GT(n, 0);
  7701. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7702. }
  7703. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7704. // otherwise it splits the request line and injects a header or a whole
  7705. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7706. // when path encoding is disabled.
  7707. const std::string evil_targets[] = {
  7708. "/a\r\nInjected: pwned",
  7709. "/a\rInjected",
  7710. "/a\nInjected",
  7711. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7712. };
  7713. for (const auto &evil : evil_targets) {
  7714. detail::BufferStream strm;
  7715. auto n = detail::write_request_line(strm, "GET", evil);
  7716. EXPECT_LT(n, 0);
  7717. EXPECT_TRUE(strm.get_buffer().empty());
  7718. }
  7719. }
  7720. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7721. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7722. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7723. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7724. // client must fail cleanly with Error::Write instead of putting a
  7725. // request-line-less, header-injecting request on the wire.
  7726. Server svr;
  7727. svr.Get("/a", [](const Request &, Response &res) {
  7728. res.set_content("ok", "text/plain");
  7729. });
  7730. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7731. auto se = detail::scope_exit([&] {
  7732. svr.stop();
  7733. thread.join();
  7734. ASSERT_FALSE(svr.is_running());
  7735. });
  7736. svr.wait_until_ready();
  7737. {
  7738. Client cli(HOST, PORT);
  7739. cli.set_path_encode(false);
  7740. // The request is rejected before anything is written, so the connection
  7741. // stays silent and the subsequent response read would otherwise block for
  7742. // the full default read timeout. Shorten it -- the assertion is on the
  7743. // error, not the timeout.
  7744. cli.set_read_timeout(1, 0);
  7745. auto res = cli.Get("/a\r\nInjected: pwned");
  7746. EXPECT_FALSE(res);
  7747. EXPECT_EQ(Error::Write, res.error());
  7748. }
  7749. }
  7750. // Sends a raw request and verifies that there isn't a crash or exception.
  7751. static void test_raw_request(const std::string &req,
  7752. std::string *out = nullptr) {
  7753. Server svr;
  7754. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7755. res.set_content("ok", "text/plain");
  7756. });
  7757. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7758. res.set_content("ok", "text/plain");
  7759. });
  7760. svr.Get("/header_field_value_check",
  7761. [&](const Request & /*req*/, Response &res) {
  7762. res.set_content("ok", "text/plain");
  7763. });
  7764. svr.CustomRoute("PROPFIND", "/dav",
  7765. [&](const Request & /*req*/, Response &res) {
  7766. res.status = StatusCode::MultiStatus_207;
  7767. });
  7768. // Server read timeout must be longer than the client read timeout for the
  7769. // bug to reproduce, probably to force the server to process a request
  7770. // without a trailing blank line.
  7771. const time_t client_read_timeout_sec = 1;
  7772. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7773. bool listen_thread_ok = false;
  7774. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7775. auto se = detail::scope_exit([&] {
  7776. svr.stop();
  7777. t.join();
  7778. ASSERT_FALSE(svr.is_running());
  7779. EXPECT_TRUE(listen_thread_ok);
  7780. });
  7781. svr.wait_until_ready();
  7782. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7783. }
  7784. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7785. // A certain header line causes an exception if the header property is parsed
  7786. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7787. test_raw_request(
  7788. "GET /hi HTTP/1.1\r\n"
  7789. " : "
  7790. " "
  7791. " ");
  7792. }
  7793. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7794. // A certain header line causes an exception if the header property *name* is
  7795. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7796. // greedy matcher and requires backtracking when there are a lot of ":"
  7797. // characters.
  7798. // This occurs with libc++ but not libstdc++.
  7799. test_raw_request(
  7800. "GET /hi HTTP/1.1\r\n"
  7801. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7802. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7803. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7804. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7805. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7806. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7807. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7808. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7809. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7810. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7811. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7812. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7813. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7814. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7815. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7816. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7817. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7818. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7819. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7820. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7821. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7822. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7823. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7824. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7825. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7826. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7827. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7828. "&&&%%%");
  7829. }
  7830. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7831. // Make sure this doesn't crash the server.
  7832. // In a previous version of the header line regex, the "\r" rendered the line
  7833. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7834. // a new position where the leading white space ended and the field value
  7835. // began.
  7836. // The crash occurs with libc++ but not libstdc++.
  7837. test_raw_request("GET /hi HTTP/1.1\r\n"
  7838. "a:" +
  7839. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7840. "\r\n"
  7841. "\r\n");
  7842. }
  7843. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7844. std::string out;
  7845. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7846. "Content-Type: text/plain\r\n"
  7847. "Transfer-Encoding: chunked\r\n"
  7848. "\r\n"
  7849. "nothex\r\n",
  7850. &out);
  7851. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7852. }
  7853. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7854. std::string out;
  7855. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7856. "Content-Type: text/plain\r\n"
  7857. "Transfer-Encoding: chunked\r\n"
  7858. "\r\n"
  7859. "3\r\n"
  7860. "xyz\r\n"
  7861. "NaN\r\n",
  7862. &out);
  7863. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7864. }
  7865. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7866. std::string out;
  7867. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7868. "Content-Type: text/plain\r\n"
  7869. "Transfer-Encoding: chunked\r\n"
  7870. "\r\n"
  7871. // Length is too large for 64 bits.
  7872. "1ffffffffffffffff\r\n"
  7873. "xyz\r\n",
  7874. &out);
  7875. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7876. }
  7877. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7878. test_raw_request("GET /hi HTTP/1.1\r\n"
  7879. "Content-Type: text/plain\r\n\r");
  7880. }
  7881. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7882. std::string out;
  7883. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7884. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7885. }
  7886. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7887. Server svr;
  7888. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7889. EXPECT_TRUE(!req.remote_addr.empty());
  7890. });
  7891. thread t = thread([&] { svr.listen(HOST, PORT); });
  7892. auto se = detail::scope_exit([&] {
  7893. svr.stop();
  7894. t.join();
  7895. ASSERT_FALSE(svr.is_running());
  7896. });
  7897. svr.wait_until_ready();
  7898. // Send an invalid request line to trigger Bad Request
  7899. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7900. std::string out;
  7901. ASSERT_TRUE(send_request(5, bad_req, &out));
  7902. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7903. }
  7904. // A custom method with neither Content-Length nor Transfer-Encoding must be
  7905. // answered right away rather than blocking on a read that waits for EOF.
  7906. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  7907. std::string out;
  7908. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  7909. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  7910. }
  7911. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  7912. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  7913. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  7914. for (const auto *method : methods) {
  7915. Server svr;
  7916. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  7917. EXPECT_FALSE(svr.is_valid()) << method;
  7918. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  7919. }
  7920. }
  7921. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  7922. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  7923. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  7924. for (const auto *method : methods) {
  7925. Server svr;
  7926. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  7927. EXPECT_FALSE(svr.is_valid()) << method;
  7928. }
  7929. }
  7930. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  7931. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  7932. "COPY", "MOVE", "LOCK",
  7933. "UNLOCK", "REPORT", "SUBSCRIBE"};
  7934. Server svr;
  7935. for (const auto *method : methods) {
  7936. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  7937. }
  7938. EXPECT_TRUE(svr.is_valid());
  7939. }
  7940. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  7941. Server svr;
  7942. svr.CustomRoute("POST", "/x",
  7943. [](const Request &, Response &, const ContentReader &) {});
  7944. EXPECT_FALSE(svr.is_valid());
  7945. }
  7946. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  7947. Server svr;
  7948. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  7949. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  7950. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  7951. EXPECT_FALSE(svr.is_valid());
  7952. }
  7953. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  7954. Server svr;
  7955. auto captured = Error::Success;
  7956. svr.set_error_logger(
  7957. [&](const Error &err, const Request * /*req*/) { captured = err; });
  7958. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  7959. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  7960. }
  7961. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7962. std::string out;
  7963. std::string request(
  7964. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7965. test_raw_request(request, &out);
  7966. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7967. }
  7968. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7969. std::string out;
  7970. std::string request(
  7971. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7972. test_raw_request(request, &out);
  7973. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7974. }
  7975. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7976. std::string out;
  7977. std::string request(
  7978. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7979. test_raw_request(request, &out);
  7980. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7981. }
  7982. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7983. std::string out;
  7984. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7985. "Test: \r\n\r\n",
  7986. &out);
  7987. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7988. }
  7989. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7990. Server svr;
  7991. std::string x_custom;
  7992. std::string cookie;
  7993. std::string xff;
  7994. std::string x_unicode;
  7995. std::string x_iis;
  7996. svr.Get("/check", [&](const Request &req, Response &res) {
  7997. x_custom = req.get_header_value("X-Custom");
  7998. cookie = req.get_header_value("Cookie");
  7999. xff = req.get_header_value("X-Forwarded-For");
  8000. x_unicode = req.get_header_value("X-Unicode");
  8001. x_iis = req.get_header_value("X-IIS");
  8002. res.set_content("ok", "text/plain");
  8003. });
  8004. thread t = thread([&] { svr.listen(HOST, PORT); });
  8005. auto se = detail::scope_exit([&] {
  8006. svr.stop();
  8007. t.join();
  8008. ASSERT_FALSE(svr.is_running());
  8009. });
  8010. svr.wait_until_ready();
  8011. const std::string req = "GET /check HTTP/1.1\r\n"
  8012. "Host: localhost\r\n"
  8013. "X-Custom: a%0D%0AInjected: b\r\n"
  8014. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8015. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8016. "X-Unicode: %E3%81%82\r\n"
  8017. "X-IIS: %u00E9\r\n"
  8018. "Connection: close\r\n"
  8019. "\r\n";
  8020. std::string res;
  8021. ASSERT_TRUE(send_request(5, req, &res));
  8022. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8023. // Every value must be returned verbatim (wire form), with no decoding.
  8024. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8025. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8026. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8027. EXPECT_EQ("%E3%81%82", x_unicode);
  8028. EXPECT_EQ("%u00E9", x_iis);
  8029. }
  8030. // Applications that previously relied on automatic percent-decoding can
  8031. // reproduce the old behavior by explicitly calling decode_path_component()
  8032. // or, for RFC 3986 conformance, decode_uri_component().
  8033. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8034. Server svr;
  8035. std::string decoded;
  8036. svr.Get("/check", [&](const Request &req, Response &res) {
  8037. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8038. res.set_content("ok", "text/plain");
  8039. });
  8040. thread t = thread([&] { svr.listen(HOST, PORT); });
  8041. auto se = detail::scope_exit([&] {
  8042. svr.stop();
  8043. t.join();
  8044. ASSERT_FALSE(svr.is_running());
  8045. });
  8046. svr.wait_until_ready();
  8047. const std::string req = "GET /check HTTP/1.1\r\n"
  8048. "Host: localhost\r\n"
  8049. "X-Custom: hello%20world\r\n"
  8050. "Connection: close\r\n"
  8051. "\r\n";
  8052. std::string res;
  8053. ASSERT_TRUE(send_request(5, req, &res));
  8054. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8055. EXPECT_EQ("hello world", decoded);
  8056. }
  8057. // Regression test for #2033. Browsers send Referer values that include
  8058. // percent-encoded characters such as %0A inside the URL. Decoding the
  8059. // header value would either trip the post-decode CR/LF/NUL guard (the
  8060. // original bug, returning 400) or, after that guard was relaxed, silently
  8061. // store a literal LF — both unacceptable. The wire form must round-trip.
  8062. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8063. Server svr;
  8064. std::string referer;
  8065. svr.Get("/check", [&](const Request &req, Response &res) {
  8066. referer = req.get_header_value("Referer");
  8067. res.set_content("ok", "text/plain");
  8068. });
  8069. thread t = thread([&] { svr.listen(HOST, PORT); });
  8070. auto se = detail::scope_exit([&] {
  8071. svr.stop();
  8072. t.join();
  8073. ASSERT_FALSE(svr.is_running());
  8074. });
  8075. svr.wait_until_ready();
  8076. const std::string req = "GET /check HTTP/1.1\r\n"
  8077. "Host: localhost\r\n"
  8078. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8079. "Connection: close\r\n"
  8080. "\r\n";
  8081. std::string res;
  8082. ASSERT_TRUE(send_request(5, req, &res));
  8083. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8084. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8085. }
  8086. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8087. Server svr;
  8088. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8089. res.set_header("Cache-Control", "no-cache");
  8090. res.set_chunked_content_provider(
  8091. "text/event-stream", [](size_t offset, DataSink &sink) {
  8092. std::string s = "data:";
  8093. s += std::to_string(offset);
  8094. s += "\n\n";
  8095. auto ret = sink.write(s.data(), s.size());
  8096. EXPECT_TRUE(ret);
  8097. std::this_thread::sleep_for(std::chrono::seconds(1));
  8098. return true;
  8099. });
  8100. });
  8101. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8102. svr.wait_until_ready();
  8103. Client client(HOST, PORT);
  8104. const Headers headers = {{"Accept", "text/event-stream"}};
  8105. auto get_thread = std::thread([&client, &headers]() {
  8106. auto res = client.Get(
  8107. "/events", headers,
  8108. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8109. });
  8110. auto se = detail::scope_exit([&] {
  8111. svr.stop();
  8112. get_thread.join();
  8113. listen_thread.join();
  8114. ASSERT_FALSE(svr.is_running());
  8115. });
  8116. // Give GET time to get a few messages.
  8117. std::this_thread::sleep_for(std::chrono::seconds(2));
  8118. }
  8119. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8120. httplib::Server svr;
  8121. svr.Post("/hi",
  8122. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8123. res.status = StatusCode::OK_200;
  8124. });
  8125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8126. svr.wait_until_ready();
  8127. Client cli(HOST, PORT);
  8128. auto res = cli.Post("/hi", "data", "text/plain");
  8129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8130. EXPECT_EQ(StatusCode::OK_200, res->status);
  8131. svr.stop();
  8132. thread.join();
  8133. ASSERT_FALSE(svr.is_running());
  8134. res = cli.Post("/hi", "data", "text/plain");
  8135. ASSERT_FALSE(res);
  8136. }
  8137. TEST(ServerStopTest, ListenFailure) {
  8138. Server svr;
  8139. auto t = thread([&]() {
  8140. auto ret = svr.listen("????", PORT);
  8141. EXPECT_FALSE(ret);
  8142. });
  8143. svr.wait_until_ready();
  8144. svr.stop();
  8145. t.join();
  8146. }
  8147. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8148. TEST(ServerStopTest, Decommision) {
  8149. Server svr;
  8150. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8151. for (int i = 0; i < 4; i++) {
  8152. auto is_even = !(i % 2);
  8153. std::thread t{[&] {
  8154. try {
  8155. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8156. if (is_even) {
  8157. throw std::runtime_error("Some thing that happens to go wrong.");
  8158. }
  8159. svr.listen(HOST, PORT);
  8160. } catch (...) { svr.decommission(); }
  8161. }};
  8162. svr.wait_until_ready();
  8163. // Server is up
  8164. {
  8165. Client cli(HOST, PORT);
  8166. auto res = cli.Get("/hi");
  8167. if (is_even) {
  8168. EXPECT_FALSE(res);
  8169. } else {
  8170. EXPECT_TRUE(res);
  8171. EXPECT_EQ("hi...", res->body);
  8172. }
  8173. }
  8174. svr.stop();
  8175. t.join();
  8176. // Server is down...
  8177. {
  8178. Client cli(HOST, PORT);
  8179. auto res = cli.Get("/hi");
  8180. EXPECT_FALSE(res);
  8181. }
  8182. }
  8183. }
  8184. #endif
  8185. // Helper function for string body upload progress tests
  8186. template <typename SetupHandler, typename ClientCall>
  8187. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  8188. ClientCall &&client_call,
  8189. const string &body) {
  8190. Server svr;
  8191. setup_handler(svr);
  8192. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8193. auto se = detail::scope_exit([&] {
  8194. svr.stop();
  8195. t.join();
  8196. });
  8197. svr.wait_until_ready();
  8198. Client cli(HOST, PORT);
  8199. vector<uint64_t> progress_values;
  8200. bool progress_called = false;
  8201. auto res =
  8202. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8203. progress_values.push_back(current);
  8204. progress_called = true;
  8205. return true;
  8206. });
  8207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8208. EXPECT_EQ(200, res->status);
  8209. EXPECT_TRUE(progress_called);
  8210. }
  8211. TEST(UploadProgressTest, PostStringBodyBasic) {
  8212. TestStringBodyUploadProgress(
  8213. [](Server &svr) {
  8214. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8215. res.set_content("received", "text/plain");
  8216. });
  8217. },
  8218. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8219. return cli.Post("/test", body, "text/plain", progress_callback);
  8220. },
  8221. "test data for upload progress");
  8222. }
  8223. TEST(UploadProgressTest, PutStringBodyBasic) {
  8224. TestStringBodyUploadProgress(
  8225. [](Server &svr) {
  8226. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  8227. res.set_content("put received", "text/plain");
  8228. });
  8229. },
  8230. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8231. return cli.Put("/test", body, "text/plain", progress_callback);
  8232. },
  8233. "put test data for upload progress");
  8234. }
  8235. TEST(UploadProgressTest, PatchStringBodyBasic) {
  8236. TestStringBodyUploadProgress(
  8237. [](Server &svr) {
  8238. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  8239. res.set_content("patch received", "text/plain");
  8240. });
  8241. },
  8242. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8243. return cli.Patch("/test", body, "text/plain", progress_callback);
  8244. },
  8245. "patch test data for upload progress");
  8246. }
  8247. // Helper function for content provider upload progress tests
  8248. template <typename SetupHandler, typename ClientCall>
  8249. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  8250. ClientCall &&client_call) {
  8251. Server svr;
  8252. setup_handler(svr);
  8253. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8254. auto se = detail::scope_exit([&] {
  8255. svr.stop();
  8256. t.join();
  8257. });
  8258. svr.wait_until_ready();
  8259. Client cli(HOST, PORT);
  8260. vector<uint64_t> progress_values;
  8261. auto res =
  8262. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8263. progress_values.push_back(current);
  8264. return true;
  8265. });
  8266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8267. EXPECT_EQ(200, res->status);
  8268. EXPECT_FALSE(progress_values.empty());
  8269. }
  8270. TEST(UploadProgressTest, PostContentProviderProgress) {
  8271. TestContentProviderUploadProgress(
  8272. [](Server &svr) {
  8273. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8274. res.set_content("provider received", "text/plain");
  8275. });
  8276. },
  8277. [](Client &cli, UploadProgress progress_callback) {
  8278. return cli.Post(
  8279. "/test", 10,
  8280. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  8281. sink.os << "test data";
  8282. return true;
  8283. },
  8284. "text/plain", progress_callback);
  8285. });
  8286. }
  8287. // Helper function for multipart upload progress tests
  8288. template <typename SetupHandler, typename ClientCall>
  8289. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  8290. ClientCall &&client_call,
  8291. const string &endpoint) {
  8292. Server svr;
  8293. setup_handler(svr);
  8294. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8295. auto se = detail::scope_exit([&] {
  8296. svr.stop();
  8297. t.join();
  8298. });
  8299. svr.wait_until_ready();
  8300. Client cli(HOST, PORT);
  8301. vector<uint64_t> progress_values;
  8302. UploadFormDataItems items = {
  8303. {"field1", "value1", "", ""},
  8304. {"field2", "longer value for progress tracking test", "", ""},
  8305. {"file1", "file content data for upload progress", "test.txt",
  8306. "text/plain"}};
  8307. auto res = client_call(cli, endpoint, items,
  8308. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8309. progress_values.push_back(current);
  8310. return true;
  8311. });
  8312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8313. EXPECT_EQ(200, res->status);
  8314. EXPECT_FALSE(progress_values.empty());
  8315. }
  8316. TEST(UploadProgressTest, PostMultipartProgress) {
  8317. TestMultipartUploadProgress(
  8318. [](Server &svr) {
  8319. svr.Post("/multipart", [](const Request &req, Response &res) {
  8320. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8321. res.set_content("multipart received", "text/plain");
  8322. });
  8323. },
  8324. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8325. UploadProgress progress_callback) {
  8326. return cli.Post(endpoint, items, progress_callback);
  8327. },
  8328. "/multipart");
  8329. }
  8330. // Helper function for basic download progress tests
  8331. template <typename SetupHandler, typename ClientCall>
  8332. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8333. ClientCall &&client_call, const string &endpoint,
  8334. size_t expected_content_size) {
  8335. Server svr;
  8336. setup_handler(svr);
  8337. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8338. auto se = detail::scope_exit([&] {
  8339. svr.stop();
  8340. t.join();
  8341. });
  8342. svr.wait_until_ready();
  8343. Client cli(HOST, PORT);
  8344. vector<uint64_t> progress_values;
  8345. auto res = client_call(cli, endpoint,
  8346. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8347. progress_values.push_back(current);
  8348. return true;
  8349. });
  8350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8351. EXPECT_EQ(200, res->status);
  8352. EXPECT_FALSE(progress_values.empty());
  8353. EXPECT_EQ(expected_content_size, res->body.size());
  8354. }
  8355. TEST(DownloadProgressTest, GetBasic) {
  8356. TestBasicDownloadProgress(
  8357. [](Server &svr) {
  8358. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8359. string content(1000, 'D');
  8360. res.set_content(content, "text/plain");
  8361. });
  8362. },
  8363. [](Client &cli, const string &endpoint,
  8364. DownloadProgress progress_callback) {
  8365. return cli.Get(endpoint, progress_callback);
  8366. },
  8367. "/download", 1000u);
  8368. }
  8369. // Helper function for content receiver download progress tests
  8370. template <typename SetupHandler, typename ClientCall>
  8371. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8372. ClientCall &&client_call,
  8373. const string &endpoint,
  8374. size_t expected_content_size) {
  8375. Server svr;
  8376. setup_handler(svr);
  8377. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8378. auto se = detail::scope_exit([&] {
  8379. svr.stop();
  8380. t.join();
  8381. });
  8382. svr.wait_until_ready();
  8383. Client cli(HOST, PORT);
  8384. vector<uint64_t> progress_values;
  8385. string received_body;
  8386. auto res = client_call(
  8387. cli, endpoint,
  8388. [&](const char *data, size_t data_length) -> bool {
  8389. received_body.append(data, data_length);
  8390. return true;
  8391. },
  8392. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8393. progress_values.push_back(current);
  8394. return true;
  8395. });
  8396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8397. EXPECT_EQ(200, res->status);
  8398. EXPECT_FALSE(progress_values.empty());
  8399. EXPECT_EQ(expected_content_size, received_body.size());
  8400. EXPECT_TRUE(res->body.empty());
  8401. }
  8402. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8403. TestContentReceiverDownloadProgress(
  8404. [](Server &svr) {
  8405. svr.Get("/download-receiver",
  8406. [](const Request & /*req*/, Response &res) {
  8407. string content(2000, 'R');
  8408. res.set_content(content, "text/plain");
  8409. });
  8410. },
  8411. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8412. DownloadProgress progress_callback) {
  8413. return cli.Get(endpoint, content_receiver, progress_callback);
  8414. },
  8415. "/download-receiver", 2000u);
  8416. }
  8417. TEST(StreamingTest, NoContentLengthStreaming) {
  8418. Server svr;
  8419. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8420. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8421. if (offset < 6) {
  8422. sink.os << (offset < 3 ? "a" : "b");
  8423. } else {
  8424. sink.done();
  8425. }
  8426. return true;
  8427. });
  8428. });
  8429. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8430. auto listen_se = detail::scope_exit([&] {
  8431. svr.stop();
  8432. listen_thread.join();
  8433. ASSERT_FALSE(svr.is_running());
  8434. });
  8435. svr.wait_until_ready();
  8436. Client client(HOST, PORT);
  8437. auto get_thread = std::thread([&client]() {
  8438. std::string s;
  8439. auto res =
  8440. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8441. s += std::string(data, len);
  8442. return true;
  8443. });
  8444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8445. EXPECT_EQ(StatusCode::OK_200, res->status);
  8446. EXPECT_EQ("aaabbb", s);
  8447. });
  8448. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8449. // Give GET time to get a few messages.
  8450. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8451. }
  8452. TEST(MountTest, Unmount) {
  8453. Server svr;
  8454. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8455. auto se = detail::scope_exit([&] {
  8456. svr.stop();
  8457. listen_thread.join();
  8458. ASSERT_FALSE(svr.is_running());
  8459. });
  8460. svr.wait_until_ready();
  8461. Client cli("localhost", PORT);
  8462. svr.set_mount_point("/mount2", "./www2");
  8463. auto res = cli.Get("/");
  8464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8465. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8466. res = cli.Get("/mount2/dir/test.html");
  8467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8468. EXPECT_EQ(StatusCode::OK_200, res->status);
  8469. svr.set_mount_point("/", "./www");
  8470. res = cli.Get("/dir/");
  8471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8472. EXPECT_EQ(StatusCode::OK_200, res->status);
  8473. svr.remove_mount_point("/");
  8474. res = cli.Get("/dir/");
  8475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8476. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8477. svr.remove_mount_point("/mount2");
  8478. res = cli.Get("/mount2/dir/test.html");
  8479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8480. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8481. }
  8482. TEST(MountTest, PathSegmentBoundary) {
  8483. Server svr;
  8484. svr.set_mount_point("/mount2", "./www2");
  8485. svr.set_mount_point("/", "./www");
  8486. auto port = svr.bind_to_any_port(HOST);
  8487. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8488. auto se = detail::scope_exit([&] {
  8489. svr.stop();
  8490. listen_thread.join();
  8491. ASSERT_FALSE(svr.is_running());
  8492. });
  8493. svr.wait_until_ready();
  8494. Client cli(HOST, port);
  8495. auto res = cli.Get("/mount2/dir/test.html");
  8496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8497. EXPECT_EQ(StatusCode::OK_200, res->status);
  8498. // "/mount2" must not match part-way through a path segment.
  8499. res = cli.Get("/mount2dir/test.html");
  8500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8501. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8502. // A mount point ending in '/' keeps matching every path below it.
  8503. res = cli.Get("/dir/test.html");
  8504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8505. EXPECT_EQ(StatusCode::OK_200, res->status);
  8506. }
  8507. TEST(MountTest, Redicect) {
  8508. Server svr;
  8509. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8510. auto se = detail::scope_exit([&] {
  8511. svr.stop();
  8512. listen_thread.join();
  8513. ASSERT_FALSE(svr.is_running());
  8514. });
  8515. svr.set_mount_point("/", "./www");
  8516. svr.wait_until_ready();
  8517. Client cli("localhost", PORT);
  8518. auto res = cli.Get("/dir/");
  8519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8520. EXPECT_EQ(StatusCode::OK_200, res->status);
  8521. res = cli.Get("/dir");
  8522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8523. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8524. res = cli.Get("/file");
  8525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8526. EXPECT_EQ(StatusCode::OK_200, res->status);
  8527. res = cli.Get("/file/");
  8528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8530. cli.set_follow_location(true);
  8531. res = cli.Get("/dir");
  8532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8533. EXPECT_EQ(StatusCode::OK_200, res->status);
  8534. }
  8535. TEST(MountTest, MultibytesPathName) {
  8536. Server svr;
  8537. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8538. auto se = detail::scope_exit([&] {
  8539. svr.stop();
  8540. listen_thread.join();
  8541. ASSERT_FALSE(svr.is_running());
  8542. });
  8543. svr.set_mount_point("/", "./www");
  8544. svr.wait_until_ready();
  8545. Client cli("localhost", PORT);
  8546. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8548. EXPECT_EQ(StatusCode::OK_200, res->status);
  8549. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8550. }
  8551. #ifdef _WIN32
  8552. // Issue #2435: mmap::open() must succeed even when another handle holds
  8553. // the file open for writing (e.g. an active log file).
  8554. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8555. const char *path = "mmap_concurrent_writer_test.txt";
  8556. const char *content = "hello";
  8557. {
  8558. std::ofstream f(path, std::ios::binary);
  8559. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8560. }
  8561. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8562. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8563. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8564. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8565. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8566. detail::mmap m(path);
  8567. ASSERT_TRUE(m.is_open());
  8568. EXPECT_EQ(strlen(content), m.size());
  8569. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8570. }
  8571. #endif
  8572. #ifndef _WIN32
  8573. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8574. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8575. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8576. TEST(MmapTest, FailedMappingIsNotOpen) {
  8577. const char *path = "./mmap_failed_mapping_test_dir";
  8578. ASSERT_EQ(0, ::mkdir(path, 0755));
  8579. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8580. detail::mmap m(path);
  8581. EXPECT_FALSE(m.is_open());
  8582. EXPECT_EQ(0U, m.size());
  8583. EXPECT_NE(static_cast<const void *>(m.data()),
  8584. static_cast<const void *>(MAP_FAILED));
  8585. }
  8586. #endif
  8587. TEST(KeepAliveTest, ReadTimeout) {
  8588. Server svr;
  8589. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8590. std::this_thread::sleep_for(std::chrono::seconds(2));
  8591. res.set_content("a", "text/plain");
  8592. });
  8593. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8594. res.set_content("b", "text/plain");
  8595. });
  8596. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8597. auto se = detail::scope_exit([&] {
  8598. svr.stop();
  8599. listen_thread.join();
  8600. ASSERT_FALSE(svr.is_running());
  8601. });
  8602. svr.wait_until_ready();
  8603. Client cli("localhost", PORT);
  8604. cli.set_keep_alive(true);
  8605. cli.set_read_timeout(std::chrono::seconds(1));
  8606. auto resa = cli.Get("/a");
  8607. ASSERT_FALSE(resa);
  8608. EXPECT_EQ(Error::Read, resa.error());
  8609. auto resb = cli.Get("/b");
  8610. ASSERT_TRUE(resb);
  8611. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8612. EXPECT_EQ("b", resb->body);
  8613. }
  8614. TEST(KeepAliveTest, MaxCount) {
  8615. size_t keep_alive_max_count = 3;
  8616. Server svr;
  8617. svr.set_keep_alive_max_count(keep_alive_max_count);
  8618. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8619. res.set_content("Hello World!", "text/plain");
  8620. });
  8621. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8622. auto se = detail::scope_exit([&] {
  8623. svr.stop();
  8624. listen_thread.join();
  8625. ASSERT_FALSE(svr.is_running());
  8626. });
  8627. svr.wait_until_ready();
  8628. Client cli(HOST, PORT);
  8629. cli.set_keep_alive(true);
  8630. for (size_t i = 0; i < 5; i++) {
  8631. auto result = cli.Get("/hi");
  8632. ASSERT_TRUE(result);
  8633. EXPECT_EQ(StatusCode::OK_200, result->status);
  8634. if (i == keep_alive_max_count - 1) {
  8635. EXPECT_EQ("close", result->get_header_value("Connection"));
  8636. } else {
  8637. EXPECT_FALSE(result->has_header("Connection"));
  8638. }
  8639. }
  8640. }
  8641. TEST(KeepAliveTest, Issue1041) {
  8642. Server svr;
  8643. svr.set_keep_alive_timeout(3);
  8644. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8645. res.set_content("Hello World!", "text/plain");
  8646. });
  8647. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8648. auto se = detail::scope_exit([&] {
  8649. svr.stop();
  8650. listen_thread.join();
  8651. ASSERT_FALSE(svr.is_running());
  8652. });
  8653. svr.wait_until_ready();
  8654. Client cli(HOST, PORT);
  8655. cli.set_keep_alive(true);
  8656. auto result = cli.Get("/hi");
  8657. ASSERT_TRUE(result);
  8658. EXPECT_EQ(StatusCode::OK_200, result->status);
  8659. std::this_thread::sleep_for(std::chrono::seconds(5));
  8660. result = cli.Get("/hi");
  8661. ASSERT_TRUE(result);
  8662. EXPECT_EQ(StatusCode::OK_200, result->status);
  8663. }
  8664. TEST(KeepAliveTest, Issue1959) {
  8665. Server svr;
  8666. svr.set_keep_alive_timeout(5);
  8667. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8668. res.set_content("a", "text/plain");
  8669. });
  8670. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8671. auto se = detail::scope_exit([&] {
  8672. if (!svr.is_running()) return;
  8673. svr.stop();
  8674. listen_thread.join();
  8675. ASSERT_FALSE(svr.is_running());
  8676. });
  8677. svr.wait_until_ready();
  8678. Client cli("localhost", PORT);
  8679. cli.set_keep_alive(true);
  8680. using namespace std::chrono;
  8681. auto start = steady_clock::now();
  8682. cli.Get("/a");
  8683. svr.stop();
  8684. listen_thread.join();
  8685. auto end = steady_clock::now();
  8686. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8687. EXPECT_LT(elapsed, 5000);
  8688. }
  8689. #ifdef CPPHTTPLIB_SSL_ENABLED
  8690. TEST(KeepAliveTest, SSLClientReconnection) {
  8691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8692. ASSERT_TRUE(svr.is_valid());
  8693. svr.set_keep_alive_timeout(1);
  8694. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8695. res.set_content("Hello World!", "text/plain");
  8696. });
  8697. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8698. auto se = detail::scope_exit([&] {
  8699. svr.stop();
  8700. listen_thread.join();
  8701. ASSERT_FALSE(svr.is_running());
  8702. });
  8703. svr.wait_until_ready();
  8704. SSLClient cli(HOST, PORT);
  8705. cli.enable_server_certificate_verification(false);
  8706. cli.set_keep_alive(true);
  8707. auto result = cli.Get("/hi");
  8708. ASSERT_TRUE(result);
  8709. EXPECT_EQ(StatusCode::OK_200, result->status);
  8710. result = cli.Get("/hi");
  8711. ASSERT_TRUE(result);
  8712. EXPECT_EQ(StatusCode::OK_200, result->status);
  8713. std::this_thread::sleep_for(std::chrono::seconds(2));
  8714. // Recoonect
  8715. result = cli.Get("/hi");
  8716. ASSERT_TRUE(result);
  8717. EXPECT_EQ(StatusCode::OK_200, result->status);
  8718. result = cli.Get("/hi");
  8719. ASSERT_TRUE(result);
  8720. EXPECT_EQ(StatusCode::OK_200, result->status);
  8721. }
  8722. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8723. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8724. ASSERT_TRUE(svr.is_valid());
  8725. svr.set_keep_alive_timeout(1);
  8726. std::string content = "reconnect";
  8727. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8728. res.set_content("Hello World!", "text/plain");
  8729. });
  8730. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8731. auto se = detail::scope_exit([&] {
  8732. svr.stop();
  8733. listen_thread.join();
  8734. ASSERT_FALSE(svr.is_running());
  8735. });
  8736. svr.wait_until_ready();
  8737. SSLClient cli(HOST, PORT);
  8738. cli.enable_server_certificate_verification(false);
  8739. cli.set_keep_alive(true);
  8740. auto result = cli.Post(
  8741. "/hi", content.size(),
  8742. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8743. sink.write(content.c_str(), content.size());
  8744. return true;
  8745. },
  8746. "text/plain");
  8747. ASSERT_TRUE(result);
  8748. EXPECT_EQ(200, result->status);
  8749. std::this_thread::sleep_for(std::chrono::seconds(2));
  8750. // Recoonect
  8751. result = cli.Post(
  8752. "/hi", content.size(),
  8753. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8754. sink.write(content.c_str(), content.size());
  8755. return true;
  8756. },
  8757. "text/plain");
  8758. ASSERT_TRUE(result);
  8759. EXPECT_EQ(200, result->status);
  8760. result = cli.Post(
  8761. "/hi", content.size(),
  8762. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8763. sink.write(content.c_str(), content.size());
  8764. return true;
  8765. },
  8766. "text/plain");
  8767. ASSERT_TRUE(result);
  8768. EXPECT_EQ(200, result->status);
  8769. }
  8770. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8771. using namespace httplib::tls;
  8772. {
  8773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8774. ASSERT_TRUE(svr.is_valid());
  8775. svr.Get("/sni", [&](const Request &req, Response &res) {
  8776. std::string expected = req.sni();
  8777. EXPECT_EQ(expected, req.get_param_value("expected"));
  8778. res.set_content("ok", "text/plain");
  8779. });
  8780. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8781. auto se = detail::scope_exit([&] {
  8782. svr.stop();
  8783. listen_thread.join();
  8784. ASSERT_FALSE(svr.is_running());
  8785. });
  8786. svr.wait_until_ready();
  8787. {
  8788. SSLClient cli("localhost", PORT);
  8789. cli.enable_server_certificate_verification(false);
  8790. auto res = cli.Get("/sni?expected=localhost");
  8791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8792. }
  8793. {
  8794. SSLClient cli("::1", PORT);
  8795. cli.enable_server_certificate_verification(false);
  8796. auto res = cli.Get("/sni?expected=");
  8797. // NOTE: This may fail if the server is listening on IPv4 only
  8798. // (e.g., when localhost resolves to 127.0.0.1 only)
  8799. if (res) {
  8800. EXPECT_EQ(StatusCode::OK_200, res->status);
  8801. } else {
  8802. EXPECT_EQ(Error::Connection, res.error());
  8803. }
  8804. }
  8805. }
  8806. }
  8807. #endif
  8808. TEST(ClientProblemDetectionTest, ContentProvider) {
  8809. Server svr;
  8810. size_t content_length = 1024 * 1024;
  8811. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8812. res.set_content_provider(
  8813. content_length, "text/plain",
  8814. [&](size_t offset, size_t length, DataSink &sink) {
  8815. auto out_len = std::min(length, static_cast<size_t>(1024));
  8816. std::string out(out_len, '@');
  8817. sink.write(out.data(), out_len);
  8818. return offset < 4096;
  8819. },
  8820. [](bool success) { ASSERT_FALSE(success); });
  8821. });
  8822. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8823. res.set_content_provider(
  8824. 0, "text/plain",
  8825. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8826. EXPECT_TRUE(false);
  8827. return true;
  8828. },
  8829. [](bool success) { ASSERT_FALSE(success); });
  8830. });
  8831. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8832. auto se = detail::scope_exit([&] {
  8833. svr.stop();
  8834. listen_thread.join();
  8835. ASSERT_FALSE(svr.is_running());
  8836. });
  8837. svr.wait_until_ready();
  8838. Client cli("localhost", PORT);
  8839. {
  8840. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8841. size_t /*data_length*/) { return false; });
  8842. ASSERT_FALSE(res);
  8843. }
  8844. {
  8845. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8846. size_t /*data_length*/) { return false; });
  8847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8848. }
  8849. }
  8850. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8851. Server svr;
  8852. svr.set_error_handler([](Request const &, Response &res) -> void {
  8853. res.set_chunked_content_provider(
  8854. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8855. sink.os << "hello";
  8856. sink.os << "world";
  8857. sink.done();
  8858. return true;
  8859. });
  8860. });
  8861. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8862. auto se = detail::scope_exit([&] {
  8863. svr.stop();
  8864. listen_thread.join();
  8865. ASSERT_FALSE(svr.is_running());
  8866. });
  8867. svr.wait_until_ready();
  8868. Client cli("localhost", PORT);
  8869. auto res = cli.Get("/");
  8870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8871. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8872. EXPECT_EQ("helloworld", res->body);
  8873. }
  8874. TEST(LongPollingTest, ClientCloseDetection) {
  8875. Server svr;
  8876. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8877. res.set_chunked_content_provider(
  8878. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8879. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8880. sink.os << "hello";
  8881. auto count = 10;
  8882. while (count > 0 && sink.is_writable()) {
  8883. this_thread::sleep_for(chrono::milliseconds(10));
  8884. count--;
  8885. }
  8886. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8887. return true;
  8888. });
  8889. });
  8890. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8891. auto se = detail::scope_exit([&] {
  8892. svr.stop();
  8893. listen_thread.join();
  8894. ASSERT_FALSE(svr.is_running());
  8895. });
  8896. svr.wait_until_ready();
  8897. Client cli("localhost", PORT);
  8898. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8899. EXPECT_EQ("hello", string(data, data_length));
  8900. return false; // close the socket immediately.
  8901. });
  8902. ASSERT_FALSE(res);
  8903. }
  8904. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8905. Server svr;
  8906. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8907. res.set_chunked_content_provider(
  8908. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8909. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8910. sink.os << "hello";
  8911. EXPECT_TRUE(sink.os.good());
  8912. // Wait for the client to close the connection
  8913. auto count = 10;
  8914. while (count > 0 && sink.is_writable()) {
  8915. this_thread::sleep_for(chrono::milliseconds(10));
  8916. count--;
  8917. }
  8918. // After client disconnect, write repeatedly until the socket
  8919. // write actually fails (small writes may be absorbed by the
  8920. // kernel buffer)
  8921. std::string chunk(1024, 'x');
  8922. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8923. sink.os << chunk;
  8924. }
  8925. EXPECT_TRUE(sink.os.fail());
  8926. return true;
  8927. });
  8928. });
  8929. auto port = svr.bind_to_any_port("localhost");
  8930. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8931. auto se = detail::scope_exit([&] {
  8932. svr.stop();
  8933. listen_thread.join();
  8934. ASSERT_FALSE(svr.is_running());
  8935. });
  8936. svr.wait_until_ready();
  8937. Client cli("localhost", port);
  8938. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8939. EXPECT_EQ("hello", string(data, data_length));
  8940. return false; // close the socket immediately.
  8941. });
  8942. ASSERT_FALSE(res);
  8943. }
  8944. TEST(GetWithParametersTest, GetWithParameters) {
  8945. Server svr;
  8946. svr.Get("/", [&](const Request &req, Response &) {
  8947. EXPECT_EQ("world", req.get_param_value("hello"));
  8948. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8949. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8950. });
  8951. svr.Get("/params", [&](const Request &req, Response &) {
  8952. EXPECT_EQ("world", req.get_param_value("hello"));
  8953. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8954. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8955. });
  8956. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8957. EXPECT_EQ("resource-id", req.matches[1]);
  8958. EXPECT_EQ("foo", req.get_param_value("param1"));
  8959. EXPECT_EQ("bar", req.get_param_value("param2"));
  8960. });
  8961. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8962. EXPECT_EQ("user-id", req.path_params.at("id"));
  8963. EXPECT_EQ("foo", req.get_param_value("param1"));
  8964. EXPECT_EQ("bar", req.get_param_value("param2"));
  8965. });
  8966. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8967. auto se = detail::scope_exit([&] {
  8968. svr.stop();
  8969. listen_thread.join();
  8970. ASSERT_FALSE(svr.is_running());
  8971. });
  8972. svr.wait_until_ready();
  8973. {
  8974. Client cli(HOST, PORT);
  8975. Params params;
  8976. params.emplace("hello", "world");
  8977. params.emplace("hello2", "world2");
  8978. params.emplace("hello3", "world3");
  8979. auto res = cli.Get("/", params, Headers{});
  8980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8981. EXPECT_EQ(StatusCode::OK_200, res->status);
  8982. }
  8983. {
  8984. Client cli(HOST, PORT);
  8985. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8987. EXPECT_EQ(StatusCode::OK_200, res->status);
  8988. }
  8989. {
  8990. Client cli(HOST, PORT);
  8991. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8993. EXPECT_EQ(StatusCode::OK_200, res->status);
  8994. }
  8995. {
  8996. Client cli(HOST, PORT);
  8997. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8999. EXPECT_EQ(StatusCode::OK_200, res->status);
  9000. }
  9001. }
  9002. TEST(GetWithParametersTest, GetWithParameters2) {
  9003. Server svr;
  9004. svr.Get("/", [&](const Request &req, Response &res) {
  9005. auto text = req.get_param_value("hello");
  9006. res.set_content(text, "text/plain");
  9007. });
  9008. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9009. auto se = detail::scope_exit([&] {
  9010. svr.stop();
  9011. listen_thread.join();
  9012. ASSERT_FALSE(svr.is_running());
  9013. });
  9014. svr.wait_until_ready();
  9015. Client cli("localhost", PORT);
  9016. Params params;
  9017. params.emplace("hello", "world");
  9018. std::string body;
  9019. auto res = cli.Get("/", params, Headers{},
  9020. [&](const char *data, size_t data_length) {
  9021. body.append(data, data_length);
  9022. return true;
  9023. });
  9024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9025. EXPECT_EQ(StatusCode::OK_200, res->status);
  9026. EXPECT_EQ("world", body);
  9027. }
  9028. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9029. Server svr;
  9030. svr.Get("/search", [&](const Request &req, Response &res) {
  9031. auto q = req.get_param_value("q");
  9032. res.set_content(q, "text/plain");
  9033. });
  9034. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9035. auto se = detail::scope_exit([&] {
  9036. svr.stop();
  9037. listen_thread.join();
  9038. ASSERT_FALSE(svr.is_running());
  9039. });
  9040. svr.wait_until_ready();
  9041. Client cli("localhost", PORT);
  9042. // Verify that Get(path, params) works without requiring Headers argument
  9043. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9045. EXPECT_EQ(StatusCode::OK_200, res->status);
  9046. EXPECT_EQ("cpp-httplib", res->body);
  9047. }
  9048. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9049. auto host = "httpbingo.org";
  9050. auto path = std::string{"/range/32"};
  9051. #ifdef CPPHTTPLIB_SSL_ENABLED
  9052. SSLClient cli(host);
  9053. #else
  9054. Client cli(host);
  9055. #endif
  9056. cli.set_default_headers({make_range_header({{1, 10}})});
  9057. cli.set_connection_timeout(5);
  9058. {
  9059. auto res = cli.Get(path);
  9060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9061. EXPECT_EQ("bcdefghijk", res->body);
  9062. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9063. }
  9064. {
  9065. auto res = cli.Get(path);
  9066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9067. EXPECT_EQ("bcdefghijk", res->body);
  9068. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9069. }
  9070. }
  9071. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  9072. Server svr;
  9073. svr.set_default_headers({{"Hello", "World"}});
  9074. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9075. res.set_content("ok", "text/plain");
  9076. });
  9077. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9078. auto se = detail::scope_exit([&] {
  9079. svr.stop();
  9080. listen_thread.join();
  9081. ASSERT_FALSE(svr.is_running());
  9082. });
  9083. svr.wait_until_ready();
  9084. Client cli("localhost", PORT);
  9085. auto res = cli.Get("/");
  9086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9087. EXPECT_EQ(StatusCode::OK_200, res->status);
  9088. EXPECT_EQ("ok", res->body);
  9089. EXPECT_EQ("World", res->get_header_value("Hello"));
  9090. }
  9091. #ifdef CPPHTTPLIB_SSL_ENABLED
  9092. TEST(KeepAliveTest, ReadTimeoutSSL) {
  9093. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9094. ASSERT_TRUE(svr.is_valid());
  9095. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9096. std::this_thread::sleep_for(std::chrono::seconds(2));
  9097. res.set_content("a", "text/plain");
  9098. });
  9099. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9100. res.set_content("b", "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. SSLClient cli("localhost", PORT);
  9110. cli.enable_server_certificate_verification(false);
  9111. cli.set_keep_alive(true);
  9112. cli.set_read_timeout(std::chrono::seconds(1));
  9113. auto resa = cli.Get("/a");
  9114. ASSERT_TRUE(!resa);
  9115. EXPECT_EQ(Error::Read, resa.error());
  9116. auto resb = cli.Get("/b");
  9117. ASSERT_TRUE(resb);
  9118. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9119. EXPECT_EQ("b", resb->body);
  9120. }
  9121. #endif
  9122. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  9123. protected:
  9124. ServerTestWithAI_PASSIVE()
  9125. : cli_(HOST, PORT)
  9126. #ifdef CPPHTTPLIB_SSL_ENABLED
  9127. ,
  9128. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9129. #endif
  9130. {
  9131. #ifdef CPPHTTPLIB_SSL_ENABLED
  9132. cli_.enable_server_certificate_verification(false);
  9133. #endif
  9134. }
  9135. virtual void SetUp() {
  9136. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9137. res.set_content("Hello World!", "text/plain");
  9138. });
  9139. t_ = thread(
  9140. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  9141. svr_.wait_until_ready();
  9142. }
  9143. virtual void TearDown() {
  9144. svr_.stop();
  9145. t_.join();
  9146. }
  9147. #ifdef CPPHTTPLIB_SSL_ENABLED
  9148. SSLClient cli_;
  9149. SSLServer svr_;
  9150. #else
  9151. Client cli_;
  9152. Server svr_;
  9153. #endif
  9154. thread t_;
  9155. };
  9156. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  9157. auto res = cli_.Get("/hi");
  9158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9159. EXPECT_EQ(StatusCode::OK_200, res->status);
  9160. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9161. EXPECT_EQ("Hello World!", res->body);
  9162. }
  9163. class ServerUpDownTest : public ::testing::Test {
  9164. protected:
  9165. ServerUpDownTest() : cli_(HOST, PORT) {}
  9166. virtual void SetUp() {
  9167. t_ = thread([&]() {
  9168. svr_.bind_to_any_port(HOST);
  9169. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9170. ASSERT_TRUE(svr_.listen_after_bind());
  9171. });
  9172. svr_.wait_until_ready();
  9173. }
  9174. virtual void TearDown() {
  9175. svr_.stop();
  9176. t_.join();
  9177. }
  9178. Client cli_;
  9179. Server svr_;
  9180. thread t_;
  9181. };
  9182. TEST_F(ServerUpDownTest, QuickStartStop) {
  9183. // Should not crash, especially when run with
  9184. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  9185. }
  9186. class PayloadMaxLengthTest : public ::testing::Test {
  9187. protected:
  9188. PayloadMaxLengthTest()
  9189. : cli_(HOST, PORT)
  9190. #ifdef CPPHTTPLIB_SSL_ENABLED
  9191. ,
  9192. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9193. #endif
  9194. {
  9195. #ifdef CPPHTTPLIB_SSL_ENABLED
  9196. cli_.enable_server_certificate_verification(false);
  9197. #endif
  9198. }
  9199. virtual void SetUp() {
  9200. svr_.set_payload_max_length(8);
  9201. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9202. res.set_content("test", "text/plain");
  9203. });
  9204. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9205. svr_.wait_until_ready();
  9206. }
  9207. virtual void TearDown() {
  9208. svr_.stop();
  9209. t_.join();
  9210. }
  9211. #ifdef CPPHTTPLIB_SSL_ENABLED
  9212. SSLClient cli_;
  9213. SSLServer svr_;
  9214. #else
  9215. Client cli_;
  9216. Server svr_;
  9217. #endif
  9218. thread t_;
  9219. };
  9220. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  9221. auto res = cli_.Post("/test", "123456789", "text/plain");
  9222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9223. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9224. res = cli_.Post("/test", "12345678", "text/plain");
  9225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9226. EXPECT_EQ(StatusCode::OK_200, res->status);
  9227. }
  9228. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  9229. // Test chunked encoding with payload exceeding the 8-byte limit
  9230. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  9231. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  9232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9233. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9234. }
  9235. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  9236. // Test chunked encoding with payload within the 8-byte limit
  9237. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  9238. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  9239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9240. EXPECT_EQ(StatusCode::OK_200, res->status);
  9241. }
  9242. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  9243. // Test using send_request to send chunked data exceeding payload limit
  9244. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  9245. "Host: " +
  9246. std::string(HOST) + ":" + std::to_string(PORT) +
  9247. "\r\n"
  9248. "Transfer-Encoding: chunked\r\n"
  9249. "Connection: close\r\n"
  9250. "\r\n"
  9251. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  9252. "0123456789\r\n"
  9253. "0\r\n" // End chunk
  9254. "\r\n";
  9255. std::string response;
  9256. bool result = send_request(1, chunked_request, &response);
  9257. if (!result) {
  9258. // If send_request fails, it might be because the server closed the
  9259. // connection due to payload limit enforcement, which is acceptable
  9260. SUCCEED()
  9261. << "Server rejected oversized chunked request (connection closed)";
  9262. } else {
  9263. // If we got a response, check if it's an error response or connection was
  9264. // closed early Short response length indicates connection was closed due to
  9265. // payload limit
  9266. if (response.length() <= 10) {
  9267. SUCCEED() << "Server closed connection for oversized chunked request";
  9268. } else {
  9269. // Check for error status codes
  9270. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9271. response.find("Payload Too Large") != std::string::npos ||
  9272. response.find("400") != std::string::npos);
  9273. }
  9274. }
  9275. }
  9276. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  9277. // Test request without Content-Length header exceeding payload limit
  9278. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9279. "Host: " +
  9280. std::string(HOST) + ":" +
  9281. std::to_string(PORT) +
  9282. "\r\n"
  9283. "Connection: close\r\n"
  9284. "\r\n";
  9285. // Add payload exceeding the 8-byte limit
  9286. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  9287. request_without_content_length += large_payload;
  9288. std::string response;
  9289. bool result = send_request(1, request_without_content_length, &response);
  9290. if (!result) {
  9291. // If send_request fails, server likely closed connection due to payload
  9292. // limit
  9293. SUCCEED() << "Server rejected oversized request without Content-Length "
  9294. "(connection closed)";
  9295. } else {
  9296. // Check if server responded with error or closed connection early
  9297. if (response.length() <= 10) {
  9298. SUCCEED() << "Server closed connection for oversized request without "
  9299. "Content-Length";
  9300. } else {
  9301. // Check for error status codes
  9302. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9303. response.find("Payload Too Large") != std::string::npos ||
  9304. response.find("400") != std::string::npos);
  9305. }
  9306. }
  9307. }
  9308. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  9309. // Test request without Content-Length header within payload limit
  9310. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9311. "Host: " +
  9312. std::string(HOST) + ":" +
  9313. std::to_string(PORT) +
  9314. "\r\n"
  9315. "Connection: close\r\n"
  9316. "\r\n";
  9317. // Add payload within the 8-byte limit
  9318. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9319. request_without_content_length += small_payload;
  9320. std::string response;
  9321. bool result = send_request(1, request_without_content_length, &response);
  9322. // For requests without Content-Length, the server may have different behavior
  9323. // The key is that it should not reject due to payload limit for small
  9324. // payloads
  9325. if (result) {
  9326. // Check for any HTTP response (success or error, but not connection closed)
  9327. if (response.length() > 10) {
  9328. SUCCEED()
  9329. << "Server processed request without Content-Length within limit";
  9330. } else {
  9331. // Short response might indicate connection closed, which is acceptable
  9332. SUCCEED() << "Server closed connection for request without "
  9333. "Content-Length (acceptable behavior)";
  9334. }
  9335. } else {
  9336. // Connection failure might be due to protocol requirements
  9337. SUCCEED() << "Connection issue with request without Content-Length "
  9338. "(environment-specific)";
  9339. }
  9340. }
  9341. class LargePayloadMaxLengthTest : public ::testing::Test {
  9342. protected:
  9343. LargePayloadMaxLengthTest()
  9344. : cli_(HOST, PORT)
  9345. #ifdef CPPHTTPLIB_SSL_ENABLED
  9346. ,
  9347. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9348. #endif
  9349. {
  9350. #ifdef CPPHTTPLIB_SSL_ENABLED
  9351. cli_.enable_server_certificate_verification(false);
  9352. #endif
  9353. }
  9354. virtual void SetUp() {
  9355. // Set 10MB payload limit
  9356. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9357. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9358. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9359. res.set_content("Large payload test", "text/plain");
  9360. });
  9361. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9362. svr_.wait_until_ready();
  9363. }
  9364. virtual void TearDown() {
  9365. svr_.stop();
  9366. t_.join();
  9367. }
  9368. #ifdef CPPHTTPLIB_SSL_ENABLED
  9369. SSLClient cli_;
  9370. SSLServer svr_;
  9371. #else
  9372. Client cli_;
  9373. Server svr_;
  9374. #endif
  9375. thread t_;
  9376. };
  9377. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9378. // Test chunked encoding with payload within 10MB limit
  9379. std::string medium_payload(5 * 1024 * 1024,
  9380. 'A'); // 5MB payload, within 10MB limit
  9381. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9383. EXPECT_EQ(StatusCode::OK_200, res->status);
  9384. }
  9385. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9386. // Test chunked encoding with payload exceeding 10MB limit
  9387. std::string large_payload(12 * 1024 * 1024,
  9388. 'B'); // 12MB payload, exceeds 10MB limit
  9389. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9390. // Server may either return 413 or close the connection
  9391. if (res) {
  9392. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9393. } else {
  9394. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9395. }
  9396. }
  9397. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9398. // Test request without Content-Length header within 10MB limit
  9399. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9400. "Host: " +
  9401. std::string(HOST) + ":" +
  9402. std::to_string(PORT) +
  9403. "\r\n"
  9404. "Connection: close\r\n"
  9405. "\r\n";
  9406. // Add 1MB payload (within 10MB limit)
  9407. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9408. request_without_content_length += medium_payload;
  9409. std::string response;
  9410. bool result = send_request(5, request_without_content_length, &response);
  9411. if (result) {
  9412. // Should get a proper HTTP response for payloads within limit
  9413. if (response.length() > 10) {
  9414. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9415. "10MB limit";
  9416. } else {
  9417. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9418. "Content-Length)";
  9419. }
  9420. } else {
  9421. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9422. }
  9423. }
  9424. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9425. // Test request without Content-Length header exceeding 10MB limit
  9426. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9427. "Host: " +
  9428. std::string(HOST) + ":" +
  9429. std::to_string(PORT) +
  9430. "\r\n"
  9431. "Connection: close\r\n"
  9432. "\r\n";
  9433. // Add 12MB payload (exceeds 10MB limit)
  9434. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9435. request_without_content_length += large_payload;
  9436. std::string response;
  9437. bool result = send_request(10, request_without_content_length, &response);
  9438. if (!result) {
  9439. // Server should close connection due to payload limit
  9440. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9441. "(connection closed)";
  9442. } else {
  9443. // Check for error response
  9444. if (response.length() <= 10) {
  9445. SUCCEED()
  9446. << "Server closed connection for 12MB request exceeding 10MB limit";
  9447. } else {
  9448. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9449. response.find("Payload Too Large") != std::string::npos ||
  9450. response.find("400") != std::string::npos);
  9451. }
  9452. }
  9453. }
  9454. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9455. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9456. // path.
  9457. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9458. Server svr;
  9459. const size_t LIMIT = 64 * 1024; // 64KB
  9460. svr.set_payload_max_length(LIMIT);
  9461. size_t total = 0;
  9462. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9463. const ContentReader &content_reader) {
  9464. content_reader([&](const char * /*data*/, size_t len) {
  9465. total += len;
  9466. return true;
  9467. });
  9468. res.status = 200;
  9469. res.set_content("stream_ok", "text/plain");
  9470. });
  9471. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9472. auto se = detail::scope_exit([&] {
  9473. svr.stop();
  9474. thread.join();
  9475. ASSERT_FALSE(svr.is_running());
  9476. });
  9477. svr.wait_until_ready();
  9478. // Prepare 256KB raw data and gzip-compress it
  9479. std::string raw(256 * 1024, 'A');
  9480. std::string gz;
  9481. {
  9482. z_stream zs{};
  9483. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9484. Z_DEFAULT_STRATEGY);
  9485. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9486. zs.avail_in = static_cast<uInt>(raw.size());
  9487. char outbuf[4096];
  9488. int ret;
  9489. do {
  9490. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9491. zs.avail_out = sizeof(outbuf);
  9492. ret = deflate(&zs, Z_FINISH);
  9493. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9494. } while (ret != Z_STREAM_END);
  9495. deflateEnd(&zs);
  9496. }
  9497. Client cli(HOST, PORT);
  9498. cli.set_connection_timeout(std::chrono::seconds(5));
  9499. Headers headers = {{"Content-Encoding", "gzip"}};
  9500. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9501. "application/octet-stream");
  9502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9503. // Server must reject oversized decompressed payloads with 413.
  9504. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9505. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9506. EXPECT_LE(total, LIMIT);
  9507. }
  9508. #ifndef CPPHTTPLIB_SSL_ENABLED
  9509. // For a request with neither Content-Length nor Transfer-Encoding, the
  9510. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9511. // compressed wire bytes straight to the ContentReader without ever routing
  9512. // them through the decompressor, so payload_max_length_ only bounded the
  9513. // compressed size on the wire, not the decompressed size.
  9514. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9515. Server svr;
  9516. const size_t LIMIT = 64 * 1024; // 64KB
  9517. svr.set_payload_max_length(LIMIT);
  9518. size_t total = 0;
  9519. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9520. const ContentReader &content_reader) {
  9521. content_reader([&](const char * /*data*/, size_t len) {
  9522. total += len;
  9523. return true;
  9524. });
  9525. res.status = 200;
  9526. res.set_content("stream_ok", "text/plain");
  9527. });
  9528. auto port = svr.bind_to_any_port(HOST);
  9529. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9530. auto se = detail::scope_exit([&] {
  9531. svr.stop();
  9532. thread.join();
  9533. ASSERT_FALSE(svr.is_running());
  9534. });
  9535. svr.wait_until_ready();
  9536. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9537. // StreamingGzipDecompression test above.
  9538. std::string raw(256 * 1024, 'A');
  9539. std::string gz;
  9540. {
  9541. httplib::detail::gzip_compressor compressor;
  9542. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9543. [&](const char *chunk, size_t len) {
  9544. gz.append(chunk, len);
  9545. return true;
  9546. });
  9547. ASSERT_TRUE(result);
  9548. }
  9549. // Send the gzip body over raw TCP with neither Content-Length nor
  9550. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  9551. // kicks in.
  9552. std::string req = "POST /stream HTTP/1.1\r\n"
  9553. "Host: " +
  9554. std::string(HOST) + ":" + std::to_string(port) +
  9555. "\r\n"
  9556. "Content-Encoding: gzip\r\n"
  9557. "Connection: close\r\n"
  9558. "\r\n" +
  9559. gz;
  9560. std::string response;
  9561. ASSERT_TRUE(send_request(5, req, &response, port));
  9562. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9563. EXPECT_LE(total, LIMIT);
  9564. }
  9565. #endif
  9566. #endif
  9567. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9568. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9569. // the payload must be passed through untouched instead of being rejected.
  9570. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9571. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9572. Server svr;
  9573. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9574. res.set_content(body, "image/jpeg");
  9575. res.set_header("Content-Encoding", "UTF-8");
  9576. });
  9577. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9578. res.set_content(body, "image/jpeg");
  9579. res.set_header("Content-Encoding", "identity");
  9580. });
  9581. svr.Post("/echo", [](const Request &req, Response &res) {
  9582. res.set_content(req.body, "image/jpeg");
  9583. });
  9584. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9585. auto se = detail::scope_exit([&] {
  9586. svr.stop();
  9587. t.join();
  9588. ASSERT_FALSE(svr.is_running());
  9589. });
  9590. svr.wait_until_ready();
  9591. Client cli(HOST, PORT);
  9592. {
  9593. auto res = cli.Get("/image");
  9594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9595. EXPECT_EQ(StatusCode::OK_200, res->status);
  9596. EXPECT_EQ(body, res->body);
  9597. }
  9598. {
  9599. auto res = cli.Get("/identity");
  9600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9601. EXPECT_EQ(StatusCode::OK_200, res->status);
  9602. EXPECT_EQ(body, res->body);
  9603. }
  9604. {
  9605. // The same applies to a request body reaching the server.
  9606. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9607. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9609. EXPECT_EQ(StatusCode::OK_200, res->status);
  9610. EXPECT_EQ(body, res->body);
  9611. }
  9612. }
  9613. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9614. // gzip-encoded response even when the build has no zlib support.
  9615. static const char GZIPPED_HELLO_WORLD[] = {
  9616. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9617. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9618. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9619. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9620. // A content coding is a whole token, not something the field value merely
  9621. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  9622. // as "fibre" look like Brotli, and turned a multi-coding value like
  9623. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  9624. // it was never meant to see.
  9625. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  9626. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9627. Server svr;
  9628. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  9629. res.set_content(body, "image/jpeg");
  9630. res.set_header("Content-Encoding", "fibre");
  9631. });
  9632. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  9633. res.set_content(body, "image/jpeg");
  9634. res.set_header("Content-Encoding", "gzip, br");
  9635. });
  9636. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  9637. res.set_content(body, "image/jpeg");
  9638. res.set_header("Content-Encoding", "x-zstd-ish");
  9639. });
  9640. auto port = svr.bind_to_any_port(HOST);
  9641. thread t = thread([&]() { svr.listen_after_bind(); });
  9642. auto se = detail::scope_exit([&] {
  9643. svr.stop();
  9644. t.join();
  9645. ASSERT_FALSE(svr.is_running());
  9646. });
  9647. svr.wait_until_ready();
  9648. Client cli(HOST, port);
  9649. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  9650. auto res = cli.Get(path);
  9651. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9652. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9653. // Not a coding we recognize, so the payload comes back untouched
  9654. EXPECT_EQ(body, res->body) << path;
  9655. }
  9656. }
  9657. // A content coding cpp-httplib recognizes but was not built with must be
  9658. // reported as such. Handing the still-compressed payload back to the caller
  9659. // would silently corrupt it.
  9660. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9661. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9662. Server svr;
  9663. // "image/jpeg" keeps the server from applying a content coding of its own,
  9664. // so the hand-crafted Content-Encoding below survives.
  9665. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9666. res.set_content(gzipped, "image/jpeg");
  9667. res.set_header("Content-Encoding", "gzip");
  9668. });
  9669. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9670. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9671. res.set_content(gzipped, "image/jpeg");
  9672. res.set_header("Content-Encoding", "GZIP");
  9673. });
  9674. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9675. auto se = detail::scope_exit([&] {
  9676. svr.stop();
  9677. t.join();
  9678. ASSERT_FALSE(svr.is_running());
  9679. });
  9680. svr.wait_until_ready();
  9681. Client cli(HOST, PORT);
  9682. {
  9683. auto res = cli.Get("/gzipped");
  9684. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9686. EXPECT_EQ("Hello World!", res->body);
  9687. #else
  9688. ASSERT_FALSE(res);
  9689. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9690. #endif
  9691. }
  9692. {
  9693. // open_stream() must behave the same way.
  9694. auto handle = cli.open_stream("GET", "/gzipped");
  9695. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9696. ASSERT_TRUE(handle.is_valid());
  9697. std::string received;
  9698. char buf[256];
  9699. ssize_t n;
  9700. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9701. received.append(buf, static_cast<size_t>(n));
  9702. }
  9703. EXPECT_EQ("Hello World!", received);
  9704. #else
  9705. EXPECT_FALSE(handle.is_valid());
  9706. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9707. #endif
  9708. }
  9709. {
  9710. // A differently-cased coding must not be mistaken for an unknown one, or
  9711. // the body would be handed back still compressed.
  9712. auto res = cli.Get("/gzipped-uppercase");
  9713. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9715. EXPECT_EQ("Hello World!", res->body);
  9716. #else
  9717. ASSERT_FALSE(res);
  9718. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9719. #endif
  9720. }
  9721. }
  9722. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  9723. // the same message as the comma-joined one, so both have to be read the same
  9724. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  9725. // single gzip coding, and a body the sender says was encoded twice was handed
  9726. // back after one pass, still compressed but presented as decoded.
  9727. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  9728. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9729. Server svr;
  9730. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  9731. res.set_content(body, "image/jpeg");
  9732. res.headers.emplace("Content-Encoding", "gzip");
  9733. res.headers.emplace("Content-Encoding", "gzip");
  9734. });
  9735. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  9736. res.set_content(body, "image/jpeg");
  9737. res.set_header("Content-Encoding", "gzip, gzip");
  9738. });
  9739. auto port = svr.bind_to_any_port(HOST);
  9740. thread t = thread([&]() { svr.listen_after_bind(); });
  9741. auto se = detail::scope_exit([&] {
  9742. svr.stop();
  9743. t.join();
  9744. ASSERT_FALSE(svr.is_running());
  9745. });
  9746. svr.wait_until_ready();
  9747. Client cli(HOST, port);
  9748. // Two codings is not something cpp-httplib decodes, so both representations
  9749. // take the pass-through path rather than one of them being gunzipped once.
  9750. for (const char *path : {"/split", "/joined"}) {
  9751. auto res = cli.Get(path);
  9752. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9753. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9754. EXPECT_EQ(body, res->body) << path;
  9755. }
  9756. }
  9757. // Regression test for DoS vulnerability: a malicious server sending a response
  9758. // without Content-Length header must not cause unbounded memory consumption on
  9759. // the client side. The client should stop reading after a reasonable limit,
  9760. // similar to the server-side set_payload_max_length protection.
  9761. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9762. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9763. #ifndef _WIN32
  9764. signal(SIGPIPE, SIG_IGN);
  9765. #endif
  9766. auto server_thread = std::thread([] {
  9767. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9768. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9769. default_socket_options(srv);
  9770. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9771. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9772. sockaddr_in addr{};
  9773. addr.sin_family = AF_INET;
  9774. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9775. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9776. int opt = 1;
  9777. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9778. #ifdef _WIN32
  9779. reinterpret_cast<const char *>(&opt),
  9780. #else
  9781. &opt,
  9782. #endif
  9783. sizeof(opt));
  9784. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9785. ::listen(srv, 1);
  9786. sockaddr_in cli_addr{};
  9787. socklen_t cli_len = sizeof(cli_addr);
  9788. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9789. if (cli != INVALID_SOCKET) {
  9790. char buf[4096];
  9791. ::recv(cli, buf, sizeof(buf), 0);
  9792. // Malicious response: no Content-Length, no chunked encoding
  9793. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9794. "Connection: close\r\n"
  9795. "\r\n";
  9796. ::send(cli,
  9797. #ifdef _WIN32
  9798. static_cast<const char *>(response_header.c_str()),
  9799. static_cast<int>(response_header.size()),
  9800. #else
  9801. response_header.c_str(), response_header.size(),
  9802. #endif
  9803. 0);
  9804. // Send 10MB of data
  9805. std::string chunk(64 * 1024, 'A');
  9806. size_t total_sent = 0;
  9807. while (total_sent < MALICIOUS_DATA_SIZE) {
  9808. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9809. auto sent = ::send(cli,
  9810. #ifdef _WIN32
  9811. static_cast<const char *>(chunk.c_str()),
  9812. static_cast<int>(to_send),
  9813. #else
  9814. chunk.c_str(), to_send,
  9815. #endif
  9816. 0);
  9817. if (sent <= 0) break;
  9818. total_sent += static_cast<size_t>(sent);
  9819. }
  9820. detail::close_socket(cli);
  9821. }
  9822. detail::close_socket(srv);
  9823. });
  9824. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9825. size_t total_read = 0;
  9826. {
  9827. Client cli("127.0.0.1", PORT + 2);
  9828. cli.set_read_timeout(5, 0);
  9829. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9830. auto stream = cli.open_stream("GET", "/malicious");
  9831. ASSERT_TRUE(stream.is_valid());
  9832. char buffer[64 * 1024];
  9833. ssize_t n;
  9834. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9835. total_read += static_cast<size_t>(n);
  9836. }
  9837. } // StreamHandle and Client destroyed here, closing the socket
  9838. server_thread.join();
  9839. // With set_payload_max_length, the client must stop reading before consuming
  9840. // all 10MB. The read loop should be cut off at or near the configured limit.
  9841. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9842. << "Client read " << total_read << " bytes, exceeding the configured "
  9843. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9844. }
  9845. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9846. // the entire response body without truncation.
  9847. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9848. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9849. #ifndef _WIN32
  9850. signal(SIGPIPE, SIG_IGN);
  9851. #endif
  9852. auto server_thread = std::thread([] {
  9853. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9854. default_socket_options(srv);
  9855. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9856. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9857. sockaddr_in addr{};
  9858. addr.sin_family = AF_INET;
  9859. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9860. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9861. int opt = 1;
  9862. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9863. #ifdef _WIN32
  9864. reinterpret_cast<const char *>(&opt),
  9865. #else
  9866. &opt,
  9867. #endif
  9868. sizeof(opt));
  9869. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9870. ::listen(srv, 1);
  9871. sockaddr_in cli_addr{};
  9872. socklen_t cli_len = sizeof(cli_addr);
  9873. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9874. if (cli != INVALID_SOCKET) {
  9875. char buf[4096];
  9876. ::recv(cli, buf, sizeof(buf), 0);
  9877. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9878. "Connection: close\r\n"
  9879. "\r\n";
  9880. ::send(cli,
  9881. #ifdef _WIN32
  9882. static_cast<const char *>(response_header.c_str()),
  9883. static_cast<int>(response_header.size()),
  9884. #else
  9885. response_header.c_str(), response_header.size(),
  9886. #endif
  9887. 0);
  9888. std::string chunk(64 * 1024, 'A');
  9889. size_t total_sent = 0;
  9890. while (total_sent < DATA_SIZE) {
  9891. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9892. auto sent = ::send(cli,
  9893. #ifdef _WIN32
  9894. static_cast<const char *>(chunk.c_str()),
  9895. static_cast<int>(to_send),
  9896. #else
  9897. chunk.c_str(), to_send,
  9898. #endif
  9899. 0);
  9900. if (sent <= 0) break;
  9901. total_sent += static_cast<size_t>(sent);
  9902. }
  9903. #ifdef _WIN32
  9904. ::shutdown(cli, SD_SEND);
  9905. #else
  9906. ::shutdown(cli, SHUT_WR);
  9907. #endif
  9908. // Drain until the client closes its end, ensuring all data is delivered
  9909. char drain[1024];
  9910. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9911. detail::close_socket(cli);
  9912. }
  9913. detail::close_socket(srv);
  9914. });
  9915. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9916. size_t total_read = 0;
  9917. {
  9918. Client cli("127.0.0.1", PORT + 2);
  9919. cli.set_read_timeout(5, 0);
  9920. cli.set_payload_max_length(0); // 0 means no limit
  9921. auto stream = cli.open_stream("GET", "/data");
  9922. ASSERT_TRUE(stream.is_valid());
  9923. char buffer[64 * 1024];
  9924. ssize_t n;
  9925. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9926. total_read += static_cast<size_t>(n);
  9927. }
  9928. }
  9929. server_thread.join();
  9930. EXPECT_EQ(total_read, DATA_SIZE)
  9931. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9932. << " bytes without truncation, but only read " << total_read << " bytes.";
  9933. }
  9934. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9935. // enormous Content-Length must not cause the client to pre-allocate a huge
  9936. // response body buffer. The reservation is capped at payload_max_length_, and
  9937. // the read itself fails when the body exceeds the limit.
  9938. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9939. #ifndef _WIN32
  9940. signal(SIGPIPE, SIG_IGN);
  9941. #endif
  9942. auto server_thread = std::thread([] {
  9943. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9944. default_socket_options(srv);
  9945. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9946. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9947. sockaddr_in addr{};
  9948. addr.sin_family = AF_INET;
  9949. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9950. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9951. int opt = 1;
  9952. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9953. #ifdef _WIN32
  9954. reinterpret_cast<const char *>(&opt),
  9955. #else
  9956. &opt,
  9957. #endif
  9958. sizeof(opt));
  9959. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9960. ::listen(srv, 1);
  9961. sockaddr_in cli_addr{};
  9962. socklen_t cli_len = sizeof(cli_addr);
  9963. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9964. if (cli != INVALID_SOCKET) {
  9965. char buf[4096];
  9966. ::recv(cli, buf, sizeof(buf), 0);
  9967. // Malicious response: claim a 20GB body but send only a tiny payload.
  9968. std::string response = "HTTP/1.1 200 OK\r\n"
  9969. "Content-Length: 20000000000\r\n"
  9970. "\r\n"
  9971. "abc";
  9972. ::send(cli,
  9973. #ifdef _WIN32
  9974. static_cast<const char *>(response.c_str()),
  9975. static_cast<int>(response.size()),
  9976. #else
  9977. response.c_str(), response.size(),
  9978. #endif
  9979. 0);
  9980. detail::close_socket(cli);
  9981. }
  9982. detail::close_socket(srv);
  9983. });
  9984. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9985. {
  9986. Client cli("127.0.0.1", PORT + 2);
  9987. cli.set_read_timeout(5, 0);
  9988. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9989. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9990. // (server claims more bytes than payload_max_length permits), but it must
  9991. // not exhaust memory before getting there.
  9992. auto res = cli.Get("/malicious");
  9993. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9994. }
  9995. server_thread.join();
  9996. }
  9997. // Verify that content_receiver bypasses the default payload_max_length,
  9998. // allowing streaming downloads larger than 100MB without requiring an explicit
  9999. // set_payload_max_length call.
  10000. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  10001. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10002. #ifndef _WIN32
  10003. signal(SIGPIPE, SIG_IGN);
  10004. #endif
  10005. auto server_thread = std::thread([] {
  10006. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10007. default_socket_options(srv);
  10008. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10009. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10010. sockaddr_in addr{};
  10011. addr.sin_family = AF_INET;
  10012. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10013. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10014. int opt = 1;
  10015. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10016. #ifdef _WIN32
  10017. reinterpret_cast<const char *>(&opt),
  10018. #else
  10019. &opt,
  10020. #endif
  10021. sizeof(opt));
  10022. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10023. ::listen(srv, 1);
  10024. sockaddr_in cli_addr{};
  10025. socklen_t cli_len = sizeof(cli_addr);
  10026. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10027. if (cli != INVALID_SOCKET) {
  10028. char buf[4096];
  10029. ::recv(cli, buf, sizeof(buf), 0);
  10030. // Response with Content-Length larger than default 100MB limit
  10031. auto content_length = std::to_string(DATA_SIZE);
  10032. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10033. "Content-Length: " +
  10034. content_length +
  10035. "\r\n"
  10036. "Connection: close\r\n"
  10037. "\r\n";
  10038. ::send(cli,
  10039. #ifdef _WIN32
  10040. static_cast<const char *>(response_header.c_str()),
  10041. static_cast<int>(response_header.size()),
  10042. #else
  10043. response_header.c_str(), response_header.size(),
  10044. #endif
  10045. 0);
  10046. std::string chunk(64 * 1024, 'A');
  10047. size_t total_sent = 0;
  10048. while (total_sent < DATA_SIZE) {
  10049. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10050. auto sent = ::send(cli,
  10051. #ifdef _WIN32
  10052. static_cast<const char *>(chunk.c_str()),
  10053. static_cast<int>(to_send),
  10054. #else
  10055. chunk.c_str(), to_send,
  10056. #endif
  10057. 0);
  10058. if (sent <= 0) break;
  10059. total_sent += static_cast<size_t>(sent);
  10060. }
  10061. detail::close_socket(cli);
  10062. }
  10063. detail::close_socket(srv);
  10064. });
  10065. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10066. size_t total_received = 0;
  10067. {
  10068. Client cli("127.0.0.1", PORT + 2);
  10069. cli.set_read_timeout(10, 0);
  10070. // Do NOT call set_payload_max_length — use the default 100MB limit
  10071. auto res =
  10072. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10073. total_received += data_length;
  10074. return true;
  10075. });
  10076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10077. EXPECT_EQ(StatusCode::OK_200, res->status);
  10078. }
  10079. server_thread.join();
  10080. EXPECT_EQ(total_received, DATA_SIZE)
  10081. << "With content_receiver, the client should read all " << DATA_SIZE
  10082. << " bytes despite the default 100MB payload_max_length, but only read "
  10083. << total_received << " bytes.";
  10084. }
  10085. // Verify that an explicit set_payload_max_length smaller than the response is
  10086. // enforced even when a content_receiver is used.
  10087. TEST(ClientVulnerabilityTest,
  10088. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  10089. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10090. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  10091. #ifndef _WIN32
  10092. signal(SIGPIPE, SIG_IGN);
  10093. #endif
  10094. auto server_thread = std::thread([] {
  10095. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10096. default_socket_options(srv);
  10097. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10098. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10099. sockaddr_in addr{};
  10100. addr.sin_family = AF_INET;
  10101. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10102. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10103. int opt = 1;
  10104. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10105. #ifdef _WIN32
  10106. reinterpret_cast<const char *>(&opt),
  10107. #else
  10108. &opt,
  10109. #endif
  10110. sizeof(opt));
  10111. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10112. ::listen(srv, 1);
  10113. sockaddr_in cli_addr{};
  10114. socklen_t cli_len = sizeof(cli_addr);
  10115. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10116. if (cli != INVALID_SOCKET) {
  10117. char buf[4096];
  10118. ::recv(cli, buf, sizeof(buf), 0);
  10119. auto content_length = std::to_string(DATA_SIZE);
  10120. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10121. "Content-Length: " +
  10122. content_length +
  10123. "\r\n"
  10124. "Connection: close\r\n"
  10125. "\r\n";
  10126. ::send(cli,
  10127. #ifdef _WIN32
  10128. static_cast<const char *>(response_header.c_str()),
  10129. static_cast<int>(response_header.size()),
  10130. #else
  10131. response_header.c_str(), response_header.size(),
  10132. #endif
  10133. 0);
  10134. std::string chunk(64 * 1024, 'A');
  10135. size_t total_sent = 0;
  10136. while (total_sent < DATA_SIZE) {
  10137. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10138. auto sent = ::send(cli,
  10139. #ifdef _WIN32
  10140. static_cast<const char *>(chunk.c_str()),
  10141. static_cast<int>(to_send),
  10142. #else
  10143. chunk.c_str(), to_send,
  10144. #endif
  10145. 0);
  10146. if (sent <= 0) break;
  10147. total_sent += static_cast<size_t>(sent);
  10148. }
  10149. detail::close_socket(cli);
  10150. }
  10151. detail::close_socket(srv);
  10152. });
  10153. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10154. size_t total_received = 0;
  10155. {
  10156. Client cli("127.0.0.1", PORT + 2);
  10157. cli.set_read_timeout(10, 0);
  10158. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  10159. auto res =
  10160. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10161. total_received += data_length;
  10162. return true;
  10163. });
  10164. // Should fail because 200MB exceeds the explicit 150MB limit
  10165. EXPECT_FALSE(res);
  10166. }
  10167. server_thread.join();
  10168. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  10169. << "Client with content_receiver should respect the explicit "
  10170. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  10171. << total_received << " bytes.";
  10172. }
  10173. // Verify that an explicit set_payload_max_length larger than the response
  10174. // allows the content_receiver to read all data successfully.
  10175. TEST(ClientVulnerabilityTest,
  10176. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  10177. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10178. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  10179. #ifndef _WIN32
  10180. signal(SIGPIPE, SIG_IGN);
  10181. #endif
  10182. auto server_thread = std::thread([] {
  10183. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10184. default_socket_options(srv);
  10185. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10186. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10187. sockaddr_in addr{};
  10188. addr.sin_family = AF_INET;
  10189. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10190. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10191. int opt = 1;
  10192. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10193. #ifdef _WIN32
  10194. reinterpret_cast<const char *>(&opt),
  10195. #else
  10196. &opt,
  10197. #endif
  10198. sizeof(opt));
  10199. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10200. ::listen(srv, 1);
  10201. sockaddr_in cli_addr{};
  10202. socklen_t cli_len = sizeof(cli_addr);
  10203. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10204. if (cli != INVALID_SOCKET) {
  10205. char buf[4096];
  10206. ::recv(cli, buf, sizeof(buf), 0);
  10207. auto content_length = std::to_string(DATA_SIZE);
  10208. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10209. "Content-Length: " +
  10210. content_length +
  10211. "\r\n"
  10212. "Connection: close\r\n"
  10213. "\r\n";
  10214. ::send(cli,
  10215. #ifdef _WIN32
  10216. static_cast<const char *>(response_header.c_str()),
  10217. static_cast<int>(response_header.size()),
  10218. #else
  10219. response_header.c_str(), response_header.size(),
  10220. #endif
  10221. 0);
  10222. std::string chunk(64 * 1024, 'A');
  10223. size_t total_sent = 0;
  10224. while (total_sent < DATA_SIZE) {
  10225. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10226. auto sent = ::send(cli,
  10227. #ifdef _WIN32
  10228. static_cast<const char *>(chunk.c_str()),
  10229. static_cast<int>(to_send),
  10230. #else
  10231. chunk.c_str(), to_send,
  10232. #endif
  10233. 0);
  10234. if (sent <= 0) break;
  10235. total_sent += static_cast<size_t>(sent);
  10236. }
  10237. #ifdef _WIN32
  10238. ::shutdown(cli, SD_SEND);
  10239. #else
  10240. ::shutdown(cli, SHUT_WR);
  10241. #endif
  10242. char drain[1024];
  10243. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10244. detail::close_socket(cli);
  10245. }
  10246. detail::close_socket(srv);
  10247. });
  10248. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10249. size_t total_received = 0;
  10250. {
  10251. Client cli("127.0.0.1", PORT + 2);
  10252. cli.set_read_timeout(10, 0);
  10253. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  10254. auto res =
  10255. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10256. total_received += data_length;
  10257. return true;
  10258. });
  10259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10260. EXPECT_EQ(StatusCode::OK_200, res->status);
  10261. }
  10262. server_thread.join();
  10263. EXPECT_EQ(total_received, DATA_SIZE)
  10264. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  10265. << " bytes (larger than " << DATA_SIZE
  10266. << " bytes response), content_receiver should read all data, but only "
  10267. "read "
  10268. << total_received << " bytes.";
  10269. }
  10270. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  10271. // Regression test for "zip bomb" attack on the client side: a malicious server
  10272. // sends a small gzip-compressed response that decompresses to a huge payload.
  10273. // The client must enforce payload_max_length on the decompressed size.
  10274. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  10275. constexpr size_t DECOMPRESSED_SIZE =
  10276. 10 * 1024 * 1024; // 10MB after decompression
  10277. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10278. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  10279. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  10280. std::string compressed;
  10281. {
  10282. httplib::detail::gzip_compressor compressor;
  10283. bool ok =
  10284. compressor.compress(uncompressed.data(), uncompressed.size(),
  10285. /*last=*/true, [&](const char *buf, size_t len) {
  10286. compressed.append(buf, len);
  10287. return true;
  10288. });
  10289. ASSERT_TRUE(ok);
  10290. }
  10291. // Sanity: compressed data should be much smaller than the decompressed size
  10292. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  10293. #ifndef _WIN32
  10294. signal(SIGPIPE, SIG_IGN);
  10295. #endif
  10296. // Set up the listening socket in the main thread so the server is guaranteed
  10297. // to be ready before the client connects (eliminates race condition).
  10298. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10299. default_socket_options(srv);
  10300. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10301. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10302. sockaddr_in addr{};
  10303. addr.sin_family = AF_INET;
  10304. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  10305. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10306. int opt = 1;
  10307. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10308. #ifdef _WIN32
  10309. reinterpret_cast<const char *>(&opt),
  10310. #else
  10311. &opt,
  10312. #endif
  10313. sizeof(opt));
  10314. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  10315. ASSERT_EQ(0, ::listen(srv, 1));
  10316. auto server_thread = std::thread([&compressed, srv] {
  10317. sockaddr_in cli_addr{};
  10318. socklen_t cli_len = sizeof(cli_addr);
  10319. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10320. if (cli != INVALID_SOCKET) {
  10321. // Read the full HTTP request (until \r\n\r\n)
  10322. char buf[4096];
  10323. size_t total = 0;
  10324. while (total < sizeof(buf)) {
  10325. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  10326. if (n <= 0) break;
  10327. total += static_cast<size_t>(n);
  10328. // Check for end of headers
  10329. if (total >= 4) {
  10330. std::string req(buf, total);
  10331. if (req.find("\r\n\r\n") != std::string::npos) break;
  10332. }
  10333. }
  10334. // Malicious response: gzip-compressed body, no Content-Length
  10335. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10336. "Content-Encoding: gzip\r\n"
  10337. "Connection: close\r\n"
  10338. "\r\n";
  10339. ::send(cli,
  10340. #ifdef _WIN32
  10341. static_cast<const char *>(response_header.c_str()),
  10342. static_cast<int>(response_header.size()),
  10343. #else
  10344. response_header.c_str(), response_header.size(),
  10345. #endif
  10346. 0);
  10347. // Send the compressed payload (small on the wire, huge when decompressed)
  10348. size_t total_sent = 0;
  10349. while (total_sent < compressed.size()) {
  10350. auto to_send = std::min(compressed.size() - total_sent,
  10351. static_cast<size_t>(64 * 1024));
  10352. auto sent =
  10353. ::send(cli,
  10354. #ifdef _WIN32
  10355. static_cast<const char *>(compressed.c_str() + total_sent),
  10356. static_cast<int>(to_send),
  10357. #else
  10358. compressed.c_str() + total_sent, to_send,
  10359. #endif
  10360. 0);
  10361. if (sent <= 0) break;
  10362. total_sent += static_cast<size_t>(sent);
  10363. }
  10364. detail::close_socket(cli);
  10365. }
  10366. });
  10367. auto se = detail::scope_exit([&] {
  10368. detail::close_socket(srv);
  10369. server_thread.join();
  10370. });
  10371. size_t total_decompressed = 0;
  10372. {
  10373. Client cli("127.0.0.1", PORT + 3);
  10374. cli.set_read_timeout(5, 0);
  10375. cli.set_decompress(true);
  10376. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10377. auto stream = cli.open_stream("GET", "/zipbomb");
  10378. ASSERT_TRUE(stream.is_valid());
  10379. char buffer[64 * 1024];
  10380. ssize_t n;
  10381. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10382. total_decompressed += static_cast<size_t>(n);
  10383. }
  10384. }
  10385. // The decompressed size must be capped by payload_max_length. Without
  10386. // protection, the client would decompress the full 10MB from a tiny
  10387. // compressed payload, enabling a zip bomb DoS attack.
  10388. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10389. << "Client decompressed " << total_decompressed
  10390. << " bytes from a gzip response. The decompressed size should be "
  10391. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10392. }
  10393. #endif
  10394. TEST(HostAndPortPropertiesTest, NoSSL) {
  10395. httplib::Client cli("www.google.com", 1234);
  10396. ASSERT_EQ("www.google.com", cli.host());
  10397. ASSERT_EQ(1234, cli.port());
  10398. }
  10399. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10400. httplib::Client cli("www.google.com:1234");
  10401. ASSERT_EQ("www.google.com", cli.host());
  10402. ASSERT_EQ(1234, cli.port());
  10403. }
  10404. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10405. // Port number that overflows int — should not crash, client becomes invalid
  10406. httplib::Client cli("http://www.google.com:99999999999999999999");
  10407. ASSERT_FALSE(cli.is_valid());
  10408. }
  10409. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10410. // Port 99999 exceeds valid range (1-65535) — should not crash
  10411. httplib::Client cli("http://www.google.com:99999");
  10412. ASSERT_FALSE(cli.is_valid());
  10413. }
  10414. #ifdef CPPHTTPLIB_SSL_ENABLED
  10415. TEST(HostAndPortPropertiesTest, SSL) {
  10416. httplib::SSLClient cli("www.google.com");
  10417. ASSERT_EQ("www.google.com", cli.host());
  10418. ASSERT_EQ(443, cli.port());
  10419. }
  10420. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10421. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10422. std::string cert;
  10423. read_file(CA_CERT_FILE, cert);
  10424. httplib::SSLClient httplib_client("www.google.com");
  10425. // Load CA store first time
  10426. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10427. // Load CA store second time (update)
  10428. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10429. // Verify client is still valid and can make connections
  10430. httplib_client.enable_server_certificate_verification(true);
  10431. auto res = httplib_client.Get("/");
  10432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10433. // Google may return 200 or 301 depending on various factors
  10434. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10435. res->status == StatusCode::MovedPermanently_301);
  10436. }
  10437. TEST(SSLClientTest, ServerNameIndication_Online) {
  10438. auto host = "httpbingo.org";
  10439. auto path = std::string{"/get"};
  10440. SSLClient cli(host, 443);
  10441. auto res = cli.Get(path);
  10442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10443. ASSERT_EQ(StatusCode::OK_200, res->status);
  10444. }
  10445. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10446. // Use a site that will cause SSL verification failure due to self-signed cert
  10447. SSLClient cli("self-signed.badssl.com", 443);
  10448. cli.enable_server_certificate_verification(true);
  10449. auto res = cli.Get("/");
  10450. ASSERT_TRUE(!res);
  10451. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10452. // Verify backend error is captured for SSLServerVerification
  10453. // This occurs when certificate verification fails
  10454. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10455. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10456. EXPECT_NE(0UL, res.ssl_backend_error());
  10457. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10458. // For OpenSSL, ssl_error is 0 for verification errors
  10459. EXPECT_EQ(0, res.ssl_error());
  10460. #if !defined(_WIN32) || \
  10461. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10462. // On non-Windows or when Windows Schannel is disabled, the error comes
  10463. // from OpenSSL's verification
  10464. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10465. res.ssl_backend_error());
  10466. #endif
  10467. #endif
  10468. }
  10469. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10470. // Use a site where hostname doesn't match the certificate
  10471. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10472. SSLClient cli("wrong.host.badssl.com", 443);
  10473. cli.enable_server_certificate_verification(true);
  10474. cli.enable_server_hostname_verification(true);
  10475. auto res = cli.Get("/");
  10476. ASSERT_TRUE(!res);
  10477. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10478. // Verify backend error is captured for hostname verification failure
  10479. EXPECT_NE(0UL, res.ssl_backend_error());
  10480. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10481. // For OpenSSL, ssl_error is 0 for verification errors
  10482. EXPECT_EQ(0, res.ssl_error());
  10483. #if !defined(_WIN32) || \
  10484. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10485. // On non-Windows or when Windows Schannel is disabled, the error comes
  10486. // from OpenSSL's hostname verification
  10487. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10488. res.ssl_backend_error());
  10489. #endif
  10490. #endif
  10491. }
  10492. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10493. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10494. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10495. SSLClient cli("www.google.com", 443);
  10496. cli.enable_server_certificate_verification(true);
  10497. auto res = cli.Get("/");
  10498. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10499. }
  10500. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10501. SSLClient cli("www.google.com", 443);
  10502. cli.enable_server_certificate_verification(true);
  10503. cli.enable_windows_certificate_verification(false);
  10504. auto res = cli.Get("/");
  10505. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10506. }
  10507. #endif
  10508. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10509. Client cli("https://google.com");
  10510. auto res = cli.Get("/");
  10511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10512. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10513. }
  10514. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10515. SSLClient cli("google.com");
  10516. cli.set_ca_cert_path(CA_CERT_FILE);
  10517. auto res = cli.Get("/");
  10518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10519. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10520. }
  10521. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10522. SSLClient cli("google.com");
  10523. cli.enable_server_certificate_verification(true);
  10524. cli.set_ca_cert_path("hello");
  10525. auto res = cli.Get("/");
  10526. ASSERT_TRUE(!res);
  10527. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10528. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10529. // should be set
  10530. EXPECT_EQ(0, res.ssl_error());
  10531. // Verify backend error is captured for SSLLoadingCerts
  10532. // This error occurs when loading CA certificates fails
  10533. EXPECT_NE(0UL, res.ssl_backend_error());
  10534. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10535. // OpenSSL specific error codes:
  10536. // > openssl errstr 0x80000002
  10537. // error:80000002:system library::No such file or directory
  10538. // > openssl errstr 0xA000126
  10539. // error:0A000126:SSL routines::unexpected eof while reading
  10540. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10541. res.ssl_backend_error() == 0xA000126);
  10542. #endif
  10543. }
  10544. TEST(SSLClientTest, ServerCertificateVerification4) {
  10545. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10546. ASSERT_TRUE(svr.is_valid());
  10547. svr.Get("/test", [&](const Request &, Response &res) {
  10548. res.set_content("test", "text/plain");
  10549. svr.stop();
  10550. ASSERT_TRUE(true);
  10551. });
  10552. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10553. auto se = detail::scope_exit([&] {
  10554. t.join();
  10555. ASSERT_FALSE(svr.is_running());
  10556. });
  10557. svr.wait_until_ready();
  10558. SSLClient cli("127.0.0.1", PORT);
  10559. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10560. cli.enable_server_certificate_verification(true);
  10561. cli.set_connection_timeout(30);
  10562. auto res = cli.Get("/test");
  10563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10564. ASSERT_EQ(StatusCode::OK_200, res->status);
  10565. }
  10566. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10567. std::string cert;
  10568. read_file(CA_CERT_FILE, cert);
  10569. SSLClient cli("google.com");
  10570. cli.load_ca_cert_store(cert.data(), cert.size());
  10571. const auto res = cli.Get("/");
  10572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10573. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10574. }
  10575. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10576. // clang-format off
  10577. static constexpr char cert[] =
  10578. "GlobalSign Root CA\n"
  10579. "==================\n"
  10580. "-----BEGIN CERTIFICATE-----\n"
  10581. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10582. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10583. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10584. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10585. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10586. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10587. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10588. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10589. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10590. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10591. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10592. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10593. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10594. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10595. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10596. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10597. "-----END CERTIFICATE-----\n";
  10598. // clang-format on
  10599. SSLClient cli("google.com");
  10600. cli.load_ca_cert_store(cert, sizeof(cert));
  10601. const auto res = cli.Get("/");
  10602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10603. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10604. }
  10605. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10606. SSLClient cli("www.youtube.com");
  10607. cli.set_ca_cert_path(CA_CERT_FILE);
  10608. cli.enable_server_certificate_verification(true);
  10609. cli.set_follow_location(true);
  10610. auto res = cli.Get("/");
  10611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10612. ASSERT_EQ(StatusCode::OK_200, res->status);
  10613. }
  10614. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10615. SSLClient cli("wWw.YouTube.Com");
  10616. cli.set_ca_cert_path(CA_CERT_FILE);
  10617. cli.enable_server_certificate_verification(true);
  10618. cli.enable_server_hostname_verification(true);
  10619. cli.set_follow_location(true);
  10620. auto res = cli.Get("/");
  10621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10622. ASSERT_EQ(StatusCode::OK_200, res->status);
  10623. }
  10624. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10625. SSLClient cli("gOoGlE.COm");
  10626. cli.enable_server_certificate_verification(true);
  10627. cli.enable_server_hostname_verification(true);
  10628. cli.set_follow_location(true);
  10629. auto res = cli.Get("/");
  10630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10631. ASSERT_EQ(StatusCode::OK_200, res->status);
  10632. }
  10633. TEST(SSLClientTest, Issue2004_Online) {
  10634. Client client("https://google.com");
  10635. client.set_follow_location(true);
  10636. auto res = client.Get("/");
  10637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10638. ASSERT_EQ(StatusCode::OK_200, res->status);
  10639. auto body = res->body;
  10640. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10641. }
  10642. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10643. // Create SSLClient with invalid cert/key to make is_valid() return false
  10644. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10645. "nonexistent_key.pem");
  10646. // is_valid() should be false due to cert loading failure
  10647. ASSERT_FALSE(cli.is_valid());
  10648. auto res = cli.Get("/");
  10649. ASSERT_FALSE(res);
  10650. EXPECT_EQ(Error::SSLConnection, res.error());
  10651. }
  10652. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10653. // Test for Issue #2251: SSL error not properly reported when client cert
  10654. // and key paths are swapped or mismatched
  10655. // This simulates the scenario where user accidentally swaps the cert and key
  10656. // files
  10657. // Using client cert file as private key and vice versa (completely wrong)
  10658. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10659. // Should fail validation due to cert/key mismatch
  10660. ASSERT_FALSE(cli.is_valid());
  10661. // Attempt to make a request should fail with proper error
  10662. auto res = cli.Get("/");
  10663. ASSERT_FALSE(res);
  10664. EXPECT_EQ(Error::SSLConnection, res.error());
  10665. // SSL error should be recorded in the Result object (this is the key fix for
  10666. // Issue #2251)
  10667. auto backend_error = res.ssl_backend_error();
  10668. EXPECT_NE(0u, backend_error);
  10669. }
  10670. // Tests cert/key mismatch detection at the TLS context level
  10671. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10672. // Test that using mismatched cert/key causes connection failure.
  10673. // We verify this at the SSLClient level rather than through internal
  10674. // TLS API functions.
  10675. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10676. cli.enable_server_certificate_verification(false);
  10677. cli.set_connection_timeout(2);
  10678. // The mismatch should cause a connection or handshake error
  10679. auto res = cli.Get("/test");
  10680. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10681. // Either way, the request should fail
  10682. EXPECT_FALSE(res);
  10683. }
  10684. #endif
  10685. #if 0
  10686. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10687. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10688. ASSERT_TRUE(cli != nullptr);
  10689. cli->set_address_family(AF_INET6);
  10690. cli->set_interface("en0");
  10691. auto res = cli->Get("/get");
  10692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10693. ASSERT_EQ(StatusCode::OK_200, res->status);
  10694. }
  10695. #endif
  10696. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10697. #ifdef CPPHTTPLIB_SSL_ENABLED
  10698. void ClientCertPresent(
  10699. const std::string &client_cert_file,
  10700. const std::string &client_private_key_file,
  10701. const std::string &client_encrypted_private_key_pass = std::string()) {
  10702. using namespace httplib::tls;
  10703. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10704. CLIENT_CA_CERT_DIR);
  10705. ASSERT_TRUE(svr.is_valid());
  10706. svr.Get("/test", [&](const Request &req, Response &res) {
  10707. res.set_content("test", "text/plain");
  10708. auto cert = req.peer_cert();
  10709. ASSERT_TRUE(static_cast<bool>(cert));
  10710. std::string common_name = cert.subject_cn();
  10711. EXPECT_EQ("Common Name", common_name);
  10712. });
  10713. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10714. auto se = detail::scope_exit([&] {
  10715. svr.stop();
  10716. t.join();
  10717. ASSERT_FALSE(svr.is_running());
  10718. });
  10719. svr.wait_until_ready();
  10720. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10721. client_encrypted_private_key_pass);
  10722. cli.enable_server_certificate_verification(false);
  10723. cli.set_connection_timeout(30);
  10724. auto res = cli.Get("/test");
  10725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10726. ASSERT_EQ(StatusCode::OK_200, res->status);
  10727. }
  10728. TEST(SSLClientServerTest, ClientCertPresent) {
  10729. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10730. }
  10731. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10732. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10733. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10734. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10735. }
  10736. // PEM memory-based constructor tests (works with all TLS backends)
  10737. void PemMemoryClientCertPresent(
  10738. const std::string &client_cert_file,
  10739. const std::string &client_private_key_file,
  10740. const std::string &client_encrypted_private_key_pass = std::string()) {
  10741. // Read PEM files into memory
  10742. std::string server_cert_pem, server_key_pem;
  10743. std::string client_ca_pem;
  10744. std::string client_cert_pem, client_key_pem;
  10745. read_file(SERVER_CERT_FILE, server_cert_pem);
  10746. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10747. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10748. read_file(client_cert_file, client_cert_pem);
  10749. read_file(client_private_key_file, client_key_pem);
  10750. // Create server with PEM memory
  10751. SSLServer::PemMemory server_pem = {
  10752. server_cert_pem.c_str(),
  10753. server_cert_pem.size(),
  10754. server_key_pem.c_str(),
  10755. server_key_pem.size(),
  10756. client_ca_pem.c_str(),
  10757. client_ca_pem.size(),
  10758. nullptr // no password for server key
  10759. };
  10760. SSLServer svr(server_pem);
  10761. ASSERT_TRUE(svr.is_valid());
  10762. svr.Get("/test", [&](const Request &, Response &res) {
  10763. res.set_content("test", "text/plain");
  10764. });
  10765. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10766. auto se = detail::scope_exit([&] {
  10767. svr.stop();
  10768. t.join();
  10769. ASSERT_FALSE(svr.is_running());
  10770. });
  10771. svr.wait_until_ready();
  10772. // Create client with PEM memory
  10773. const char *password = client_encrypted_private_key_pass.empty()
  10774. ? nullptr
  10775. : client_encrypted_private_key_pass.c_str();
  10776. SSLClient::PemMemory client_pem = {
  10777. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10778. client_key_pem.size(), password};
  10779. SSLClient cli(HOST, PORT, client_pem);
  10780. cli.enable_server_certificate_verification(false);
  10781. cli.set_connection_timeout(30);
  10782. auto res = cli.Get("/test");
  10783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10784. ASSERT_EQ(StatusCode::OK_200, res->status);
  10785. }
  10786. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10787. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10788. }
  10789. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10790. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10791. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10792. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10793. }
  10794. TEST(SSLClientServerTest, ClientCertMissing) {
  10795. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10796. CLIENT_CA_CERT_DIR);
  10797. ASSERT_TRUE(svr.is_valid());
  10798. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10799. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10800. auto se = detail::scope_exit([&] {
  10801. svr.stop();
  10802. t.join();
  10803. ASSERT_FALSE(svr.is_running());
  10804. });
  10805. svr.wait_until_ready();
  10806. SSLClient cli(HOST, PORT);
  10807. cli.set_connection_timeout(30);
  10808. auto res = cli.Get("/test");
  10809. ASSERT_TRUE(!res);
  10810. // When client cert is missing and server requires it, connection fails
  10811. // Error type depends on backend implementation
  10812. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10813. res.error() == Error::SSLConnection);
  10814. // Verify backend error is captured
  10815. // Note: This test may have different error codes depending on the exact
  10816. // verification failure
  10817. EXPECT_NE(0UL, res.ssl_backend_error());
  10818. }
  10819. TEST(SSLClientServerTest, TrustDirOptional) {
  10820. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10821. ASSERT_TRUE(svr.is_valid());
  10822. svr.Get("/test", [&](const Request &, Response &res) {
  10823. res.set_content("test", "text/plain");
  10824. });
  10825. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10826. auto se = detail::scope_exit([&] {
  10827. svr.stop();
  10828. t.join();
  10829. ASSERT_FALSE(svr.is_running());
  10830. });
  10831. svr.wait_until_ready();
  10832. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10833. cli.enable_server_certificate_verification(false);
  10834. cli.set_connection_timeout(30);
  10835. auto res = cli.Get("/test");
  10836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10837. ASSERT_EQ(StatusCode::OK_200, res->status);
  10838. }
  10839. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10840. class NoListenSSLServer : public SSLServer {
  10841. public:
  10842. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10843. const char *client_ca_cert_file_path,
  10844. const char *client_ca_cert_dir_path = nullptr)
  10845. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10846. client_ca_cert_dir_path),
  10847. stop_(false) {}
  10848. std::atomic_bool stop_;
  10849. private:
  10850. bool process_and_close_socket(socket_t /*sock*/) override {
  10851. // Don't create SSL context
  10852. while (!stop_.load()) {
  10853. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10854. }
  10855. return true;
  10856. }
  10857. };
  10858. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10859. CLIENT_CA_CERT_FILE);
  10860. ASSERT_TRUE(svr.is_valid());
  10861. svr.Get("/test", [&](const Request &, Response &res) {
  10862. res.set_content("test", "text/plain");
  10863. });
  10864. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10865. auto se = detail::scope_exit([&] {
  10866. svr.stop_ = true;
  10867. svr.stop();
  10868. t.join();
  10869. ASSERT_FALSE(svr.is_running());
  10870. });
  10871. svr.wait_until_ready();
  10872. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10873. cli.enable_server_certificate_verification(false);
  10874. cli.set_connection_timeout(1);
  10875. auto res = cli.Get("/test");
  10876. ASSERT_TRUE(!res);
  10877. EXPECT_EQ(Error::SSLConnection, res.error());
  10878. // Timeout results in WantRead error code (maps to backend-specific value)
  10879. EXPECT_NE(0, res.ssl_error());
  10880. }
  10881. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10882. // Test SSLServer with client certificate verification using the standard
  10883. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10884. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10885. CLIENT_CA_CERT_DIR);
  10886. ASSERT_TRUE(svr.is_valid());
  10887. svr.Get("/test", [&](const Request &req, Response &res) {
  10888. res.set_content("test", "text/plain");
  10889. auto cert = req.peer_cert();
  10890. ASSERT_TRUE(static_cast<bool>(cert));
  10891. auto common_name = cert.subject_cn();
  10892. EXPECT_EQ("Common Name", common_name);
  10893. });
  10894. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10895. auto se = detail::scope_exit([&] {
  10896. svr.stop();
  10897. t.join();
  10898. ASSERT_FALSE(svr.is_running());
  10899. });
  10900. svr.wait_until_ready();
  10901. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10902. cli.enable_server_certificate_verification(false);
  10903. cli.set_connection_timeout(30);
  10904. auto res = cli.Get("/test");
  10905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10906. ASSERT_EQ(StatusCode::OK_200, res->status);
  10907. }
  10908. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10909. // Verifies that wildcard matching and exact matching work consistently
  10910. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10911. using namespace httplib::tls;
  10912. // We need a running server to test against
  10913. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10914. ASSERT_TRUE(svr.is_valid());
  10915. svr.Get("/test", [](const Request &, Response &res) {
  10916. res.set_content("ok", "text/plain");
  10917. });
  10918. thread t([&]() { svr.listen(HOST, PORT); });
  10919. auto se = detail::scope_exit([&] {
  10920. svr.stop();
  10921. t.join();
  10922. });
  10923. svr.wait_until_ready();
  10924. bool verify_callback_called = false;
  10925. bool verify_result_wrong = false;
  10926. SSLClient cli(HOST, PORT);
  10927. cli.enable_server_certificate_verification(true);
  10928. cli.set_ca_cert_path(CA_CERT_FILE);
  10929. cli.set_connection_timeout(5);
  10930. // Note: Test certificate has CN="Common Name", not "localhost"
  10931. bool verify_result_cn = false;
  10932. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10933. verify_callback_called = true;
  10934. if (!ctx.cert) return false;
  10935. // Test 1: "Common Name" should match (our test server cert CN)
  10936. verify_result_cn = ctx.check_hostname("Common Name");
  10937. // Test 2: wrong hostname should not match
  10938. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10939. return true; // Accept for the purpose of this test
  10940. });
  10941. auto res = cli.Get("/test");
  10942. // The request may succeed or fail depending on cert configuration
  10943. // but the callback should have been called
  10944. ASSERT_TRUE(verify_callback_called)
  10945. << "Verify callback should have been called";
  10946. // CN="Common Name" should match our test certificate
  10947. //
  10948. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10949. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10950. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10951. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10952. // <openssl/base.h>, which is included transitively when
  10953. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10954. #if defined(OPENSSL_IS_BORINGSSL)
  10955. EXPECT_FALSE(verify_result_cn)
  10956. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10957. #else
  10958. EXPECT_TRUE(verify_result_cn)
  10959. << "verify_hostname should match 'Common Name' (certificate CN)";
  10960. #endif
  10961. // Wrong hostname should not match
  10962. EXPECT_FALSE(verify_result_wrong)
  10963. << "verify_hostname should not match 'wronghost.example.com'";
  10964. }
  10965. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10966. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10967. // X509_check_ip behavior and must hold for every backend.
  10968. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10969. using namespace httplib::tls;
  10970. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10971. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10972. ASSERT_TRUE(svr.is_valid());
  10973. svr.Get("/test", [](const Request &, Response &res) {
  10974. res.set_content("ok", "text/plain");
  10975. });
  10976. thread t([&]() { svr.listen(HOST, PORT); });
  10977. auto se = detail::scope_exit([&] {
  10978. svr.stop();
  10979. t.join();
  10980. });
  10981. svr.wait_until_ready();
  10982. bool verify_callback_called = false;
  10983. bool ip_matched_via_cn = true;
  10984. SSLClient cli(HOST, PORT);
  10985. cli.enable_server_certificate_verification(true);
  10986. cli.set_ca_cert_path(CA_CERT_FILE);
  10987. cli.set_connection_timeout(5);
  10988. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10989. verify_callback_called = true;
  10990. if (!ctx.cert) return false;
  10991. // The IP appears only in the CN, so it must NOT be accepted.
  10992. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10993. return true; // Accept for the purpose of this test
  10994. });
  10995. cli.Get("/test");
  10996. ASSERT_TRUE(verify_callback_called)
  10997. << "Verify callback should have been called";
  10998. EXPECT_FALSE(ip_matched_via_cn)
  10999. << "An IP host must not be authenticated via the certificate CN";
  11000. }
  11001. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  11002. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  11003. using namespace httplib::tls;
  11004. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  11005. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  11006. ASSERT_TRUE(svr.is_valid());
  11007. svr.Get("/test", [](const Request &, Response &res) {
  11008. res.set_content("ok", "text/plain");
  11009. });
  11010. thread t([&]() { svr.listen(HOST, PORT); });
  11011. auto se = detail::scope_exit([&] {
  11012. svr.stop();
  11013. t.join();
  11014. });
  11015. svr.wait_until_ready();
  11016. bool verify_callback_called = false;
  11017. bool san_matched = false;
  11018. bool wrong_ipv6_matched = true;
  11019. bool cn_ipv6_matched = true;
  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. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11025. verify_callback_called = true;
  11026. if (!ctx.cert) return false;
  11027. // Matches the IPv6 iPAddress SAN.
  11028. san_matched = ctx.check_hostname("2001:db8::1");
  11029. // A different IPv6 address must not match.
  11030. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  11031. // "::1" lives only in the CN, so it must not be accepted.
  11032. cn_ipv6_matched = ctx.check_hostname("::1");
  11033. return true; // Accept for the purpose of this test
  11034. });
  11035. cli.Get("/test");
  11036. ASSERT_TRUE(verify_callback_called)
  11037. << "Verify callback should have been called";
  11038. EXPECT_TRUE(san_matched)
  11039. << "verify_hostname should match an IPv6 iPAddress SAN";
  11040. EXPECT_FALSE(wrong_ipv6_matched)
  11041. << "verify_hostname should not match a non-matching IPv6 address";
  11042. EXPECT_FALSE(cn_ipv6_matched)
  11043. << "An IPv6 host must not be authenticated via the certificate CN";
  11044. }
  11045. #endif
  11046. // mbedTLS-specific callback constructor test
  11047. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  11048. #ifdef CPPHTTPLIB_SSL_ENABLED
  11049. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  11050. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11051. ASSERT_TRUE(svr.is_valid());
  11052. // Set up a handler to verify client certificate is present
  11053. bool client_cert_verified = false;
  11054. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11055. // Verify that client certificate was provided
  11056. client_cert_verified = true;
  11057. res.set_content("success", "text/plain");
  11058. });
  11059. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11060. auto se = detail::scope_exit([&] {
  11061. svr.stop();
  11062. t.join();
  11063. ASSERT_FALSE(svr.is_running());
  11064. });
  11065. svr.wait_until_ready();
  11066. // Client with certificate
  11067. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11068. cli.enable_server_certificate_verification(false);
  11069. cli.set_connection_timeout(30);
  11070. auto res = cli.Get("/test");
  11071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11072. ASSERT_EQ(StatusCode::OK_200, res->status);
  11073. ASSERT_TRUE(client_cert_verified);
  11074. EXPECT_EQ("success", res->body);
  11075. }
  11076. #endif
  11077. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  11078. // backends
  11079. #ifdef CPPHTTPLIB_SSL_ENABLED
  11080. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  11081. using namespace httplib::tls;
  11082. // Test that when client CA cert file is provided,
  11083. // the server properly requests and validates client certificates
  11084. // Create a server with client authentication
  11085. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11086. ASSERT_TRUE(svr.is_valid());
  11087. bool handler_called = false;
  11088. svr.Get("/test", [&](const Request &req, Response &res) {
  11089. handler_called = true;
  11090. // Verify that a client certificate was provided
  11091. auto cert = req.peer_cert();
  11092. ASSERT_TRUE(static_cast<bool>(cert));
  11093. // Get the issuer name
  11094. std::string issuer_str = cert.issuer_name();
  11095. ASSERT_FALSE(issuer_str.empty());
  11096. // The client certificate should be issued by our test CA
  11097. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  11098. res.set_content("authenticated", "text/plain");
  11099. });
  11100. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11101. auto se = detail::scope_exit([&] {
  11102. svr.stop();
  11103. t.join();
  11104. ASSERT_FALSE(svr.is_running());
  11105. });
  11106. svr.wait_until_ready();
  11107. // Connect with a client certificate issued by the CA
  11108. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11109. cli.enable_server_certificate_verification(false);
  11110. cli.set_connection_timeout(30);
  11111. auto res = cli.Get("/test");
  11112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11113. ASSERT_EQ(StatusCode::OK_200, res->status);
  11114. ASSERT_TRUE(handler_called);
  11115. EXPECT_EQ("authenticated", res->body);
  11116. }
  11117. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  11118. using namespace httplib::tls;
  11119. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11120. ASSERT_TRUE(svr.is_valid());
  11121. svr.Get("/test", [](const Request &, Response &res) {
  11122. res.set_content("ok", "text/plain");
  11123. });
  11124. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11125. auto se = detail::scope_exit([&] {
  11126. svr.stop();
  11127. t.join();
  11128. });
  11129. svr.wait_until_ready();
  11130. SSLClient cli(HOST, PORT);
  11131. cli.enable_server_certificate_verification(false);
  11132. cli.set_connection_timeout(30);
  11133. bool cert_checked = false;
  11134. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11135. if (ctx.cert) {
  11136. auto sans = ctx.sans();
  11137. // Test certificate may or may not have SANs - just verify the API
  11138. // works If SANs exist, verify the types are valid
  11139. for (const auto &san : sans) {
  11140. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  11141. san.type == SanType::EMAIL || san.type == SanType::URI ||
  11142. san.type == SanType::OTHER);
  11143. EXPECT_FALSE(san.value.empty());
  11144. }
  11145. cert_checked = true;
  11146. }
  11147. return true;
  11148. });
  11149. auto res = cli.Get("/test");
  11150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11151. EXPECT_TRUE(cert_checked);
  11152. }
  11153. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  11154. using namespace httplib::tls;
  11155. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11156. ASSERT_TRUE(svr.is_valid());
  11157. svr.Get("/test", [](const Request &, Response &res) {
  11158. res.set_content("ok", "text/plain");
  11159. });
  11160. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11161. auto se = detail::scope_exit([&] {
  11162. svr.stop();
  11163. t.join();
  11164. });
  11165. svr.wait_until_ready();
  11166. SSLClient cli(HOST, PORT);
  11167. cli.enable_server_certificate_verification(false);
  11168. cli.set_connection_timeout(30);
  11169. bool validity_checked = false;
  11170. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11171. if (ctx.cert) {
  11172. time_t not_before = 0, not_after = 0;
  11173. bool result = ctx.validity(not_before, not_after);
  11174. EXPECT_TRUE(result);
  11175. // Verify that not_before < now < not_after for a valid cert
  11176. time_t now = time(nullptr);
  11177. EXPECT_LT(not_before, now);
  11178. EXPECT_GT(not_after, now);
  11179. validity_checked = true;
  11180. }
  11181. return true;
  11182. });
  11183. auto res = cli.Get("/test");
  11184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11185. EXPECT_TRUE(validity_checked);
  11186. }
  11187. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  11188. using namespace httplib::tls;
  11189. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11190. ASSERT_TRUE(svr.is_valid());
  11191. svr.Get("/test", [](const Request &, Response &res) {
  11192. res.set_content("ok", "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. });
  11199. svr.wait_until_ready();
  11200. SSLClient cli(HOST, PORT);
  11201. cli.enable_server_certificate_verification(false);
  11202. cli.set_connection_timeout(30);
  11203. bool serial_checked = false;
  11204. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11205. if (ctx.cert) {
  11206. std::string serial = ctx.serial();
  11207. EXPECT_FALSE(serial.empty());
  11208. // Serial should be a hex string
  11209. for (char c : serial) {
  11210. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  11211. (c >= 'a' && c <= 'f'));
  11212. }
  11213. serial_checked = true;
  11214. }
  11215. return true;
  11216. });
  11217. auto res = cli.Get("/test");
  11218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11219. EXPECT_TRUE(serial_checked);
  11220. }
  11221. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  11222. // Test 1: Valid CA file - no error should be recorded
  11223. {
  11224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11225. CLIENT_CA_CERT_FILE);
  11226. ASSERT_TRUE(svr.is_valid());
  11227. // With valid setup, last_ssl_error should be 0
  11228. EXPECT_EQ(0, svr.ssl_last_error());
  11229. }
  11230. // Test 2: Invalid CA file content
  11231. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  11232. {
  11233. // Create a temporary file with completely invalid content
  11234. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  11235. {
  11236. std::ofstream ofs(temp_invalid_ca);
  11237. ofs << "This is not a certificate file at all\n";
  11238. ofs << "Just plain text content\n";
  11239. }
  11240. // Create server with invalid CA file
  11241. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  11242. // Clean up temporary file
  11243. std::remove(temp_invalid_ca);
  11244. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  11245. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  11246. // Note: SSL_CTX_load_verify_locations typically fails first,
  11247. // but our error handling code path is still exercised
  11248. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  11249. }
  11250. }
  11251. TEST(VerifyCallbackTest, VerifyContextFields) {
  11252. using namespace httplib::tls;
  11253. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11254. ASSERT_TRUE(svr.is_valid());
  11255. svr.Get("/test", [](const Request &, Response &res) {
  11256. res.set_content("ok", "text/plain");
  11257. });
  11258. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11259. auto se = detail::scope_exit([&] {
  11260. svr.stop();
  11261. t.join();
  11262. });
  11263. svr.wait_until_ready();
  11264. SSLClient cli(HOST, PORT);
  11265. cli.enable_server_certificate_verification(false);
  11266. cli.set_connection_timeout(30);
  11267. int callback_count = 0;
  11268. bool saw_leaf_cert = false;
  11269. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11270. if (ctx.cert) {
  11271. callback_count++;
  11272. // We should see at least one certificate (the leaf)
  11273. std::string cn = ctx.subject_cn();
  11274. if (!cn.empty()) { saw_leaf_cert = true; }
  11275. // Verify context fields are populated
  11276. EXPECT_NE(ctx.session, nullptr);
  11277. EXPECT_GE(ctx.depth, 0);
  11278. }
  11279. return true;
  11280. });
  11281. auto res = cli.Get("/test");
  11282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11283. EXPECT_GT(callback_count, 0);
  11284. EXPECT_TRUE(saw_leaf_cert);
  11285. }
  11286. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  11287. using httplib::tls::TlsError;
  11288. // Test that verify_error_to_string returns empty for success
  11289. std::string success_str = TlsError::verify_error_to_string(0);
  11290. EXPECT_TRUE(success_str.empty());
  11291. // Test that verify_error_to_string returns non-empty for error codes
  11292. // Using a common error code (certificate expired)
  11293. std::string error_str =
  11294. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  11295. EXPECT_FALSE(error_str.empty());
  11296. }
  11297. TEST(SessionVerifierTest, CertificateAccepted) {
  11298. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11299. ASSERT_TRUE(svr.is_valid());
  11300. svr.Get("/test", [](const Request &, Response &res) {
  11301. res.set_content("ok", "text/plain");
  11302. });
  11303. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11304. auto se = detail::scope_exit([&] {
  11305. svr.stop();
  11306. t.join();
  11307. });
  11308. svr.wait_until_ready();
  11309. SSLClient cli(HOST, PORT);
  11310. cli.enable_server_certificate_verification(false);
  11311. cli.set_connection_timeout(30);
  11312. bool callback_called = false;
  11313. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11314. EXPECT_NE(session, nullptr);
  11315. callback_called = true;
  11316. return SSLVerifierResponse::CertificateAccepted;
  11317. });
  11318. auto res = cli.Get("/test");
  11319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11320. EXPECT_EQ(200, res->status);
  11321. EXPECT_TRUE(callback_called);
  11322. }
  11323. TEST(SessionVerifierTest, CertificateRejected) {
  11324. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11325. ASSERT_TRUE(svr.is_valid());
  11326. svr.Get("/test", [](const Request &, Response &res) {
  11327. res.set_content("ok", "text/plain");
  11328. });
  11329. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11330. auto se = detail::scope_exit([&] {
  11331. svr.stop();
  11332. t.join();
  11333. });
  11334. svr.wait_until_ready();
  11335. SSLClient cli(HOST, PORT);
  11336. cli.enable_server_certificate_verification(false);
  11337. cli.set_connection_timeout(30);
  11338. bool callback_called = false;
  11339. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11340. EXPECT_NE(session, nullptr);
  11341. callback_called = true;
  11342. return SSLVerifierResponse::CertificateRejected;
  11343. });
  11344. auto res = cli.Get("/test");
  11345. EXPECT_FALSE(res);
  11346. EXPECT_TRUE(callback_called);
  11347. }
  11348. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11349. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11350. ASSERT_TRUE(svr.is_valid());
  11351. svr.Get("/test", [](const Request &, Response &res) {
  11352. res.set_content("ok", "text/plain");
  11353. });
  11354. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11355. auto se = detail::scope_exit([&] {
  11356. svr.stop();
  11357. t.join();
  11358. });
  11359. svr.wait_until_ready();
  11360. // NoDecisionMade with verification disabled should succeed (no default check)
  11361. SSLClient cli(HOST, PORT);
  11362. cli.enable_server_certificate_verification(false);
  11363. cli.set_connection_timeout(30);
  11364. bool callback_called = false;
  11365. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11366. EXPECT_NE(session, nullptr);
  11367. callback_called = true;
  11368. return SSLVerifierResponse::NoDecisionMade;
  11369. });
  11370. auto res = cli.Get("/test");
  11371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11372. EXPECT_EQ(200, res->status);
  11373. EXPECT_TRUE(callback_called);
  11374. }
  11375. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11377. ASSERT_TRUE(svr.is_valid());
  11378. svr.Get("/test", [](const Request &, Response &res) {
  11379. res.set_content("ok", "text/plain");
  11380. });
  11381. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11382. auto se = detail::scope_exit([&] {
  11383. svr.stop();
  11384. t.join();
  11385. });
  11386. svr.wait_until_ready();
  11387. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11388. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11389. // so we only check that the request fails, not whether the callback was
  11390. // called.
  11391. SSLClient cli(HOST, PORT);
  11392. cli.enable_server_certificate_verification(true);
  11393. cli.set_connection_timeout(30);
  11394. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11395. EXPECT_NE(session, nullptr);
  11396. return SSLVerifierResponse::NoDecisionMade;
  11397. });
  11398. auto res = cli.Get("/test");
  11399. EXPECT_FALSE(res);
  11400. }
  11401. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11402. // Test SSL server using PemMemory constructor with client CA certificates
  11403. // Read PEM files
  11404. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11405. read_file(SERVER_CERT_FILE, server_cert_pem);
  11406. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11407. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11408. // Create SSLServer with PemMemory constructor including client CA
  11409. SSLServer::PemMemory server_pem = {
  11410. server_cert_pem.c_str(),
  11411. server_cert_pem.size(),
  11412. server_key_pem.c_str(),
  11413. server_key_pem.size(),
  11414. client_ca_pem.c_str(),
  11415. client_ca_pem.size(),
  11416. nullptr // no password for server key
  11417. };
  11418. SSLServer svr(server_pem);
  11419. ASSERT_TRUE(svr.is_valid());
  11420. // No SSL error should be recorded for valid setup
  11421. EXPECT_EQ(0, svr.ssl_last_error());
  11422. // Set up server endpoints
  11423. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11424. res.set_content("ok", "text/plain");
  11425. });
  11426. // Start server in a thread
  11427. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11428. svr.wait_until_ready();
  11429. // Connect with client certificate (using constructor with paths)
  11430. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11431. cli.enable_server_certificate_verification(false);
  11432. auto res = cli.Get("/test-pem-ca");
  11433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11434. EXPECT_EQ(200, res->status);
  11435. EXPECT_EQ("ok", res->body);
  11436. svr.stop();
  11437. server_thread.join();
  11438. }
  11439. #endif
  11440. #ifdef _WIN32
  11441. TEST(CleanupTest, WSACleanup) {
  11442. int ret = WSACleanup();
  11443. ASSERT_EQ(0, ret);
  11444. }
  11445. #endif
  11446. #ifndef CPPHTTPLIB_SSL_ENABLED
  11447. TEST(NoSSLSupport, SimpleInterface) {
  11448. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11449. }
  11450. #endif
  11451. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11452. TEST(InvalidScheme, SimpleInterface) {
  11453. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11454. }
  11455. #endif
  11456. TEST(NoScheme, SimpleInterface) {
  11457. Client cli("yahoo.com:80");
  11458. ASSERT_TRUE(cli.is_valid());
  11459. }
  11460. TEST(SendAPI, SimpleInterface_Online) {
  11461. Client cli("http://yahoo.com");
  11462. Request req;
  11463. req.method = "GET";
  11464. req.path = "/";
  11465. auto res = cli.send(req);
  11466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11467. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11468. }
  11469. TEST(SendAPI, WithParamsInRequest) {
  11470. Server svr;
  11471. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11472. EXPECT_TRUE(req.has_param("test"));
  11473. EXPECT_EQ("test_value", req.get_param_value("test"));
  11474. });
  11475. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11476. auto se = detail::scope_exit([&] {
  11477. svr.stop();
  11478. t.join();
  11479. ASSERT_FALSE(svr.is_running());
  11480. });
  11481. svr.wait_until_ready();
  11482. Client cli(HOST, PORT);
  11483. {
  11484. Request req;
  11485. req.method = "GET";
  11486. req.path = "/";
  11487. req.params.emplace("test", "test_value");
  11488. auto res = cli.send(req);
  11489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11490. }
  11491. {
  11492. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11494. }
  11495. }
  11496. TEST(ClientImplMethods, GetSocketTest) {
  11497. httplib::Server svr;
  11498. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11499. res.status = StatusCode::OK_200;
  11500. });
  11501. auto port = svr.bind_to_any_port("127.0.0.1");
  11502. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11503. auto se = detail::scope_exit([&] {
  11504. svr.stop();
  11505. thread.join();
  11506. ASSERT_FALSE(svr.is_running());
  11507. });
  11508. svr.wait_until_ready();
  11509. {
  11510. httplib::Client cli("127.0.0.1", port);
  11511. cli.set_keep_alive(true);
  11512. // Use the behavior of cpp-httplib of opening the connection
  11513. // only when the first request happens. If that changes,
  11514. // this test would be obsolete.
  11515. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11516. // This also implicitly tests the server. But other tests would fail much
  11517. // earlier than this one to be considered.
  11518. auto res = cli.Get("/");
  11519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11520. EXPECT_EQ(StatusCode::OK_200, res->status);
  11521. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11522. }
  11523. }
  11524. #ifdef CPPHTTPLIB_SSL_ENABLED
  11525. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11526. Client cli("http://yahoo.com");
  11527. auto res = cli.Get("/");
  11528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11529. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11530. cli.set_follow_location(true);
  11531. res = cli.Get("/");
  11532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11533. EXPECT_EQ(StatusCode::OK_200, res->status);
  11534. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11535. }
  11536. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11537. Client cli("https://yahoo.com");
  11538. auto res = cli.Get("/");
  11539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11540. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11541. cli.set_follow_location(true);
  11542. res = cli.Get("/");
  11543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11544. EXPECT_EQ(StatusCode::OK_200, res->status);
  11545. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11546. }
  11547. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11548. Client cli("https://yahoo.com");
  11549. auto res = cli.Get("/");
  11550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11551. ASSERT_FALSE(!res);
  11552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11553. ASSERT_FALSE(res == nullptr);
  11554. ASSERT_TRUE(res != nullptr);
  11555. EXPECT_EQ(Error::Success, res.error());
  11556. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11557. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11558. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11559. cli.set_follow_location(true);
  11560. res = cli.Get("/");
  11561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11562. EXPECT_EQ(Error::Success, res.error());
  11563. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11564. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11565. EXPECT_EQ(StatusCode::OK_200, res->status);
  11566. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11567. }
  11568. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11569. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11570. Client cli("https://cdnjs.cloudflare.com");
  11571. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11572. Headers{{"Accept-Encoding", "br"}});
  11573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11574. EXPECT_EQ(StatusCode::OK_200, res->status);
  11575. EXPECT_EQ(287630U, res->body.size());
  11576. EXPECT_EQ("application/javascript; charset=utf-8",
  11577. res->get_header_value("Content-Type"));
  11578. }
  11579. #endif
  11580. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11581. #undef REDIR_HOST // Silence compiler warning
  11582. #define REDIR_HOST "https://httpbingo.org"
  11583. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11584. Client cli(REDIR_HOST);
  11585. cli.set_follow_location(true);
  11586. auto res =
  11587. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11589. EXPECT_EQ(StatusCode::OK_200, res->status);
  11590. }
  11591. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11592. Client cli(REDIR_HOST);
  11593. cli.set_follow_location(true);
  11594. Params params;
  11595. params.emplace("url", "http://example.com");
  11596. params.emplace("status_code", "302");
  11597. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11599. EXPECT_EQ(StatusCode::OK_200, res->status);
  11600. }
  11601. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11602. Client cli(REDIR_HOST);
  11603. cli.set_follow_location(true);
  11604. Params params;
  11605. params.emplace("url", "http://example.com");
  11606. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11608. EXPECT_EQ(StatusCode::OK_200, res->status);
  11609. }
  11610. TEST(HttpToHttpsRedirectTest, CertFile) {
  11611. auto ssl_port = PORT + 1;
  11612. Server svr;
  11613. ASSERT_TRUE(svr.is_valid());
  11614. svr.Get("/index", [&](const Request &, Response &res) {
  11615. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11616. "/index");
  11617. svr.stop();
  11618. });
  11619. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11620. ASSERT_TRUE(ssl_svr.is_valid());
  11621. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11622. res.set_content("test", "text/plain");
  11623. ssl_svr.stop();
  11624. });
  11625. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11626. thread t2 =
  11627. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11628. auto se = detail::scope_exit([&] {
  11629. t2.join();
  11630. t.join();
  11631. ASSERT_FALSE(svr.is_running());
  11632. });
  11633. svr.wait_until_ready();
  11634. ssl_svr.wait_until_ready();
  11635. Client cli("127.0.0.1", PORT);
  11636. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11637. cli.enable_server_certificate_verification(true);
  11638. cli.set_follow_location(true);
  11639. cli.set_connection_timeout(30);
  11640. auto res = cli.Get("/index");
  11641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11642. ASSERT_EQ(StatusCode::OK_200, res->status);
  11643. }
  11644. TEST(SSLClientRedirectTest, CertFile) {
  11645. auto ssl_port = PORT + 1;
  11646. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11647. ASSERT_TRUE(ssl_svr1.is_valid());
  11648. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11649. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11650. "/index");
  11651. ssl_svr1.stop();
  11652. });
  11653. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11654. ASSERT_TRUE(ssl_svr2.is_valid());
  11655. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11656. res.set_content("test", "text/plain");
  11657. ssl_svr2.stop();
  11658. });
  11659. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11660. thread t2 =
  11661. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11662. auto se = detail::scope_exit([&] {
  11663. t2.join();
  11664. t.join();
  11665. ASSERT_FALSE(ssl_svr1.is_running());
  11666. });
  11667. ssl_svr1.wait_until_ready();
  11668. ssl_svr2.wait_until_ready();
  11669. SSLClient cli("127.0.0.1", PORT);
  11670. std::string cert;
  11671. read_file(SERVER_CERT2_FILE, cert);
  11672. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11673. cli.enable_server_certificate_verification(true);
  11674. cli.set_follow_location(true);
  11675. cli.set_connection_timeout(30);
  11676. auto res = cli.Get("/index");
  11677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11678. ASSERT_EQ(StatusCode::OK_200, res->status);
  11679. }
  11680. #endif
  11681. #ifdef CPPHTTPLIB_SSL_ENABLED
  11682. // Test that set_ca_cert_store() skips system certs (consistent with
  11683. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11684. // should be trusted - system certs should NOT be loaded.
  11685. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11686. // Load a specific cert that is NOT a system CA cert
  11687. std::string cert;
  11688. read_file(SERVER_CERT2_FILE, cert);
  11689. SSLClient cli("google.com");
  11690. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11691. cli.enable_server_certificate_verification(true);
  11692. // This should FAIL because:
  11693. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11694. // 2. System certs should NOT be loaded when custom store is set
  11695. // If system certs WERE loaded, this would succeed
  11696. auto res = cli.Get("/");
  11697. ASSERT_FALSE(res);
  11698. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11699. }
  11700. // Same as above, but through the native store handle path. Regression test:
  11701. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11702. // merged system certs into the user-provided store.
  11703. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11704. std::string cert;
  11705. read_file(SERVER_CERT2_FILE, cert);
  11706. SSLClient cli("google.com");
  11707. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11708. cli.enable_server_certificate_verification(true);
  11709. auto res = cli.Get("/");
  11710. ASSERT_FALSE(res);
  11711. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11712. }
  11713. // A custom store set via the native handle must still verify a server whose
  11714. // cert it does contain.
  11715. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11716. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11717. ASSERT_TRUE(svr.is_valid());
  11718. svr.Get("/test", [&](const Request &, Response &res) {
  11719. res.set_content("test", "text/plain");
  11720. });
  11721. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11722. auto se = detail::scope_exit([&] {
  11723. svr.stop();
  11724. t.join();
  11725. ASSERT_FALSE(svr.is_running());
  11726. });
  11727. svr.wait_until_ready();
  11728. SSLClient cli("127.0.0.1", PORT);
  11729. std::string cert;
  11730. read_file(SERVER_CERT2_FILE, cert);
  11731. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11732. cli.enable_server_certificate_verification(true);
  11733. cli.set_connection_timeout(30);
  11734. auto res = cli.Get("/test");
  11735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11736. ASSERT_EQ(StatusCode::OK_200, res->status);
  11737. }
  11738. // CA certs loaded through the universal Client must be transferred to the
  11739. // client created internally for following an HTTPS redirect. Regression test:
  11740. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11741. // the CA data for redirect transfer.
  11742. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11743. auto ssl_port = PORT + 1;
  11744. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11745. ASSERT_TRUE(ssl_svr1.is_valid());
  11746. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11747. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11748. "/index");
  11749. });
  11750. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11751. ASSERT_TRUE(ssl_svr2.is_valid());
  11752. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11753. res.set_content("test", "text/plain");
  11754. });
  11755. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11756. thread t2 =
  11757. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11758. auto se = detail::scope_exit([&] {
  11759. ssl_svr2.stop();
  11760. ssl_svr1.stop();
  11761. t2.join();
  11762. t.join();
  11763. ASSERT_FALSE(ssl_svr1.is_running());
  11764. });
  11765. ssl_svr1.wait_until_ready();
  11766. ssl_svr2.wait_until_ready();
  11767. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11768. std::string cert;
  11769. read_file(SERVER_CERT2_FILE, cert);
  11770. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11771. cli.enable_server_certificate_verification(true);
  11772. cli.set_follow_location(true);
  11773. cli.set_connection_timeout(30);
  11774. auto res = cli.Get("/index");
  11775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11776. ASSERT_EQ(StatusCode::OK_200, res->status);
  11777. }
  11778. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11779. // so a host signed by a system CA verifies even though a custom CA is set
  11780. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  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_system_ca(true);
  11786. cli.enable_server_certificate_verification(true);
  11787. auto res = cli.Get("/");
  11788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11789. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11790. }
  11791. // The custom CA remains effective when combined with the system CA
  11792. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11793. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11794. ASSERT_TRUE(svr.is_valid());
  11795. svr.Get("/test", [&](const Request &, Response &res) {
  11796. res.set_content("test", "text/plain");
  11797. });
  11798. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11799. auto se = detail::scope_exit([&] {
  11800. svr.stop();
  11801. t.join();
  11802. ASSERT_FALSE(svr.is_running());
  11803. });
  11804. svr.wait_until_ready();
  11805. SSLClient cli("127.0.0.1", PORT);
  11806. std::string cert;
  11807. read_file(SERVER_CERT2_FILE, cert);
  11808. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11809. cli.enable_system_ca(true);
  11810. cli.enable_server_certificate_verification(true);
  11811. cli.set_connection_timeout(30);
  11812. auto res = cli.Get("/test");
  11813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11814. ASSERT_EQ(StatusCode::OK_200, res->status);
  11815. }
  11816. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11817. // skip chain verification entirely (only the certificate identity was
  11818. // checked), so a server presenting an untrusted certificate with a matching
  11819. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11820. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11821. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11822. ASSERT_TRUE(svr.is_valid());
  11823. svr.Get("/test", [&](const Request &, Response &res) {
  11824. res.set_content("test", "text/plain");
  11825. });
  11826. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11827. auto se = detail::scope_exit([&] {
  11828. svr.stop();
  11829. t.join();
  11830. ASSERT_FALSE(svr.is_running());
  11831. });
  11832. svr.wait_until_ready();
  11833. SSLClient cli("127.0.0.1", PORT);
  11834. std::string cert;
  11835. // A trusted CA that did not sign the server certificate. The server cert
  11836. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11837. // this connection.
  11838. read_file(CLIENT_CA_CERT_FILE, cert);
  11839. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11840. cli.enable_server_certificate_verification(true);
  11841. cli.set_connection_timeout(30);
  11842. auto res = cli.Get("/test");
  11843. ASSERT_FALSE(res);
  11844. }
  11845. // enable_system_ca(false) prevents system CA loading entirely
  11846. TEST(SSLClientTest, DisableSystemCa_Online) {
  11847. SSLClient cli("google.com");
  11848. cli.enable_system_ca(false);
  11849. cli.enable_server_certificate_verification(true);
  11850. auto res = cli.Get("/");
  11851. ASSERT_FALSE(res);
  11852. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11853. // itself when the CA chain is empty
  11854. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11855. res.error() == Error::SSLConnection);
  11856. }
  11857. // The universal Client forwards enable_system_ca()
  11858. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11859. std::string cert;
  11860. read_file(SERVER_CERT2_FILE, cert);
  11861. Client cli("https://google.com");
  11862. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11863. cli.enable_system_ca(true);
  11864. cli.enable_server_certificate_verification(true);
  11865. auto res = cli.Get("/");
  11866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11867. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11868. }
  11869. // The system CA policy must carry over to the client created internally for
  11870. // following a cross-host HTTPS redirect
  11871. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11872. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11873. ASSERT_TRUE(svr.is_valid());
  11874. svr.Get("/index", [&](const Request &, Response &res) {
  11875. res.set_redirect("https://www.google.com/");
  11876. });
  11877. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11878. auto se = detail::scope_exit([&] {
  11879. svr.stop();
  11880. t.join();
  11881. ASSERT_FALSE(svr.is_running());
  11882. });
  11883. svr.wait_until_ready();
  11884. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11885. std::string cert;
  11886. read_file(SERVER_CERT2_FILE, cert);
  11887. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11888. cli.enable_system_ca(true);
  11889. cli.enable_server_certificate_verification(true);
  11890. cli.set_follow_location(true);
  11891. cli.set_connection_timeout(30);
  11892. // Receiving any response proves the redirect client completed the TLS
  11893. // handshake with a system-CA-signed host
  11894. auto res = cli.Get("/index");
  11895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11896. }
  11897. TEST(MultipartFormDataTest, LargeData) {
  11898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11899. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11900. const ContentReader &content_reader) {
  11901. if (req.is_multipart_form_data()) {
  11902. std::vector<FormData> items;
  11903. content_reader(
  11904. [&](const FormData &file) {
  11905. items.push_back(file);
  11906. return true;
  11907. },
  11908. [&](const char *data, size_t data_length) {
  11909. items.back().content.append(data, data_length);
  11910. return true;
  11911. });
  11912. EXPECT_TRUE(std::string(items[0].name) == "document");
  11913. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11914. EXPECT_TRUE(items[0].filename == "2MB_data");
  11915. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11916. EXPECT_TRUE(items[1].name == "hello");
  11917. EXPECT_TRUE(items[1].content == "world");
  11918. EXPECT_TRUE(items[1].filename == "");
  11919. EXPECT_TRUE(items[1].content_type == "");
  11920. } else {
  11921. std::string body;
  11922. content_reader([&](const char *data, size_t data_length) {
  11923. body.append(data, data_length);
  11924. return true;
  11925. });
  11926. }
  11927. });
  11928. auto port = svr.bind_to_any_port(HOST);
  11929. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11930. auto se = detail::scope_exit([&] {
  11931. svr.stop();
  11932. t.join();
  11933. ASSERT_FALSE(svr.is_running());
  11934. });
  11935. svr.wait_until_ready();
  11936. {
  11937. std::string data(1024 * 1024 * 2, '.');
  11938. std::stringstream buffer;
  11939. buffer << data;
  11940. SSLClient cli(HOST, port);
  11941. cli.enable_server_certificate_verification(false);
  11942. UploadFormDataItems items{
  11943. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11944. {"hello", "world", "", ""},
  11945. };
  11946. auto res = cli.Post("/post", items);
  11947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11948. ASSERT_EQ(StatusCode::OK_200, res->status);
  11949. }
  11950. }
  11951. TEST(MultipartFormDataTest, DataProviderItems) {
  11952. std::random_device seed_gen;
  11953. std::mt19937 random(seed_gen());
  11954. std::string rand1;
  11955. rand1.resize(1000);
  11956. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11957. std::string rand2;
  11958. rand2.resize(3000);
  11959. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11960. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11961. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11962. const ContentReader &content_reader) {
  11963. ASSERT_FALSE(req.is_multipart_form_data());
  11964. std::string body;
  11965. content_reader([&](const char *data, size_t data_length) {
  11966. body.append(data, data_length);
  11967. return true;
  11968. });
  11969. EXPECT_EQ(body, "");
  11970. });
  11971. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11972. const ContentReader &content_reader) {
  11973. ASSERT_TRUE(req.is_multipart_form_data());
  11974. std::vector<FormData> items;
  11975. content_reader(
  11976. [&](const FormData &file) {
  11977. items.push_back(file);
  11978. return true;
  11979. },
  11980. [&](const char *data, size_t data_length) {
  11981. items.back().content.append(data, data_length);
  11982. return true;
  11983. });
  11984. ASSERT_TRUE(items.size() == 2);
  11985. EXPECT_EQ(std::string(items[0].name), "name1");
  11986. EXPECT_EQ(items[0].content, "Testing123");
  11987. EXPECT_EQ(items[0].filename, "filename1");
  11988. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11989. EXPECT_EQ(items[1].name, "name2");
  11990. EXPECT_EQ(items[1].content, "Testing456");
  11991. EXPECT_EQ(items[1].filename, "");
  11992. EXPECT_EQ(items[1].content_type, "");
  11993. });
  11994. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11995. const ContentReader &content_reader) {
  11996. ASSERT_TRUE(req.is_multipart_form_data());
  11997. std::vector<FormData> items;
  11998. content_reader(
  11999. [&](const FormData &file) {
  12000. items.push_back(file);
  12001. return true;
  12002. },
  12003. [&](const char *data, size_t data_length) {
  12004. items.back().content.append(data, data_length);
  12005. return true;
  12006. });
  12007. ASSERT_TRUE(items.size() == 2);
  12008. EXPECT_EQ(items[0].name, "name3");
  12009. EXPECT_EQ(items[0].content, rand1);
  12010. EXPECT_EQ(items[0].filename, "filename3");
  12011. EXPECT_EQ(items[0].content_type, "");
  12012. EXPECT_EQ(items[1].name, "name4");
  12013. EXPECT_EQ(items[1].content, rand2);
  12014. EXPECT_EQ(items[1].filename, "filename4");
  12015. EXPECT_EQ(items[1].content_type, "");
  12016. });
  12017. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  12018. const ContentReader &content_reader) {
  12019. ASSERT_TRUE(req.is_multipart_form_data());
  12020. std::vector<FormData> items;
  12021. content_reader(
  12022. [&](const FormData &file) {
  12023. items.push_back(file);
  12024. return true;
  12025. },
  12026. [&](const char *data, size_t data_length) {
  12027. items.back().content.append(data, data_length);
  12028. return true;
  12029. });
  12030. ASSERT_TRUE(items.size() == 4);
  12031. EXPECT_EQ(std::string(items[0].name), "name1");
  12032. EXPECT_EQ(items[0].content, "Testing123");
  12033. EXPECT_EQ(items[0].filename, "filename1");
  12034. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12035. EXPECT_EQ(items[1].name, "name2");
  12036. EXPECT_EQ(items[1].content, "Testing456");
  12037. EXPECT_EQ(items[1].filename, "");
  12038. EXPECT_EQ(items[1].content_type, "");
  12039. EXPECT_EQ(items[2].name, "name3");
  12040. EXPECT_EQ(items[2].content, rand1);
  12041. EXPECT_EQ(items[2].filename, "filename3");
  12042. EXPECT_EQ(items[2].content_type, "");
  12043. EXPECT_EQ(items[3].name, "name4");
  12044. EXPECT_EQ(items[3].content, rand2);
  12045. EXPECT_EQ(items[3].filename, "filename4");
  12046. EXPECT_EQ(items[3].content_type, "");
  12047. });
  12048. auto port = svr.bind_to_any_port("localhost");
  12049. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12050. auto se = detail::scope_exit([&] {
  12051. svr.stop();
  12052. t.join();
  12053. ASSERT_FALSE(svr.is_running());
  12054. });
  12055. svr.wait_until_ready();
  12056. {
  12057. SSLClient cli("localhost", port);
  12058. cli.enable_server_certificate_verification(false);
  12059. UploadFormDataItems items{
  12060. {"name1", "Testing123", "filename1", "application/octet-stream"},
  12061. {"name2", "Testing456", "", ""}, // not a file
  12062. };
  12063. {
  12064. auto res = cli.Post("/post-none", {}, {}, {});
  12065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12066. ASSERT_EQ(StatusCode::OK_200, res->status);
  12067. }
  12068. FormDataProviderItems providers;
  12069. {
  12070. auto res =
  12071. cli.Post("/post-items", {}, items, providers); // empty providers
  12072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12073. ASSERT_EQ(StatusCode::OK_200, res->status);
  12074. }
  12075. providers.push_back({"name3",
  12076. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12077. // test the offset is given correctly at each step
  12078. if (!offset)
  12079. sink.os.write(rand1.data(), 30);
  12080. else if (offset == 30)
  12081. sink.os.write(rand1.data() + 30, 300);
  12082. else if (offset == 330)
  12083. sink.os.write(rand1.data() + 330, 670);
  12084. else if (offset == rand1.size())
  12085. sink.done();
  12086. return true;
  12087. },
  12088. "filename3",
  12089. {}});
  12090. providers.push_back({"name4",
  12091. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12092. // test the offset is given correctly at each step
  12093. if (!offset)
  12094. sink.os.write(rand2.data(), 2000);
  12095. else if (offset == 2000)
  12096. sink.os.write(rand2.data() + 2000, 1);
  12097. else if (offset == 2001)
  12098. sink.os.write(rand2.data() + 2001, 999);
  12099. else if (offset == rand2.size())
  12100. sink.done();
  12101. return true;
  12102. },
  12103. "filename4",
  12104. {}});
  12105. {
  12106. auto res = cli.Post("/post-providers", {}, {}, providers);
  12107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12108. ASSERT_EQ(StatusCode::OK_200, res->status);
  12109. }
  12110. {
  12111. auto res = cli.Post("/post-both", {}, items, providers);
  12112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12113. ASSERT_EQ(StatusCode::OK_200, res->status);
  12114. }
  12115. }
  12116. }
  12117. TEST(MultipartFormDataTest, BadHeader) {
  12118. Server svr;
  12119. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12120. res.set_content("ok", "text/plain");
  12121. });
  12122. thread t = thread([&] { svr.listen(HOST, PORT); });
  12123. auto se = detail::scope_exit([&] {
  12124. svr.stop();
  12125. t.join();
  12126. ASSERT_FALSE(svr.is_running());
  12127. });
  12128. svr.wait_until_ready();
  12129. const std::string body =
  12130. "This is the preamble. It is to be ignored, though it\r\n"
  12131. "is a handy place for composition agents to include an\r\n"
  12132. "explanatory note to non-MIME conformant readers.\r\n"
  12133. "\r\n"
  12134. "\r\n"
  12135. "--simple boundary\r\n"
  12136. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12137. ": BAD...\r\n"
  12138. "\r\n"
  12139. "value1\r\n"
  12140. "--simple boundary\r\n"
  12141. "Content-Disposition: form-data; name=\"field2\"; "
  12142. "filename=\"example.txt\"\r\n"
  12143. "\r\n"
  12144. "value2\r\n"
  12145. "--simple boundary--\r\n"
  12146. "This is the epilogue. It is also to be ignored.\r\n";
  12147. std::string content_type =
  12148. R"(multipart/form-data; boundary="simple boundary")";
  12149. Client cli(HOST, PORT);
  12150. auto res = cli.Post("/post", body, content_type.c_str());
  12151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12152. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12153. }
  12154. TEST(MultipartFormDataTest, WithPreamble) {
  12155. Server svr;
  12156. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12157. res.set_content("ok", "text/plain");
  12158. });
  12159. thread t = thread([&] { svr.listen(HOST, PORT); });
  12160. auto se = detail::scope_exit([&] {
  12161. svr.stop();
  12162. t.join();
  12163. ASSERT_FALSE(svr.is_running());
  12164. });
  12165. svr.wait_until_ready();
  12166. const std::string body =
  12167. "This is the preamble. It is to be ignored, though it\r\n"
  12168. "is a handy place for composition agents to include an\r\n"
  12169. "explanatory note to non-MIME conformant readers.\r\n"
  12170. "\r\n"
  12171. "\r\n"
  12172. "--simple boundary\r\n"
  12173. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12174. "\r\n"
  12175. "value1\r\n"
  12176. "--simple boundary\r\n"
  12177. "Content-Disposition: form-data; name=\"field2\"; "
  12178. "filename=\"example.txt\"\r\n"
  12179. "\r\n"
  12180. "value2\r\n"
  12181. "--simple boundary--\r\n"
  12182. "This is the epilogue. It is also to be ignored.\r\n";
  12183. std::string content_type =
  12184. R"(multipart/form-data; boundary="simple boundary")";
  12185. Client cli(HOST, PORT);
  12186. auto res = cli.Post("/post", body, content_type.c_str());
  12187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12188. EXPECT_EQ(StatusCode::OK_200, res->status);
  12189. }
  12190. TEST(MultipartFormDataTest, PostCustomBoundary) {
  12191. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12192. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  12193. const ContentReader &content_reader) {
  12194. if (req.is_multipart_form_data()) {
  12195. std::vector<FormData> items;
  12196. content_reader(
  12197. [&](const FormData &file) {
  12198. items.push_back(file);
  12199. return true;
  12200. },
  12201. [&](const char *data, size_t data_length) {
  12202. items.back().content.append(data, data_length);
  12203. return true;
  12204. });
  12205. EXPECT_TRUE(std::string(items[0].name) == "document");
  12206. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12207. EXPECT_TRUE(items[0].filename == "2MB_data");
  12208. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12209. EXPECT_TRUE(items[1].name == "hello");
  12210. EXPECT_TRUE(items[1].content == "world");
  12211. EXPECT_TRUE(items[1].filename == "");
  12212. EXPECT_TRUE(items[1].content_type == "");
  12213. } else {
  12214. std::string body;
  12215. content_reader([&](const char *data, size_t data_length) {
  12216. body.append(data, data_length);
  12217. return true;
  12218. });
  12219. }
  12220. });
  12221. auto port = svr.bind_to_any_port("localhost");
  12222. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12223. auto se = detail::scope_exit([&] {
  12224. svr.stop();
  12225. t.join();
  12226. ASSERT_FALSE(svr.is_running());
  12227. });
  12228. svr.wait_until_ready();
  12229. {
  12230. std::string data(1024 * 1024 * 2, '.');
  12231. std::stringstream buffer;
  12232. buffer << data;
  12233. SSLClient cli("localhost", port);
  12234. cli.enable_server_certificate_verification(false);
  12235. UploadFormDataItems items{
  12236. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12237. {"hello", "world", "", ""},
  12238. };
  12239. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  12240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12241. ASSERT_EQ(StatusCode::OK_200, res->status);
  12242. }
  12243. }
  12244. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  12245. std::string data(1024 * 1024 * 2, '&');
  12246. std::stringstream buffer;
  12247. buffer << data;
  12248. Client cli("https://localhost:8080");
  12249. UploadFormDataItems items{
  12250. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12251. {"hello", "world", "", ""},
  12252. };
  12253. for (const char &c : " \t\r\n") {
  12254. auto res =
  12255. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  12256. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12257. ASSERT_FALSE(res);
  12258. }
  12259. }
  12260. TEST(MultipartFormDataTest, PutFormData) {
  12261. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12262. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  12263. const ContentReader &content_reader) {
  12264. if (req.is_multipart_form_data()) {
  12265. std::vector<FormData> items;
  12266. content_reader(
  12267. [&](const FormData &file) {
  12268. items.push_back(file);
  12269. return true;
  12270. },
  12271. [&](const char *data, size_t data_length) {
  12272. items.back().content.append(data, data_length);
  12273. return true;
  12274. });
  12275. EXPECT_TRUE(std::string(items[0].name) == "document");
  12276. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12277. EXPECT_TRUE(items[0].filename == "2MB_data");
  12278. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12279. EXPECT_TRUE(items[1].name == "hello");
  12280. EXPECT_TRUE(items[1].content == "world");
  12281. EXPECT_TRUE(items[1].filename == "");
  12282. EXPECT_TRUE(items[1].content_type == "");
  12283. } else {
  12284. std::string body;
  12285. content_reader([&](const char *data, size_t data_length) {
  12286. body.append(data, data_length);
  12287. return true;
  12288. });
  12289. }
  12290. });
  12291. auto port = svr.bind_to_any_port("localhost");
  12292. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12293. auto se = detail::scope_exit([&] {
  12294. svr.stop();
  12295. t.join();
  12296. ASSERT_FALSE(svr.is_running());
  12297. });
  12298. svr.wait_until_ready();
  12299. {
  12300. std::string data(1024 * 1024 * 2, '&');
  12301. std::stringstream buffer;
  12302. buffer << data;
  12303. SSLClient cli("localhost", port);
  12304. cli.enable_server_certificate_verification(false);
  12305. UploadFormDataItems items{
  12306. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12307. {"hello", "world", "", ""},
  12308. };
  12309. auto res = cli.Put("/put", items);
  12310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12311. ASSERT_EQ(StatusCode::OK_200, res->status);
  12312. }
  12313. }
  12314. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  12315. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12316. svr.Put("/put_customboundary",
  12317. [&](const Request &req, const Response & /*res*/,
  12318. const ContentReader &content_reader) {
  12319. if (req.is_multipart_form_data()) {
  12320. std::vector<FormData> items;
  12321. content_reader(
  12322. [&](const FormData &file) {
  12323. items.push_back(file);
  12324. return true;
  12325. },
  12326. [&](const char *data, size_t data_length) {
  12327. items.back().content.append(data, data_length);
  12328. return true;
  12329. });
  12330. EXPECT_TRUE(std::string(items[0].name) == "document");
  12331. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12332. EXPECT_TRUE(items[0].filename == "2MB_data");
  12333. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12334. EXPECT_TRUE(items[1].name == "hello");
  12335. EXPECT_TRUE(items[1].content == "world");
  12336. EXPECT_TRUE(items[1].filename == "");
  12337. EXPECT_TRUE(items[1].content_type == "");
  12338. } else {
  12339. std::string body;
  12340. content_reader([&](const char *data, size_t data_length) {
  12341. body.append(data, data_length);
  12342. return true;
  12343. });
  12344. }
  12345. });
  12346. auto port = svr.bind_to_any_port("localhost");
  12347. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12348. auto se = detail::scope_exit([&] {
  12349. svr.stop();
  12350. t.join();
  12351. ASSERT_FALSE(svr.is_running());
  12352. });
  12353. svr.wait_until_ready();
  12354. {
  12355. std::string data(1024 * 1024 * 2, '&');
  12356. std::stringstream buffer;
  12357. buffer << data;
  12358. SSLClient cli("localhost", port);
  12359. cli.enable_server_certificate_verification(false);
  12360. UploadFormDataItems items{
  12361. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12362. {"hello", "world", "", ""},
  12363. };
  12364. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12366. ASSERT_EQ(StatusCode::OK_200, res->status);
  12367. }
  12368. }
  12369. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12370. std::string data(1024 * 1024 * 2, '&');
  12371. std::stringstream buffer;
  12372. buffer << data;
  12373. Client cli("https://localhost:8080");
  12374. cli.enable_server_certificate_verification(false);
  12375. UploadFormDataItems items{
  12376. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12377. {"hello", "world", "", ""},
  12378. };
  12379. for (const char &c : " \t\r\n") {
  12380. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12381. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12382. ASSERT_FALSE(res);
  12383. }
  12384. }
  12385. TEST(MultipartFormDataTest, AlternateFilename) {
  12386. auto handled = false;
  12387. Server svr;
  12388. svr.Post("/test", [&](const Request &req, Response &res) {
  12389. ASSERT_EQ(2u, req.form.files.size());
  12390. ASSERT_EQ(1u, req.form.fields.size());
  12391. // Test files
  12392. const auto &file1 = req.form.get_file("file1");
  12393. ASSERT_EQ("file1", file1.name);
  12394. ASSERT_EQ("A.txt", file1.filename);
  12395. ASSERT_EQ("text/plain", file1.content_type);
  12396. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12397. const auto &file2 = req.form.get_file("file2");
  12398. ASSERT_EQ("file2", file2.name);
  12399. ASSERT_EQ("a.html", file2.filename);
  12400. ASSERT_EQ("text/html", file2.content_type);
  12401. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12402. file2.content);
  12403. // Test text field
  12404. const auto &text = req.form.get_field("text");
  12405. ASSERT_EQ("text default", text);
  12406. res.set_content("ok", "text/plain");
  12407. handled = true;
  12408. });
  12409. thread t = thread([&] { svr.listen(HOST, PORT); });
  12410. auto se = detail::scope_exit([&] {
  12411. svr.stop();
  12412. t.join();
  12413. ASSERT_FALSE(svr.is_running());
  12414. ASSERT_TRUE(handled);
  12415. });
  12416. svr.wait_until_ready();
  12417. auto req = "POST /test HTTP/1.1\r\n"
  12418. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12419. "Content-Length: 399\r\n"
  12420. "\r\n"
  12421. "----------\r\n"
  12422. "Content-Disposition: form-data; name=\"text\"\r\n"
  12423. "\r\n"
  12424. "text default\r\n"
  12425. "----------\r\n"
  12426. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12427. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12428. "Content-Type: text/plain\r\n"
  12429. "\r\n"
  12430. "Content of a.txt.\r\n"
  12431. "\r\n"
  12432. "----------\r\n"
  12433. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12434. "\"a.html\"\r\n"
  12435. "Content-Type: text/html\r\n"
  12436. "\r\n"
  12437. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12438. "\r\n"
  12439. "------------\r\n";
  12440. ASSERT_TRUE(send_request(1, req));
  12441. }
  12442. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12443. auto handled = false;
  12444. Server svr;
  12445. svr.Post("/test", [&](const Request &req, Response &res) {
  12446. // Case-insensitive "utf-8''" prefix with a long value
  12447. const auto &file = req.form.get_file("file1");
  12448. ASSERT_EQ("file1", file.name);
  12449. // 8000 chars exercises both the Content-Disposition parser and the
  12450. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12451. // Prior to the fix, std::regex_match on this header would cause O(N)
  12452. // stack recursion in libstdc++, leading to SIGSEGV.
  12453. std::string expected_filename(8000, 'A');
  12454. ASSERT_EQ(expected_filename, file.filename);
  12455. res.set_content("ok", "text/plain");
  12456. handled = true;
  12457. });
  12458. thread t = thread([&] { svr.listen(HOST, PORT); });
  12459. auto se = detail::scope_exit([&] {
  12460. svr.stop();
  12461. t.join();
  12462. ASSERT_FALSE(svr.is_running());
  12463. ASSERT_TRUE(handled);
  12464. });
  12465. svr.wait_until_ready();
  12466. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12467. // Regression test for GHSA-qq6v-r583-3h69
  12468. std::string long_filename(8000, 'A');
  12469. std::string body = "----------\r\n"
  12470. "Content-Disposition: form-data; name=\"file1\"; "
  12471. "filename*=\"Utf-8''" +
  12472. long_filename +
  12473. "\"\r\n"
  12474. "\r\n"
  12475. "hello\r\n"
  12476. "------------\r\n";
  12477. auto req = "POST /test HTTP/1.1\r\n"
  12478. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12479. "Content-Length: " +
  12480. std::to_string(body.size()) + "\r\n\r\n" + body;
  12481. ASSERT_TRUE(send_request(1, req));
  12482. }
  12483. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12484. auto handled = false;
  12485. Server svr;
  12486. svr.Post("/test", [&](const Request &req, Response &) {
  12487. ASSERT_EQ(2u, req.form.fields.size());
  12488. const auto &text1 = req.form.get_field("text1");
  12489. ASSERT_EQ("text1", text1);
  12490. const auto &text2 = req.form.get_field("text2");
  12491. ASSERT_EQ("text2", text2);
  12492. handled = true;
  12493. });
  12494. thread t = thread([&] { svr.listen(HOST, PORT); });
  12495. auto se = detail::scope_exit([&] {
  12496. svr.stop();
  12497. t.join();
  12498. ASSERT_FALSE(svr.is_running());
  12499. ASSERT_TRUE(handled);
  12500. });
  12501. svr.wait_until_ready();
  12502. auto req = "POST /test HTTP/1.1\r\n"
  12503. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12504. "Content-Length: 146\r\n"
  12505. "\r\n----------\r\n"
  12506. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12507. "\r\n"
  12508. "text1"
  12509. "\r\n----------\r\n"
  12510. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12511. "\r\n"
  12512. "text2"
  12513. "\r\n------------";
  12514. std::string response;
  12515. ASSERT_TRUE(send_request(1, req, &response));
  12516. ASSERT_EQ("200", response.substr(9, 3));
  12517. }
  12518. TEST(MultipartFormDataTest, ContentLength) {
  12519. auto handled = false;
  12520. Server svr;
  12521. svr.Post("/test", [&](const Request &req, Response &) {
  12522. ASSERT_EQ(2u, req.form.fields.size());
  12523. const auto &text1 = req.form.get_field("text1");
  12524. ASSERT_EQ("text1", text1);
  12525. const auto &text2 = req.form.get_field("text2");
  12526. ASSERT_EQ("text2", text2);
  12527. handled = true;
  12528. });
  12529. thread t = thread([&] { svr.listen(HOST, PORT); });
  12530. auto se = detail::scope_exit([&] {
  12531. svr.stop();
  12532. t.join();
  12533. ASSERT_FALSE(svr.is_running());
  12534. ASSERT_TRUE(handled);
  12535. });
  12536. svr.wait_until_ready();
  12537. auto req = "POST /test HTTP/1.1\r\n"
  12538. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12539. "Content-Length: 167\r\n"
  12540. "\r\n----------\r\n"
  12541. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12542. "Content-Length: 5\r\n"
  12543. "\r\n"
  12544. "text1"
  12545. "\r\n----------\r\n"
  12546. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12547. "\r\n"
  12548. "text2"
  12549. "\r\n------------\r\n";
  12550. std::string response;
  12551. ASSERT_TRUE(send_request(1, req, &response));
  12552. ASSERT_EQ("200", response.substr(9, 3));
  12553. }
  12554. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12555. auto handled = false;
  12556. Server svr;
  12557. svr.Post("/test", [&](const Request &req, Response &) {
  12558. ASSERT_EQ(2u, req.form.fields.size());
  12559. const auto &text1 = req.form.get_field("text1");
  12560. ASSERT_EQ("text1", text1);
  12561. // TODO: Add header access for text fields if needed
  12562. const auto &text2 = req.form.get_field("text2");
  12563. ASSERT_EQ("text2", text2);
  12564. // TODO: Header access for text fields needs to be implemented
  12565. // auto &headers = it->second.headers;
  12566. // ASSERT_EQ(3U, headers.size());
  12567. // auto custom_header = headers.find("x-whatever");
  12568. // ASSERT_TRUE(custom_header != headers.end());
  12569. // ASSERT_NE("customvalue", custom_header->second);
  12570. // ASSERT_EQ("CustomValue", custom_header->second);
  12571. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12572. handled = true;
  12573. });
  12574. thread t = thread([&] { svr.listen(HOST, PORT); });
  12575. auto se = detail::scope_exit([&] {
  12576. svr.stop();
  12577. t.join();
  12578. ASSERT_FALSE(svr.is_running());
  12579. ASSERT_TRUE(handled);
  12580. });
  12581. svr.wait_until_ready();
  12582. auto req = "POST /test HTTP/1.1\r\n"
  12583. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12584. "Content-Length: 232\r\n"
  12585. "\r\n----------\r\n"
  12586. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12587. "Content-Length: 5\r\n"
  12588. "X-Test: 1\r\n"
  12589. "\r\n"
  12590. "text1"
  12591. "\r\n----------\r\n"
  12592. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12593. "Content-Type: text/plain\r\n"
  12594. "X-Whatever: CustomValue\r\n"
  12595. "\r\n"
  12596. "text2"
  12597. "\r\n------------\r\n"
  12598. "That should be disregarded. Not even read";
  12599. std::string response;
  12600. ASSERT_TRUE(send_request(1, req, &response));
  12601. ASSERT_EQ("200", response.substr(9, 3));
  12602. }
  12603. TEST(MultipartFormDataTest, LargeHeader) {
  12604. auto handled = false;
  12605. Server svr;
  12606. svr.Post("/test", [&](const Request &req, Response &) {
  12607. ASSERT_EQ(1u, req.form.fields.size());
  12608. const auto &text = req.form.get_field("name1");
  12609. ASSERT_EQ("text1", text);
  12610. handled = true;
  12611. });
  12612. thread t = thread([&] { svr.listen(HOST, PORT); });
  12613. auto se = detail::scope_exit([&] {
  12614. svr.stop();
  12615. t.join();
  12616. ASSERT_FALSE(svr.is_running());
  12617. ASSERT_TRUE(handled);
  12618. });
  12619. svr.wait_until_ready();
  12620. auto boundary = std::string("cpp-httplib-multipart-data");
  12621. std::string content = "--" + boundary +
  12622. "\r\n"
  12623. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12624. "\r\n"
  12625. "text1\r\n"
  12626. "--" +
  12627. boundary + "--\r\n";
  12628. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12629. "Content-Type: multipart/form-data;boundary=" +
  12630. boundary +
  12631. "\r\n"
  12632. "Content-Length: " +
  12633. std::to_string(content.size()) +
  12634. "\r\n"
  12635. "Dummy-Header: ";
  12636. std::string header_suffix = "\r\n"
  12637. "\r\n";
  12638. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12639. size_t header_dummy_size =
  12640. read_buff_size -
  12641. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12642. auto header_dummy = std::string(header_dummy_size, '@');
  12643. auto req = header_prefix + header_dummy + header_suffix + content;
  12644. std::string response;
  12645. ASSERT_TRUE(send_request(1, req, &response));
  12646. ASSERT_EQ("200", response.substr(9, 3));
  12647. }
  12648. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12649. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12650. // (not chunked Transfer-Encoding) after the streaming refactor.
  12651. auto handled = false;
  12652. Server svr;
  12653. svr.Post("/upload", [&](const Request &req, Response &res) {
  12654. auto cl_it = req.headers.find("Content-Length");
  12655. EXPECT_TRUE(cl_it != req.headers.end());
  12656. auto te_it = req.headers.find("Transfer-Encoding");
  12657. EXPECT_TRUE(te_it == req.headers.end());
  12658. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12659. res.set_content("ok", "text/plain");
  12660. handled = true;
  12661. });
  12662. auto port = svr.bind_to_any_port(HOST);
  12663. auto t = thread([&] { svr.listen_after_bind(); });
  12664. auto se = detail::scope_exit([&] {
  12665. svr.stop();
  12666. t.join();
  12667. ASSERT_FALSE(svr.is_running());
  12668. ASSERT_TRUE(handled);
  12669. });
  12670. svr.wait_until_ready();
  12671. UploadFormDataItems items = {
  12672. {"field1", "hello", "", "text/plain"},
  12673. {"file1", "world", "test.txt", "application/octet-stream"},
  12674. };
  12675. Client cli(HOST, port);
  12676. auto res = cli.Post("/upload", {}, items);
  12677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12678. EXPECT_EQ(StatusCode::OK_200, res->status);
  12679. }
  12680. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12681. // Verify that make_multipart_content_provider coalesces many small segments
  12682. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12683. constexpr size_t kItemCount = 1000;
  12684. UploadFormDataItems items;
  12685. items.reserve(kItemCount);
  12686. for (size_t i = 0; i < kItemCount; i++) {
  12687. items.push_back(
  12688. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12689. }
  12690. const std::string boundary = "----test-boundary";
  12691. auto content_length = detail::get_multipart_content_length(items, boundary);
  12692. auto provider = detail::make_multipart_content_provider(items, boundary);
  12693. // Drive the provider the same way write_content_with_progress does
  12694. size_t write_count = 0;
  12695. size_t total_bytes = 0;
  12696. DataSink sink;
  12697. size_t offset = 0;
  12698. sink.write = [&](const char *d, size_t l) -> bool {
  12699. (void)d;
  12700. write_count++;
  12701. total_bytes += l;
  12702. offset += l;
  12703. return true;
  12704. };
  12705. sink.is_writable = []() -> bool { return true; };
  12706. while (offset < content_length) {
  12707. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12708. }
  12709. EXPECT_EQ(content_length, total_bytes);
  12710. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12711. // With buffering into 64KB blocks, write_count should be much smaller.
  12712. auto segment_count = 3 * kItemCount + 1;
  12713. EXPECT_LT(write_count, segment_count / 10);
  12714. }
  12715. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12716. // Integration test: send many UploadFormDataItems and verify the server
  12717. // receives all of them correctly (#2410).
  12718. constexpr size_t kItemCount = 500;
  12719. auto handled = false;
  12720. Server svr;
  12721. svr.Post("/upload", [&](const Request &req, Response &res) {
  12722. EXPECT_EQ(kItemCount, req.form.fields.size());
  12723. for (size_t i = 0; i < kItemCount; i++) {
  12724. auto key = "field" + std::to_string(i);
  12725. auto val = "value" + std::to_string(i);
  12726. auto it = req.form.fields.find(key);
  12727. if (it != req.form.fields.end()) {
  12728. EXPECT_EQ(val, it->second.content);
  12729. } else {
  12730. ADD_FAILURE() << "Missing field: " << key;
  12731. }
  12732. }
  12733. res.set_content("ok", "text/plain");
  12734. handled = true;
  12735. });
  12736. auto port = svr.bind_to_any_port(HOST);
  12737. auto t = thread([&] { svr.listen_after_bind(); });
  12738. auto se = detail::scope_exit([&] {
  12739. svr.stop();
  12740. t.join();
  12741. ASSERT_FALSE(svr.is_running());
  12742. ASSERT_TRUE(handled);
  12743. });
  12744. svr.wait_until_ready();
  12745. UploadFormDataItems items;
  12746. items.reserve(kItemCount);
  12747. for (size_t i = 0; i < kItemCount; i++) {
  12748. items.push_back(
  12749. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12750. }
  12751. Client cli(HOST, port);
  12752. auto res = cli.Post("/upload", items);
  12753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12754. EXPECT_EQ(StatusCode::OK_200, res->status);
  12755. }
  12756. TEST(MultipartFormDataTest, MakeFileProvider) {
  12757. // Verify make_file_provider sends a file's contents correctly.
  12758. const std::string file_content(4096, 'Z');
  12759. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12760. {
  12761. std::ofstream ofs(tmp_path, std::ios::binary);
  12762. ofs.write(file_content.data(),
  12763. static_cast<std::streamsize>(file_content.size()));
  12764. }
  12765. auto handled = false;
  12766. Server svr;
  12767. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12768. const ContentReader &content_reader) {
  12769. ASSERT_TRUE(req.is_multipart_form_data());
  12770. std::vector<FormData> items;
  12771. content_reader(
  12772. [&](const FormData &file) {
  12773. items.push_back(file);
  12774. return true;
  12775. },
  12776. [&](const char *data, size_t data_length) {
  12777. items.back().content.append(data, data_length);
  12778. return true;
  12779. });
  12780. ASSERT_EQ(1u, items.size());
  12781. EXPECT_EQ("myfile", items[0].name);
  12782. EXPECT_EQ("data.bin", items[0].filename);
  12783. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12784. EXPECT_EQ(file_content, items[0].content);
  12785. handled = true;
  12786. });
  12787. auto port = svr.bind_to_any_port(HOST);
  12788. auto t = thread([&] { svr.listen_after_bind(); });
  12789. auto se = detail::scope_exit([&] {
  12790. svr.stop();
  12791. t.join();
  12792. ASSERT_FALSE(svr.is_running());
  12793. ASSERT_TRUE(handled);
  12794. std::remove(tmp_path.c_str());
  12795. });
  12796. svr.wait_until_ready();
  12797. FormDataProviderItems providers;
  12798. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12799. "application/octet-stream"));
  12800. Client cli(HOST, port);
  12801. auto res = cli.Post("/upload", {}, {}, providers);
  12802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12803. EXPECT_EQ(StatusCode::OK_200, res->status);
  12804. }
  12805. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12806. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12807. // (100) headers is rejected with a 400 Bad Request response.
  12808. Server svr;
  12809. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12810. res.set_content("ok", "text/plain");
  12811. });
  12812. thread t = thread([&] { svr.listen(HOST, PORT); });
  12813. auto se = detail::scope_exit([&] {
  12814. svr.stop();
  12815. t.join();
  12816. ASSERT_FALSE(svr.is_running());
  12817. });
  12818. svr.wait_until_ready();
  12819. // Build a multipart part with 101 custom headers (exceeding
  12820. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12821. std::stringstream body;
  12822. body << "--simpleboundary\r\n"
  12823. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12824. for (int i = 0; i < 101; i++) {
  12825. body << "X-Custom-Header-" << i << ": value\r\n";
  12826. }
  12827. body << "\r\n"
  12828. << "value1\r\n"
  12829. << "--simpleboundary--\r\n";
  12830. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12831. Client cli(HOST, PORT);
  12832. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12834. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12835. }
  12836. TEST(MakeFileBodyTest, Basic) {
  12837. const std::string file_content(4096, 'Z');
  12838. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12839. {
  12840. std::ofstream ofs(tmp_path, std::ios::binary);
  12841. ofs.write(file_content.data(),
  12842. static_cast<std::streamsize>(file_content.size()));
  12843. }
  12844. auto handled = false;
  12845. Server svr;
  12846. svr.Post("/upload", [&](const Request &req, Response &res) {
  12847. EXPECT_EQ(file_content, req.body);
  12848. handled = true;
  12849. res.status = StatusCode::OK_200;
  12850. });
  12851. auto port = svr.bind_to_any_port(HOST);
  12852. auto t = thread([&] { svr.listen_after_bind(); });
  12853. auto se = detail::scope_exit([&] {
  12854. svr.stop();
  12855. t.join();
  12856. ASSERT_FALSE(svr.is_running());
  12857. ASSERT_TRUE(handled);
  12858. std::remove(tmp_path.c_str());
  12859. });
  12860. svr.wait_until_ready();
  12861. auto fb = make_file_body(tmp_path);
  12862. ASSERT_GT(fb.first, 0u);
  12863. Client cli(HOST, port);
  12864. auto res =
  12865. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12867. EXPECT_EQ(StatusCode::OK_200, res->status);
  12868. }
  12869. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12870. static constexpr unsigned int number_of_tasks{1000000};
  12871. std::atomic_uint count{0};
  12872. std::unique_ptr<TaskQueue> task_queue{
  12873. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12874. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12875. auto queued = task_queue->enqueue(
  12876. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12877. EXPECT_TRUE(queued);
  12878. }
  12879. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12880. task_queue->shutdown();
  12881. #else
  12882. EXPECT_NO_THROW(task_queue->shutdown());
  12883. #endif
  12884. EXPECT_EQ(number_of_tasks, count.load());
  12885. }
  12886. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12887. static constexpr unsigned int number_of_tasks{1000000};
  12888. static constexpr unsigned int qlimit{2};
  12889. unsigned int queued_count{0};
  12890. std::atomic_uint count{0};
  12891. std::unique_ptr<TaskQueue> task_queue{
  12892. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12893. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12894. if (task_queue->enqueue(
  12895. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12896. queued_count++;
  12897. }
  12898. }
  12899. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12900. task_queue->shutdown();
  12901. #else
  12902. EXPECT_NO_THROW(task_queue->shutdown());
  12903. #endif
  12904. EXPECT_EQ(queued_count, count.load());
  12905. EXPECT_TRUE(queued_count <= number_of_tasks);
  12906. EXPECT_TRUE(queued_count >= qlimit);
  12907. }
  12908. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12909. // Use a short idle timeout so a dynamic thread spawns, times out and
  12910. // exits during the test, and the pool keeps working afterwards.
  12911. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12912. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12913. /*idle_timeout_sec=*/1}};
  12914. std::atomic_uint count{0};
  12915. std::condition_variable cv;
  12916. std::mutex mtx;
  12917. bool release = false;
  12918. // Block the base thread so the second task spawns a dynamic thread.
  12919. EXPECT_TRUE(task_queue->enqueue([&] {
  12920. std::unique_lock<std::mutex> lock(mtx);
  12921. while (!release) {
  12922. cv.wait(lock);
  12923. }
  12924. count++;
  12925. }));
  12926. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12927. // Let the dynamic thread finish its task and exceed the idle timeout.
  12928. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12929. {
  12930. std::unique_lock<std::mutex> lock(mtx);
  12931. release = true;
  12932. }
  12933. cv.notify_all();
  12934. // The pool must still accept and run tasks after the dynamic thread exited.
  12935. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12936. task_queue->shutdown();
  12937. EXPECT_EQ(3u, count.load());
  12938. }
  12939. TEST(TaskQueueTest, MaxQueuedRequests) {
  12940. static constexpr unsigned int qlimit{3};
  12941. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12942. std::condition_variable sem_cv;
  12943. std::mutex sem_mtx;
  12944. int credits = 0;
  12945. bool queued;
  12946. /* Fill up the queue with tasks that will block until we give them credits to
  12947. * complete. */
  12948. for (unsigned int n = 0; n <= qlimit;) {
  12949. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12950. std::unique_lock<std::mutex> lock(sem_mtx);
  12951. while (credits <= 0) {
  12952. sem_cv.wait(lock);
  12953. }
  12954. /* Consume the credit and signal the test code if they are all gone. */
  12955. if (--credits == 0) { sem_cv.notify_one(); }
  12956. });
  12957. if (n < qlimit) {
  12958. /* The first qlimit enqueues must succeed. */
  12959. EXPECT_TRUE(queued);
  12960. } else {
  12961. /* The last one will succeed only when the worker thread
  12962. * starts and dequeues the first blocking task. Although
  12963. * not necessary for the correctness of this test, we sleep for
  12964. * a short while to avoid busy waiting. */
  12965. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12966. }
  12967. if (queued) { n++; }
  12968. }
  12969. /* Further enqueues must fail since the queue is full. */
  12970. for (auto i = 0; i < 4; i++) {
  12971. queued = task_queue->enqueue([] {});
  12972. EXPECT_FALSE(queued);
  12973. }
  12974. /* Give the credits to allow the previous tasks to complete. */
  12975. {
  12976. std::unique_lock<std::mutex> lock(sem_mtx);
  12977. credits += qlimit + 1;
  12978. }
  12979. sem_cv.notify_all();
  12980. /* Wait for all the credits to be consumed. */
  12981. {
  12982. std::unique_lock<std::mutex> lock(sem_mtx);
  12983. while (credits > 0) {
  12984. sem_cv.wait(lock);
  12985. }
  12986. }
  12987. /* Check that we are able again to enqueue at least qlimit tasks. */
  12988. for (unsigned int i = 0; i < qlimit; i++) {
  12989. queued = task_queue->enqueue([] {});
  12990. EXPECT_TRUE(queued);
  12991. }
  12992. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12993. task_queue->shutdown();
  12994. #else
  12995. EXPECT_NO_THROW(task_queue->shutdown());
  12996. #endif
  12997. }
  12998. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12999. Server svr;
  13000. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13001. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  13002. });
  13003. svr.Get("/hello", [](const Request &req, Response &res) {
  13004. res.set_content(req.get_param_value("key"), "text/plain");
  13005. });
  13006. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13007. auto se = detail::scope_exit([&] {
  13008. svr.stop();
  13009. thread.join();
  13010. ASSERT_FALSE(svr.is_running());
  13011. });
  13012. svr.wait_until_ready();
  13013. {
  13014. Client cli(HOST, PORT);
  13015. cli.set_follow_location(true);
  13016. auto res = cli.Get("/");
  13017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13018. EXPECT_EQ(StatusCode::OK_200, res->status);
  13019. EXPECT_EQ("val&key2=val2", res->body);
  13020. }
  13021. }
  13022. #endif
  13023. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  13024. Server svr;
  13025. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13026. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  13027. });
  13028. svr.Get("/hello", [](const Request &req, Response &res) {
  13029. res.set_content(req.get_param_value("key"), "text/plain");
  13030. });
  13031. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13032. auto se = detail::scope_exit([&] {
  13033. svr.stop();
  13034. thread.join();
  13035. ASSERT_FALSE(svr.is_running());
  13036. });
  13037. svr.wait_until_ready();
  13038. {
  13039. Client cli(HOST, PORT);
  13040. cli.set_follow_location(true);
  13041. auto res = cli.Get("/");
  13042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13043. EXPECT_EQ(StatusCode::OK_200, res->status);
  13044. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  13045. }
  13046. }
  13047. TEST(RedirectTest, RedirectWithPlusInPath) {
  13048. Server svr;
  13049. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13050. res.set_redirect("/a+b");
  13051. });
  13052. // Route pattern uses regex; escape + as \\+
  13053. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  13054. res.set_content(req.path, "text/plain");
  13055. });
  13056. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13057. auto se = detail::scope_exit([&] {
  13058. svr.stop();
  13059. thread.join();
  13060. ASSERT_FALSE(svr.is_running());
  13061. });
  13062. svr.wait_until_ready();
  13063. {
  13064. Client cli(HOST, PORT);
  13065. cli.set_follow_location(true);
  13066. auto res = cli.Get("/");
  13067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13068. EXPECT_EQ(StatusCode::OK_200, res->status);
  13069. EXPECT_EQ("/a+b", res->body);
  13070. }
  13071. }
  13072. #ifdef CPPHTTPLIB_SSL_ENABLED
  13073. TEST(RedirectTest, Issue2185_Online) {
  13074. SSLClient client("github.com");
  13075. client.set_follow_location(true);
  13076. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  13077. "Coollab-Windows.zip");
  13078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13079. EXPECT_EQ(StatusCode::OK_200, res->status);
  13080. EXPECT_EQ(9920427U, res->body.size());
  13081. }
  13082. #endif
  13083. TEST(VulnerabilityTest, CRLFInjection) {
  13084. Server svr;
  13085. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  13086. res.set_content("Hello 1", "text/plain");
  13087. });
  13088. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  13089. res.set_content("Hello 2", "text/plain");
  13090. });
  13091. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  13092. res.set_content("Hello 3", "text/plain");
  13093. });
  13094. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  13095. res.set_content("Hello 4", "text/plain");
  13096. });
  13097. svr.set_logger([](const Request &req, const Response & /*res*/) {
  13098. for (const auto &x : req.headers) {
  13099. auto key = x.first;
  13100. EXPECT_STRNE("evil", key.c_str());
  13101. }
  13102. });
  13103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13104. auto se = detail::scope_exit([&] {
  13105. svr.stop();
  13106. thread.join();
  13107. ASSERT_FALSE(svr.is_running());
  13108. });
  13109. svr.wait_until_ready();
  13110. {
  13111. Client cli(HOST, PORT);
  13112. cli.Post("/test1", "A=B",
  13113. "application/x-www-form-urlencoded\r\nevil: hello1");
  13114. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  13115. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  13116. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  13117. }
  13118. }
  13119. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  13120. auto server_thread = std::thread([] {
  13121. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13122. default_socket_options(srv);
  13123. sockaddr_in addr{};
  13124. addr.sin_family = AF_INET;
  13125. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  13126. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13127. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13128. ::listen(srv, 1);
  13129. sockaddr_in cli_addr{};
  13130. socklen_t cli_len = sizeof(cli_addr);
  13131. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13132. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  13133. std::string buf_all;
  13134. char buf[2048];
  13135. ssize_t n;
  13136. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  13137. buf_all.append(buf, static_cast<size_t>(n));
  13138. size_t pos;
  13139. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  13140. auto request_block = buf_all.substr(0, pos + 4); // include separator
  13141. auto e = request_block.find("\r\n");
  13142. if (e != std::string::npos) {
  13143. auto request_line = request_block.substr(0, e);
  13144. std::string msg =
  13145. "CRLF injection detected in request line: '" + request_line + "'";
  13146. EXPECT_FALSE(true) << msg;
  13147. }
  13148. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  13149. ::send(cli,
  13150. #ifdef _WIN32
  13151. static_cast<const char *>(resp.c_str()),
  13152. static_cast<int>(resp.size()),
  13153. #else
  13154. resp.c_str(), resp.size(),
  13155. #endif
  13156. 0);
  13157. buf_all.erase(0, pos + 4);
  13158. }
  13159. }
  13160. detail::close_socket(cli);
  13161. detail::close_socket(srv);
  13162. });
  13163. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13164. auto cli = Client("127.0.0.1", PORT + 1);
  13165. auto headers = Headers{
  13166. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  13167. {"Connection", "keep-alive"}};
  13168. auto res = cli.Get("/hi", headers);
  13169. EXPECT_FALSE(res);
  13170. EXPECT_EQ(Error::InvalidHeaders, res.error());
  13171. server_thread.join();
  13172. }
  13173. TEST(PathParamsTest, StaticMatch) {
  13174. const auto pattern = "/users/all";
  13175. detail::PathParamsMatcher matcher(pattern);
  13176. Request request;
  13177. request.path = "/users/all";
  13178. ASSERT_TRUE(matcher.match(request));
  13179. std::unordered_map<std::string, std::string> expected_params = {};
  13180. EXPECT_EQ(request.path_params, expected_params);
  13181. }
  13182. TEST(PathParamsTest, StaticMismatch) {
  13183. const auto pattern = "/users/all";
  13184. detail::PathParamsMatcher matcher(pattern);
  13185. Request request;
  13186. request.path = "/users/1";
  13187. ASSERT_FALSE(matcher.match(request));
  13188. }
  13189. TEST(PathParamsTest, SingleParamInTheMiddle) {
  13190. const auto pattern = "/users/:id/subscriptions";
  13191. detail::PathParamsMatcher matcher(pattern);
  13192. Request request;
  13193. request.path = "/users/42/subscriptions";
  13194. ASSERT_TRUE(matcher.match(request));
  13195. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13196. EXPECT_EQ(request.path_params, expected_params);
  13197. }
  13198. TEST(PathParamsTest, SingleParamInTheEnd) {
  13199. const auto pattern = "/users/:id";
  13200. detail::PathParamsMatcher matcher(pattern);
  13201. Request request;
  13202. request.path = "/users/24";
  13203. ASSERT_TRUE(matcher.match(request));
  13204. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  13205. EXPECT_EQ(request.path_params, expected_params);
  13206. }
  13207. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  13208. const auto pattern = "/users/:id/";
  13209. detail::PathParamsMatcher matcher(pattern);
  13210. Request request;
  13211. request.path = "/users/42/";
  13212. ASSERT_TRUE(matcher.match(request));
  13213. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13214. EXPECT_EQ(request.path_params, expected_params);
  13215. }
  13216. TEST(PathParamsTest, EmptyParam) {
  13217. const auto pattern = "/users/:id/";
  13218. detail::PathParamsMatcher matcher(pattern);
  13219. Request request;
  13220. request.path = "/users//";
  13221. ASSERT_TRUE(matcher.match(request));
  13222. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  13223. EXPECT_EQ(request.path_params, expected_params);
  13224. }
  13225. TEST(PathParamsTest, FragmentMismatch) {
  13226. const auto pattern = "/users/:id/";
  13227. detail::PathParamsMatcher matcher(pattern);
  13228. Request request;
  13229. request.path = "/admins/24/";
  13230. ASSERT_FALSE(matcher.match(request));
  13231. }
  13232. TEST(PathParamsTest, ExtraFragments) {
  13233. const auto pattern = "/users/:id";
  13234. detail::PathParamsMatcher matcher(pattern);
  13235. Request request;
  13236. request.path = "/users/42/subscriptions";
  13237. ASSERT_FALSE(matcher.match(request));
  13238. }
  13239. TEST(PathParamsTest, MissingTrailingParam) {
  13240. const auto pattern = "/users/:id";
  13241. detail::PathParamsMatcher matcher(pattern);
  13242. Request request;
  13243. request.path = "/users";
  13244. ASSERT_FALSE(matcher.match(request));
  13245. }
  13246. TEST(PathParamsTest, MissingParamInTheMiddle) {
  13247. const auto pattern = "/users/:id/subscriptions";
  13248. detail::PathParamsMatcher matcher(pattern);
  13249. Request request;
  13250. request.path = "/users/subscriptions";
  13251. ASSERT_FALSE(matcher.match(request));
  13252. }
  13253. TEST(PathParamsTest, MultipleParams) {
  13254. const auto pattern = "/users/:userid/subscriptions/:subid";
  13255. detail::PathParamsMatcher matcher(pattern);
  13256. Request request;
  13257. request.path = "/users/42/subscriptions/2";
  13258. ASSERT_TRUE(matcher.match(request));
  13259. std::unordered_map<std::string, std::string> expected_params = {
  13260. {"userid", "42"}, {"subid", "2"}};
  13261. EXPECT_EQ(request.path_params, expected_params);
  13262. }
  13263. TEST(PathParamsTest, SequenceOfParams) {
  13264. const auto pattern = "/values/:x/:y/:z";
  13265. detail::PathParamsMatcher matcher(pattern);
  13266. Request request;
  13267. request.path = "/values/1/2/3";
  13268. ASSERT_TRUE(matcher.match(request));
  13269. std::unordered_map<std::string, std::string> expected_params = {
  13270. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  13271. EXPECT_EQ(request.path_params, expected_params);
  13272. }
  13273. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  13274. const auto pattern = "/prefix:suffix";
  13275. detail::PathParamsMatcher matcher(pattern);
  13276. Request request;
  13277. request.path = "/prefix:suffix";
  13278. ASSERT_TRUE(matcher.match(request));
  13279. const std::unordered_map<std::string, std::string> expected_params = {};
  13280. EXPECT_EQ(request.path_params, expected_params);
  13281. }
  13282. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  13283. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  13284. // calling thread's stack on a long enough path for a quantified pattern;
  13285. // RegexMatcher must refuse to run regex matching on paths beyond
  13286. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  13287. detail::RegexMatcher matcher("/files/(.*)");
  13288. Request within_limit;
  13289. within_limit.path = "/files/" + std::string(10, 'A');
  13290. EXPECT_TRUE(matcher.match(within_limit));
  13291. Request over_limit;
  13292. over_limit.path =
  13293. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  13294. EXPECT_FALSE(matcher.match(over_limit));
  13295. }
  13296. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  13297. Server svr;
  13298. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  13299. res.set_content("ok", "text/plain");
  13300. });
  13301. auto port = svr.bind_to_any_port(HOST);
  13302. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  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. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  13310. // request URI limit; this used to be able to crash the process.
  13311. std::string path =
  13312. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  13313. std::string req = "GET " + path +
  13314. " HTTP/1.1\r\n"
  13315. "Host: " +
  13316. std::string(HOST) + ":" + std::to_string(port) +
  13317. "\r\n"
  13318. "Connection: close\r\n"
  13319. "\r\n";
  13320. std::string response;
  13321. ASSERT_TRUE(send_request(5, req, &response, port));
  13322. EXPECT_NE(std::string::npos, response.find("404"));
  13323. }
  13324. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  13325. Server svr;
  13326. auto handler = [](const Request & /*req*/, Response &res) {
  13327. res.set_content("hit", "text/plain");
  13328. };
  13329. // No regex metacharacter, so this one is compared literally
  13330. svr.Get("/literal/route", handler);
  13331. // '.' is a regex metacharacter, so this one must keep regex semantics
  13332. svr.Get("/a.c", handler);
  13333. auto port = svr.bind_to_any_port(HOST);
  13334. std::thread t([&]() { svr.listen_after_bind(); });
  13335. auto se = detail::scope_exit([&] {
  13336. svr.stop();
  13337. t.join();
  13338. ASSERT_FALSE(svr.is_running());
  13339. });
  13340. svr.wait_until_ready();
  13341. Client cli(HOST, port);
  13342. struct {
  13343. const char *path;
  13344. int status;
  13345. } cases[] = {
  13346. {"/literal/route", StatusCode::OK_200},
  13347. {"/literal/routes", StatusCode::NotFound_404},
  13348. {"/literal/rout", StatusCode::NotFound_404},
  13349. {"/abc", StatusCode::OK_200},
  13350. {"/a.c", StatusCode::OK_200},
  13351. };
  13352. for (const auto &x : cases) {
  13353. auto res = cli.Get(x.path);
  13354. ASSERT_TRUE(res) << x.path;
  13355. EXPECT_EQ(x.status, res->status) << x.path;
  13356. }
  13357. }
  13358. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  13359. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  13360. // from exhausting the stack, so it must only constrain routes that actually
  13361. // run a regular expression. A literal route is matched by comparison and
  13362. // stays usable at any length.
  13363. Server svr;
  13364. const std::string pattern =
  13365. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  13366. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  13367. res.set_content("hit", "text/plain");
  13368. });
  13369. auto port = svr.bind_to_any_port(HOST);
  13370. std::thread t([&]() { svr.listen_after_bind(); });
  13371. auto se = detail::scope_exit([&] {
  13372. svr.stop();
  13373. t.join();
  13374. ASSERT_FALSE(svr.is_running());
  13375. });
  13376. svr.wait_until_ready();
  13377. Client cli(HOST, port);
  13378. auto res = cli.Get(pattern);
  13379. ASSERT_TRUE(res);
  13380. EXPECT_EQ(StatusCode::OK_200, res->status);
  13381. }
  13382. TEST(ParseUrlTest, VariousPatterns) {
  13383. {
  13384. detail::UrlComponents uc;
  13385. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  13386. EXPECT_EQ("http", uc.scheme);
  13387. EXPECT_EQ("example.com", uc.host);
  13388. EXPECT_EQ("8080", uc.port);
  13389. EXPECT_EQ("/path", uc.path);
  13390. EXPECT_EQ("?q=1", uc.query);
  13391. }
  13392. {
  13393. detail::UrlComponents uc;
  13394. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  13395. EXPECT_EQ("https", uc.scheme);
  13396. EXPECT_EQ("example.com", uc.host);
  13397. EXPECT_TRUE(uc.port.empty());
  13398. EXPECT_EQ("/path", uc.path);
  13399. }
  13400. {
  13401. detail::UrlComponents uc;
  13402. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13403. EXPECT_EQ("::1", uc.host);
  13404. EXPECT_EQ("8080", uc.port);
  13405. EXPECT_EQ("/path", uc.path);
  13406. }
  13407. {
  13408. detail::UrlComponents uc;
  13409. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13410. }
  13411. {
  13412. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13413. // the path while the connection still targets the bracketed host.
  13414. detail::UrlComponents uc;
  13415. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13416. }
  13417. {
  13418. detail::UrlComponents uc;
  13419. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13420. }
  13421. {
  13422. detail::UrlComponents uc;
  13423. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13424. EXPECT_EQ("::1", uc.host);
  13425. EXPECT_TRUE(uc.port.empty());
  13426. EXPECT_EQ("/path", uc.path);
  13427. }
  13428. {
  13429. detail::UrlComponents uc;
  13430. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13431. EXPECT_TRUE(uc.scheme.empty());
  13432. EXPECT_EQ("example.com", uc.host);
  13433. EXPECT_EQ("/path", uc.path);
  13434. EXPECT_EQ("?q=1", uc.query);
  13435. }
  13436. {
  13437. detail::UrlComponents uc;
  13438. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13439. EXPECT_TRUE(uc.host.empty());
  13440. EXPECT_EQ("/path", uc.path);
  13441. EXPECT_EQ("?q=1", uc.query);
  13442. }
  13443. {
  13444. detail::UrlComponents uc;
  13445. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13446. EXPECT_EQ("example.com", uc.host);
  13447. EXPECT_EQ("8080", uc.port);
  13448. }
  13449. {
  13450. // Unix socket path — must not be parsed as host
  13451. detail::UrlComponents uc;
  13452. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13453. EXPECT_TRUE(uc.host.empty());
  13454. }
  13455. {
  13456. detail::UrlComponents uc;
  13457. ASSERT_TRUE(detail::parse_url("", uc));
  13458. EXPECT_TRUE(uc.host.empty());
  13459. EXPECT_TRUE(uc.path.empty());
  13460. }
  13461. {
  13462. detail::UrlComponents uc;
  13463. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13464. }
  13465. {
  13466. detail::UrlComponents uc;
  13467. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13468. }
  13469. {
  13470. // Accepted by parse_url; callers restrict to http/https
  13471. detail::UrlComponents uc;
  13472. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13473. EXPECT_EQ("ftp", uc.scheme);
  13474. }
  13475. {
  13476. detail::UrlComponents uc;
  13477. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13478. }
  13479. {
  13480. detail::UrlComponents uc;
  13481. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13482. }
  13483. }
  13484. TEST(ParseUrlTest, FragmentHandling) {
  13485. {
  13486. detail::UrlComponents uc;
  13487. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13488. EXPECT_EQ("/path", uc.path);
  13489. EXPECT_TRUE(uc.query.empty());
  13490. }
  13491. {
  13492. detail::UrlComponents uc;
  13493. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13494. EXPECT_TRUE(uc.path.empty());
  13495. EXPECT_TRUE(uc.query.empty());
  13496. }
  13497. }
  13498. TEST(ParseUrlTest, UserinfoHandling) {
  13499. // Userinfo with @ but no colon — host includes @
  13500. detail::UrlComponents uc;
  13501. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13502. EXPECT_EQ("user@host.com", uc.host);
  13503. EXPECT_EQ("/path", uc.path);
  13504. }
  13505. TEST(ParseUrlTest, IPv6EdgeCases) {
  13506. {
  13507. detail::UrlComponents uc;
  13508. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13509. EXPECT_TRUE(uc.scheme.empty());
  13510. EXPECT_EQ("::1", uc.host);
  13511. EXPECT_EQ("8080", uc.port);
  13512. }
  13513. {
  13514. // Zone ID '%25' is not in [a-fA-F0-9:]
  13515. detail::UrlComponents uc;
  13516. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13517. }
  13518. }
  13519. TEST(ParseUrlTest, SchemeEdgeCases) {
  13520. {
  13521. detail::UrlComponents uc;
  13522. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13523. }
  13524. {
  13525. detail::UrlComponents uc;
  13526. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13527. }
  13528. {
  13529. detail::UrlComponents uc;
  13530. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13531. }
  13532. }
  13533. TEST(ParseUrlTest, PortEdgeCases) {
  13534. {
  13535. detail::UrlComponents uc;
  13536. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13537. EXPECT_TRUE(uc.port.empty());
  13538. EXPECT_EQ("/path", uc.path);
  13539. }
  13540. {
  13541. // parse_url accepts any port string; validation is done by parse_port
  13542. detail::UrlComponents uc;
  13543. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13544. EXPECT_EQ("abc", uc.port);
  13545. }
  13546. }
  13547. TEST(ParseUrlTest, WebSocketPatterns) {
  13548. {
  13549. detail::UrlComponents uc;
  13550. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13551. EXPECT_EQ("ws", uc.scheme);
  13552. EXPECT_EQ("echo.example.com", uc.host);
  13553. EXPECT_EQ("8080", uc.port);
  13554. EXPECT_EQ("/ws", uc.path);
  13555. }
  13556. {
  13557. detail::UrlComponents uc;
  13558. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13559. EXPECT_EQ("wss", uc.scheme);
  13560. EXPECT_EQ("echo.example.com", uc.host);
  13561. EXPECT_TRUE(uc.port.empty());
  13562. EXPECT_EQ("/ws", uc.path);
  13563. }
  13564. }
  13565. TEST(ParseUrlTest, QueryOnly) {
  13566. detail::UrlComponents uc;
  13567. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13568. EXPECT_TRUE(uc.host.empty());
  13569. EXPECT_TRUE(uc.path.empty());
  13570. EXPECT_EQ("?q=1&r=2", uc.query);
  13571. }
  13572. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13573. detail::UrlComponents uc;
  13574. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13575. EXPECT_TRUE(uc.scheme.empty());
  13576. EXPECT_EQ("example.com", uc.host);
  13577. EXPECT_EQ("443", uc.port);
  13578. EXPECT_EQ("/path", uc.path);
  13579. }
  13580. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13581. // If ipv6 regex working, regex match codepath is taken.
  13582. // else port will default to 80 in Client impl
  13583. int clientImplMagicPort = 80;
  13584. int port = 4321;
  13585. // above ports must be different to avoid false negative
  13586. EXPECT_NE(clientImplMagicPort, port);
  13587. std::string ipV6TestURL = "http://[ff06::c3]";
  13588. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13589. CLIENT_PRIVATE_KEY_FILE);
  13590. EXPECT_EQ(cli.port(), port);
  13591. }
  13592. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13593. auto file_path = "./www/dir/index.html";
  13594. auto dir_path = "./www/dir";
  13595. detail::FileStat stat_file(file_path);
  13596. EXPECT_TRUE(stat_file.is_file());
  13597. EXPECT_FALSE(stat_file.is_dir());
  13598. detail::FileStat stat_dir(dir_path);
  13599. EXPECT_FALSE(stat_dir.is_file());
  13600. EXPECT_TRUE(stat_dir.is_dir());
  13601. }
  13602. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13603. // IPv4 with default HTTP port (80)
  13604. EXPECT_EQ("example.com",
  13605. detail::make_host_and_port_string("example.com", 80, false));
  13606. // IPv4 with default HTTPS port (443)
  13607. EXPECT_EQ("example.com",
  13608. detail::make_host_and_port_string("example.com", 443, true));
  13609. // IPv4 with non-default HTTP port
  13610. EXPECT_EQ("example.com:8080",
  13611. detail::make_host_and_port_string("example.com", 8080, false));
  13612. // IPv4 with non-default HTTPS port
  13613. EXPECT_EQ("example.com:8443",
  13614. detail::make_host_and_port_string("example.com", 8443, true));
  13615. // IPv6 with default HTTP port (80)
  13616. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13617. // IPv6 with default HTTPS port (443)
  13618. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13619. // IPv6 with non-default HTTP port
  13620. EXPECT_EQ("[::1]:8080",
  13621. detail::make_host_and_port_string("::1", 8080, false));
  13622. // IPv6 with non-default HTTPS port
  13623. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13624. // IPv6 full address with default port
  13625. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13626. detail::make_host_and_port_string(
  13627. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13628. // IPv6 full address with non-default port
  13629. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13630. detail::make_host_and_port_string(
  13631. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13632. // IPv6 localhost with non-default port
  13633. EXPECT_EQ("[::1]:3000",
  13634. detail::make_host_and_port_string("::1", 3000, false));
  13635. // IPv6 with zone ID (link-local address) with default port
  13636. EXPECT_EQ("[fe80::1%eth0]",
  13637. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13638. // IPv6 with zone ID (link-local address) with non-default port
  13639. EXPECT_EQ("[fe80::1%eth0]:8080",
  13640. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13641. // Edge case: Port 443 with is_ssl=false (should add port)
  13642. EXPECT_EQ("example.com:443",
  13643. detail::make_host_and_port_string("example.com", 443, false));
  13644. // Edge case: Port 80 with is_ssl=true (should add port)
  13645. EXPECT_EQ("example.com:80",
  13646. detail::make_host_and_port_string("example.com", 80, true));
  13647. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13648. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13649. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13650. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13651. // Security fix: Already bracketed IPv6 should not get double brackets
  13652. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13653. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13654. EXPECT_EQ("[::1]:8080",
  13655. detail::make_host_and_port_string("[::1]", 8080, false));
  13656. EXPECT_EQ("[2001:db8::1]:8080",
  13657. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13658. EXPECT_EQ("[fe80::1%eth0]",
  13659. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13660. EXPECT_EQ("[fe80::1%eth0]:8080",
  13661. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13662. // Edge case: Empty host (should return as-is)
  13663. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13664. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13665. // This is a known limitation but shouldn't crash
  13666. EXPECT_EQ("[host:name]",
  13667. detail::make_host_and_port_string("host:name", 80, false));
  13668. // Port number edge cases (no validation, but should not crash)
  13669. EXPECT_EQ("example.com:0",
  13670. detail::make_host_and_port_string("example.com", 0, false));
  13671. EXPECT_EQ("example.com:-1",
  13672. detail::make_host_and_port_string("example.com", -1, false));
  13673. EXPECT_EQ("example.com:65535",
  13674. detail::make_host_and_port_string("example.com", 65535, false));
  13675. EXPECT_EQ("example.com:65536",
  13676. detail::make_host_and_port_string("example.com", 65536, false));
  13677. }
  13678. #ifdef CPPHTTPLIB_SSL_ENABLED
  13679. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13680. httplib::SSLClient cli("roblox.com", 443);
  13681. cli.set_follow_location(true);
  13682. auto res = cli.Get("/");
  13683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13684. EXPECT_EQ(StatusCode::OK_200, res->status);
  13685. }
  13686. #endif
  13687. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13688. Server svr;
  13689. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13690. EXPECT_EQ(res.status, 400);
  13691. });
  13692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13693. auto se = detail::scope_exit([&] {
  13694. svr.stop();
  13695. thread.join();
  13696. ASSERT_FALSE(svr.is_running());
  13697. });
  13698. svr.wait_until_ready();
  13699. Client cli(HOST, PORT);
  13700. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13701. }
  13702. TEST(InvalidHeaderCharsTest, is_field_name) {
  13703. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13704. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13705. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13706. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13707. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13708. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13709. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13710. EXPECT_FALSE(detail::fields::is_field_name(""));
  13711. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13712. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13713. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13714. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13715. }
  13716. TEST(InvalidHeaderCharsTest, is_field_value) {
  13717. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13718. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13719. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13720. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13721. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13722. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13723. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13724. EXPECT_TRUE(detail::fields::is_field_value(""));
  13725. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13726. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13727. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13728. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13729. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13730. }
  13731. TEST(InvalidHeaderCharsTest, OnServer) {
  13732. Server svr;
  13733. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13734. std::string header = "Not Set";
  13735. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13736. res.set_header(header, "value");
  13737. res.set_content("Page Content Page Content", "text/plain");
  13738. });
  13739. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13740. std::string header = "Not Set";
  13741. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13742. res.set_header("X-Test", header);
  13743. res.set_content("Page Content Page Content", "text/plain");
  13744. });
  13745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13746. auto se = detail::scope_exit([&] {
  13747. svr.stop();
  13748. thread.join();
  13749. ASSERT_FALSE(svr.is_running());
  13750. });
  13751. svr.wait_until_ready();
  13752. Client cli(HOST, PORT);
  13753. {
  13754. auto res = cli.Get(
  13755. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13757. EXPECT_EQ("Page Content Page Content", res->body);
  13758. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13759. }
  13760. {
  13761. auto res = cli.Get(
  13762. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13764. EXPECT_EQ("Page Content Page Content", res->body);
  13765. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13766. }
  13767. }
  13768. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13769. auto handled = false;
  13770. Server svr;
  13771. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13772. thread t = thread([&] { svr.listen(HOST, PORT); });
  13773. auto se = detail::scope_exit([&] {
  13774. svr.stop();
  13775. t.join();
  13776. ASSERT_FALSE(svr.is_running());
  13777. ASSERT_FALSE(handled);
  13778. });
  13779. svr.wait_until_ready();
  13780. auto req = "POST /test HTTP/1.1\r\n"
  13781. "Content-Length: x\r\n"
  13782. "\r\n";
  13783. std::string response;
  13784. ASSERT_TRUE(send_request(1, req, &response));
  13785. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13786. response.substr(0, response.find("\r\n")));
  13787. }
  13788. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  13789. // case-insensitive, and a server that receives a 100-continue expectation in
  13790. // an HTTP/1.0 request MUST ignore it.
  13791. static void probe_expect(int port, const std::string &req, bool *got_100) {
  13792. std::string response;
  13793. ASSERT_TRUE(send_request(1, req, &response, port));
  13794. *got_100 = response.find("100 Continue") != std::string::npos;
  13795. }
  13796. class ExpectTokenTest : public ::testing::Test {
  13797. protected:
  13798. void SetUp() override {
  13799. svr_.Post("/p", [](const Request &, Response &res) {
  13800. res.set_content("ok", "text/plain");
  13801. });
  13802. port_ = svr_.bind_to_any_port(HOST);
  13803. thread_ = thread([&]() { svr_.listen_after_bind(); });
  13804. svr_.wait_until_ready();
  13805. }
  13806. void TearDown() override {
  13807. svr_.stop();
  13808. if (thread_.joinable()) { thread_.join(); }
  13809. }
  13810. std::string request(const char *version, const char *expect_value) const {
  13811. return std::string("POST /p ") + version +
  13812. "\r\n"
  13813. "Host: localhost\r\n"
  13814. "Content-Length: 2\r\n"
  13815. "Connection: close\r\n"
  13816. "Expect: " +
  13817. expect_value +
  13818. "\r\n"
  13819. "\r\n"
  13820. "hi";
  13821. }
  13822. Server svr_;
  13823. int port_ = 0;
  13824. thread thread_;
  13825. };
  13826. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  13827. bool got_100 = false;
  13828. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  13829. EXPECT_TRUE(got_100);
  13830. }
  13831. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  13832. bool got_100 = true;
  13833. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  13834. EXPECT_FALSE(got_100);
  13835. }
  13836. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  13837. bool got_100 = false;
  13838. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  13839. EXPECT_TRUE(got_100);
  13840. }
  13841. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  13842. bool got_100 = false;
  13843. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  13844. EXPECT_TRUE(got_100);
  13845. }
  13846. #ifndef _WIN32
  13847. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13848. static constexpr char reject[] = "Unauthorized";
  13849. static constexpr char accept[] = "Upload accepted";
  13850. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13851. Server svr;
  13852. svr.set_expect_100_continue_handler(
  13853. [](const Request & /*req*/, Response &res) {
  13854. res.status = StatusCode::Unauthorized_401;
  13855. res.set_content(reject, "text/plain");
  13856. return res.status;
  13857. });
  13858. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13859. res.set_content(accept, "text/plain");
  13860. });
  13861. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13862. auto se = detail::scope_exit([&] {
  13863. svr.stop();
  13864. thread.join();
  13865. ASSERT_FALSE(svr.is_running());
  13866. });
  13867. svr.wait_until_ready();
  13868. {
  13869. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13870. curl_easy_init(), &curl_easy_cleanup};
  13871. ASSERT_NE(curl, nullptr);
  13872. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13873. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13874. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13875. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13876. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13877. &curl_slist_free_all};
  13878. ASSERT_NE(list, nullptr);
  13879. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13880. struct read_data {
  13881. size_t read_size;
  13882. size_t total_size;
  13883. } data = {0, total_size};
  13884. using read_callback_t =
  13885. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13886. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13887. void *userdata) -> size_t {
  13888. read_data *d = (read_data *)userdata;
  13889. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13890. std::fill_n(ptr, size * nmemb, 'A');
  13891. d->read_size += size * nmemb;
  13892. return size * nmemb;
  13893. };
  13894. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13895. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13896. std::vector<char> buffer;
  13897. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13898. using write_callback_t =
  13899. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13900. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13901. void *userdata) -> size_t {
  13902. std::vector<char> *buf = (std::vector<char> *)userdata;
  13903. buf->reserve(buf->size() + size * nmemb + 1);
  13904. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13905. return size * nmemb;
  13906. };
  13907. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13908. {
  13909. const auto res = curl_easy_perform(curl.get());
  13910. ASSERT_EQ(res, CURLE_OK);
  13911. }
  13912. {
  13913. auto response_code = long{};
  13914. const auto res =
  13915. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13916. ASSERT_EQ(res, CURLE_OK);
  13917. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13918. }
  13919. {
  13920. auto dl = curl_off_t{};
  13921. const auto res =
  13922. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13923. ASSERT_EQ(res, CURLE_OK);
  13924. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13925. }
  13926. {
  13927. buffer.push_back('\0');
  13928. ASSERT_STRCASEEQ(buffer.data(), reject);
  13929. }
  13930. }
  13931. }
  13932. #endif
  13933. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13934. // Regression test for #2458.
  13935. //
  13936. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13937. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13938. // ticket can make the client socket spuriously readable during the
  13939. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13940. // the client withholds the body and then blocks reading a response that never
  13941. // comes, failing with `Failed to read connection`.
  13942. //
  13943. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13944. // within the timeout. This raw OpenSSL server deliberately never sends
  13945. // `100 Continue`; the client must still deliver the body and receive 200.
  13946. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13947. signal(SIGPIPE, SIG_IGN);
  13948. const auto port = PORT + 4;
  13949. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13950. ASSERT_NE(srv, INVALID_SOCKET);
  13951. int opt = 1;
  13952. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13953. sockaddr_in addr{};
  13954. addr.sin_family = AF_INET;
  13955. addr.sin_port = htons(static_cast<uint16_t>(port));
  13956. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13957. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13958. ASSERT_EQ(0, ::listen(srv, 1));
  13959. std::atomic<size_t> server_body_bytes{0};
  13960. auto server_thread = std::thread([&] {
  13961. sockaddr_in cli_addr{};
  13962. socklen_t cli_len = sizeof(cli_addr);
  13963. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13964. if (cli == INVALID_SOCKET) { return; }
  13965. // Bound the lifetime of the server side so a buggy client (which never
  13966. // sends the body) cannot make this thread block forever on join.
  13967. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13968. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13969. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13970. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13971. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13972. SSL *ssl = SSL_new(ctx);
  13973. SSL_set_fd(ssl, static_cast<int>(cli));
  13974. if (SSL_accept(ssl) > 0) {
  13975. // Read the request headers. Reading here also flushes the TLS 1.3
  13976. // session tickets to the client. Deliberately do NOT send
  13977. // `100 Continue`.
  13978. std::string buf;
  13979. char tmp[1024];
  13980. while (buf.find("\r\n\r\n") == std::string::npos) {
  13981. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13982. if (n <= 0) { break; }
  13983. buf.append(tmp, static_cast<size_t>(n));
  13984. }
  13985. // A correct client sends the body now; count what arrives.
  13986. auto pos = buf.find("\r\n\r\n");
  13987. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13988. while (body < 4096) {
  13989. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13990. if (n <= 0) { break; }
  13991. body += static_cast<size_t>(n);
  13992. }
  13993. server_body_bytes = body;
  13994. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13995. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13996. SSL_shutdown(ssl);
  13997. }
  13998. SSL_free(ssl);
  13999. detail::close_socket(cli);
  14000. SSL_CTX_free(ctx);
  14001. });
  14002. auto se = detail::scope_exit([&] {
  14003. server_thread.join();
  14004. detail::close_socket(srv);
  14005. });
  14006. SSLClient cli("127.0.0.1", port);
  14007. cli.enable_server_certificate_verification(false);
  14008. cli.set_connection_timeout(5, 0);
  14009. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  14010. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  14011. std::string body(4096, 'A');
  14012. auto res = cli.Put("/api/test", body, "application/json");
  14013. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  14014. EXPECT_EQ(StatusCode::OK_200, res->status);
  14015. EXPECT_EQ(body.size(), server_body_bytes.load());
  14016. }
  14017. #endif
  14018. template <typename S, typename C>
  14019. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  14020. svr.Get("/stream", [&](const Request &, Response &res) {
  14021. auto data = new std::string("01234567890123456789");
  14022. res.set_content_provider(
  14023. data->size(), "text/plain",
  14024. [&, data](size_t offset, size_t length, DataSink &sink) {
  14025. const size_t DATA_CHUNK_SIZE = 4;
  14026. const auto &d = *data;
  14027. std::this_thread::sleep_for(std::chrono::seconds(1));
  14028. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  14029. return true;
  14030. },
  14031. [data](bool success) {
  14032. EXPECT_FALSE(success);
  14033. delete data;
  14034. });
  14035. });
  14036. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  14037. auto i = new size_t(0);
  14038. res.set_content_provider(
  14039. "text/plain",
  14040. [i](size_t, DataSink &sink) {
  14041. if (*i < 5) {
  14042. std::this_thread::sleep_for(std::chrono::seconds(1));
  14043. sink.write("abcd", 4);
  14044. (*i)++;
  14045. } else {
  14046. sink.done();
  14047. }
  14048. return true;
  14049. },
  14050. [i](bool success) {
  14051. EXPECT_FALSE(success);
  14052. delete i;
  14053. });
  14054. });
  14055. svr.Get("/chunked", [&](const Request &, Response &res) {
  14056. auto i = new size_t(0);
  14057. res.set_chunked_content_provider(
  14058. "text/plain",
  14059. [i](size_t, DataSink &sink) {
  14060. if (*i < 5) {
  14061. std::this_thread::sleep_for(std::chrono::seconds(1));
  14062. sink.os << "abcd";
  14063. (*i)++;
  14064. } else {
  14065. sink.done();
  14066. }
  14067. return true;
  14068. },
  14069. [i](bool success) {
  14070. EXPECT_FALSE(success);
  14071. delete i;
  14072. });
  14073. });
  14074. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14075. auto se = detail::scope_exit([&] {
  14076. svr.stop();
  14077. listen_thread.join();
  14078. ASSERT_FALSE(svr.is_running());
  14079. });
  14080. svr.wait_until_ready();
  14081. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  14082. {
  14083. auto start = std::chrono::steady_clock::now();
  14084. auto res = cli.Get("/stream");
  14085. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14086. std::chrono::steady_clock::now() - start)
  14087. .count();
  14088. ASSERT_FALSE(res);
  14089. EXPECT_EQ(Error::Read, res.error());
  14090. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14091. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14092. }
  14093. {
  14094. auto start = std::chrono::steady_clock::now();
  14095. auto res = cli.Get("/stream_without_length");
  14096. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14097. std::chrono::steady_clock::now() - start)
  14098. .count();
  14099. ASSERT_FALSE(res);
  14100. EXPECT_EQ(Error::Read, res.error());
  14101. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14102. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14103. }
  14104. {
  14105. auto start = std::chrono::steady_clock::now();
  14106. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  14107. EXPECT_EQ("abcd", string(data, data_length));
  14108. return true;
  14109. });
  14110. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14111. std::chrono::steady_clock::now() - start)
  14112. .count();
  14113. ASSERT_FALSE(res);
  14114. EXPECT_EQ(Error::Read, res.error());
  14115. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14116. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14117. }
  14118. }
  14119. TEST(MaxTimeoutTest, ContentStream) {
  14120. time_t timeout = 2000;
  14121. time_t threshold = 200;
  14122. Server svr;
  14123. Client cli("localhost", PORT);
  14124. max_timeout_test(svr, cli, timeout, threshold);
  14125. }
  14126. #ifdef CPPHTTPLIB_SSL_ENABLED
  14127. TEST(MaxTimeoutTest, ContentStreamSSL) {
  14128. time_t timeout = 2000;
  14129. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  14130. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14131. SSLClient cli("localhost", PORT);
  14132. cli.enable_server_certificate_verification(false);
  14133. max_timeout_test(svr, cli, timeout, threshold);
  14134. }
  14135. #endif
  14136. class EventDispatcher {
  14137. public:
  14138. EventDispatcher() {}
  14139. bool wait_event(DataSink *sink) {
  14140. unique_lock<mutex> lk(m_);
  14141. int id = id_;
  14142. // Wait with timeout to prevent hanging if client disconnects
  14143. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  14144. [&] { return cid_ == id; })) {
  14145. return false; // Timeout occurred
  14146. }
  14147. sink->write(message_.data(), message_.size());
  14148. return true;
  14149. }
  14150. void send_event(const string &message) {
  14151. lock_guard<mutex> lk(m_);
  14152. cid_ = id_++;
  14153. message_ = message;
  14154. cv_.notify_all();
  14155. }
  14156. private:
  14157. mutex m_;
  14158. condition_variable cv_;
  14159. atomic_int id_{0};
  14160. atomic_int cid_{-1};
  14161. string message_;
  14162. };
  14163. TEST(ClientInThreadTest, Issue2068) {
  14164. EventDispatcher ed;
  14165. Server svr;
  14166. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  14167. res.set_chunked_content_provider("text/event-stream",
  14168. [&](size_t /*offset*/, DataSink &sink) {
  14169. return ed.wait_event(&sink);
  14170. });
  14171. });
  14172. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  14173. svr.wait_until_ready();
  14174. thread event_thread([&] {
  14175. int id = 0;
  14176. while (svr.is_running()) {
  14177. this_thread::sleep_for(chrono::milliseconds(500));
  14178. std::stringstream ss;
  14179. ss << "data: " << id << "\n\n";
  14180. ed.send_event(ss.str());
  14181. id++;
  14182. }
  14183. });
  14184. auto se = detail::scope_exit([&] {
  14185. svr.stop();
  14186. listen_thread.join();
  14187. event_thread.join();
  14188. ASSERT_FALSE(svr.is_running());
  14189. });
  14190. {
  14191. auto client = detail::make_unique<Client>(HOST, PORT);
  14192. client->set_read_timeout(std::chrono::minutes(10));
  14193. std::atomic<bool> stop{false};
  14194. std::thread t([&] {
  14195. client->Get("/event1",
  14196. [&](const char *, size_t) -> bool { return !stop; });
  14197. });
  14198. std::this_thread::sleep_for(std::chrono::seconds(2));
  14199. stop = true;
  14200. client->stop();
  14201. t.join();
  14202. // Reset client after thread has finished
  14203. client.reset();
  14204. }
  14205. }
  14206. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  14207. auto handled = false;
  14208. Server svr;
  14209. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14210. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14211. auto se = detail::scope_exit([&] {
  14212. svr.stop();
  14213. t.join();
  14214. ASSERT_FALSE(svr.is_running());
  14215. ASSERT_FALSE(handled);
  14216. });
  14217. svr.wait_until_ready();
  14218. // Two Content-Length headers with different values — must be rejected
  14219. auto req = "POST /test HTTP/1.1\r\n"
  14220. "Content-Length: 5\r\n"
  14221. "Content-Length: 10\r\n"
  14222. "\r\n"
  14223. "hello";
  14224. std::string response;
  14225. ASSERT_TRUE(send_request(1, req, &response));
  14226. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14227. response.substr(0, response.find("\r\n")));
  14228. }
  14229. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  14230. auto handled = false;
  14231. Server svr;
  14232. svr.Post("/test", [&](const Request &, Response &res) {
  14233. handled = true;
  14234. res.set_content("ok", "text/plain");
  14235. });
  14236. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14237. auto se = detail::scope_exit([&] {
  14238. svr.stop();
  14239. t.join();
  14240. ASSERT_FALSE(svr.is_running());
  14241. ASSERT_TRUE(handled);
  14242. });
  14243. svr.wait_until_ready();
  14244. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  14245. auto req = "POST /test HTTP/1.1\r\n"
  14246. "Content-Length: 5\r\n"
  14247. "Content-Length: 5\r\n"
  14248. "\r\n"
  14249. "hello";
  14250. std::string response;
  14251. ASSERT_TRUE(send_request(1, req, &response));
  14252. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  14253. }
  14254. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  14255. Server svr;
  14256. svr.Get("/", [](const Request &req, Response &res) {
  14257. EXPECT_EQ(2U, req.trailers.size());
  14258. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  14259. // Denied
  14260. EXPECT_FALSE(req.has_trailer("Content-Length"));
  14261. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  14262. // Accepted
  14263. EXPECT_TRUE(req.has_trailer("X-Hello"));
  14264. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  14265. EXPECT_TRUE(req.has_trailer("X-World"));
  14266. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  14267. res.set_content("ok", "text/plain");
  14268. });
  14269. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14270. auto se = detail::scope_exit([&] {
  14271. svr.stop();
  14272. t.join();
  14273. ASSERT_FALSE(svr.is_running());
  14274. });
  14275. svr.wait_until_ready();
  14276. const std::string req = "GET / HTTP/1.1\r\n"
  14277. "Transfer-Encoding: chunked\r\n"
  14278. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  14279. "\r\n"
  14280. "0\r\n"
  14281. "Content-Length: 10\r\n"
  14282. "Host: internal.local\r\n"
  14283. "Content-Type: malicious/content\r\n"
  14284. "Cookie: any\r\n"
  14285. "Set-Cookie: any\r\n"
  14286. "X-Forwarded-For: attacker.com\r\n"
  14287. "X-Real-Ip: 1.1.1.1\r\n"
  14288. "X-Hello: hello\r\n"
  14289. "X-World: world\r\n"
  14290. "\r\n";
  14291. std::string res;
  14292. ASSERT_TRUE(send_request(1, req, &res));
  14293. }
  14294. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  14295. // several field lines, and the combined value is what has to be parsed. A
  14296. // Trailer field split across lines therefore declares every name it lists;
  14297. // reading only the first line silently drops the trailers the later lines
  14298. // declare. The prohibited-trailer filter still applies to every line.
  14299. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  14300. Server svr;
  14301. size_t observed_trailer_count = 0;
  14302. std::string observed_hello;
  14303. std::string observed_world;
  14304. bool observed_content_length = true;
  14305. svr.Get("/", [&](const Request &req, Response &res) {
  14306. observed_trailer_count = req.trailers.size();
  14307. observed_hello = req.get_trailer_value("X-Hello");
  14308. observed_world = req.get_trailer_value("X-World");
  14309. observed_content_length = req.has_trailer("Content-Length");
  14310. res.set_content("ok", "text/plain");
  14311. });
  14312. auto port = svr.bind_to_any_port(HOST);
  14313. thread t = thread([&]() { svr.listen_after_bind(); });
  14314. auto se = detail::scope_exit([&] {
  14315. svr.stop();
  14316. t.join();
  14317. ASSERT_FALSE(svr.is_running());
  14318. });
  14319. svr.wait_until_ready();
  14320. const std::string req = "GET / HTTP/1.1\r\n"
  14321. "Transfer-Encoding: chunked\r\n"
  14322. "Trailer: X-Hello\r\n"
  14323. "Trailer: X-World, Content-Length\r\n"
  14324. "\r\n"
  14325. "0\r\n"
  14326. "X-Hello: hello\r\n"
  14327. "X-World: world\r\n"
  14328. "Content-Length: 10\r\n"
  14329. "\r\n";
  14330. std::string res;
  14331. ASSERT_TRUE(send_request(1, req, &res, port));
  14332. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  14333. // Accepted: both field lines contribute to the declared set
  14334. EXPECT_EQ(2U, observed_trailer_count);
  14335. EXPECT_EQ(observed_hello, "hello");
  14336. EXPECT_EQ(observed_world, "world");
  14337. // Denied: a prohibited name stays prohibited on a later field line
  14338. EXPECT_FALSE(observed_content_length);
  14339. }
  14340. // A direct client that is not listed in trusted_proxies must not be able to
  14341. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  14342. // the peer address on the actual TCP connection determines whether the
  14343. // header is honored.
  14344. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  14345. Server svr;
  14346. // Deliberately does NOT include the loopback address the test client
  14347. // actually connects from, so the direct connection is not a trusted proxy.
  14348. svr.set_trusted_proxies({"203.0.113.66"});
  14349. std::string observed_remote_addr;
  14350. svr.Get("/ip", [&](const Request &req, Response &res) {
  14351. observed_remote_addr = req.remote_addr;
  14352. res.set_content("ok", "text/plain");
  14353. });
  14354. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14355. auto se = detail::scope_exit([&] {
  14356. svr.stop();
  14357. t.join();
  14358. ASSERT_FALSE(svr.is_running());
  14359. });
  14360. svr.wait_until_ready();
  14361. Client cli(HOST, PORT);
  14362. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  14363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14364. EXPECT_EQ(StatusCode::OK_200, res->status);
  14365. // The connecting peer is not a trusted proxy, so the spoofed header must be
  14366. // ignored entirely and the real connection-level address retained.
  14367. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14368. observed_remote_addr == "127.0.0.1");
  14369. }
  14370. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  14371. Server svr;
  14372. std::string observed_remote_addr;
  14373. std::string observed_xff;
  14374. svr.Get("/ip", [&](const Request &req, Response &res) {
  14375. observed_remote_addr = req.remote_addr;
  14376. observed_xff = req.get_header_value("X-Forwarded-For");
  14377. res.set_content("ok", "text/plain");
  14378. });
  14379. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14380. auto se = detail::scope_exit([&] {
  14381. svr.stop();
  14382. t.join();
  14383. ASSERT_FALSE(svr.is_running());
  14384. });
  14385. svr.wait_until_ready();
  14386. Client cli(HOST, PORT);
  14387. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  14388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14389. EXPECT_EQ(StatusCode::OK_200, res->status);
  14390. EXPECT_EQ(observed_xff, "203.0.113.66");
  14391. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14392. observed_remote_addr == "127.0.0.1");
  14393. }
  14394. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  14395. Server svr;
  14396. svr.set_trusted_proxies({"203.0.113.66"});
  14397. std::string observed_remote_addr;
  14398. std::string observed_xff;
  14399. svr.Get("/ip", [&](const Request &req, Response &res) {
  14400. observed_remote_addr = req.remote_addr;
  14401. observed_xff = req.get_header_value("X-Forwarded-For");
  14402. res.set_content("ok", "text/plain");
  14403. });
  14404. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14405. auto se = detail::scope_exit([&] {
  14406. svr.stop();
  14407. t.join();
  14408. ASSERT_FALSE(svr.is_running());
  14409. });
  14410. svr.wait_until_ready();
  14411. Client cli(HOST, PORT);
  14412. auto res = cli.Get("/ip");
  14413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14414. EXPECT_EQ(StatusCode::OK_200, res->status);
  14415. EXPECT_EQ(observed_xff, "");
  14416. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14417. observed_remote_addr == "127.0.0.1");
  14418. }
  14419. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  14420. Server svr;
  14421. // Include the loopback address the test client actually connects from, so
  14422. // the direct connection itself is recognized as the trusted proxy hop.
  14423. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  14424. std::string observed_remote_addr;
  14425. std::string observed_xff;
  14426. svr.Get("/ip", [&](const Request &req, Response &res) {
  14427. observed_remote_addr = req.remote_addr;
  14428. observed_xff = req.get_header_value("X-Forwarded-For");
  14429. res.set_content("ok", "text/plain");
  14430. });
  14431. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14432. auto se = detail::scope_exit([&] {
  14433. svr.stop();
  14434. t.join();
  14435. ASSERT_FALSE(svr.is_running());
  14436. });
  14437. svr.wait_until_ready();
  14438. Client cli(HOST, PORT);
  14439. auto res = cli.Get(
  14440. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  14441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14442. EXPECT_EQ(StatusCode::OK_200, res->status);
  14443. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  14444. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14445. }
  14446. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  14447. Server svr;
  14448. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  14449. std::string observed_remote_addr;
  14450. std::string observed_xff;
  14451. svr.Get("/ip", [&](const Request &req, Response &res) {
  14452. observed_remote_addr = req.remote_addr;
  14453. observed_xff = req.get_header_value("X-Forwarded-For");
  14454. res.set_content("ok", "text/plain");
  14455. });
  14456. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14457. auto se = detail::scope_exit([&] {
  14458. svr.stop();
  14459. t.join();
  14460. ASSERT_FALSE(svr.is_running());
  14461. });
  14462. svr.wait_until_ready();
  14463. Client cli(HOST, PORT);
  14464. auto res = cli.Get(
  14465. "/ip",
  14466. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14468. EXPECT_EQ(StatusCode::OK_200, res->status);
  14469. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14470. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14471. }
  14472. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  14473. Server svr;
  14474. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14475. std::string observed_remote_addr;
  14476. std::string observed_xff;
  14477. svr.Get("/ip", [&](const Request &req, Response &res) {
  14478. observed_remote_addr = req.remote_addr;
  14479. observed_xff = req.get_header_value("X-Forwarded-For");
  14480. res.set_content("ok", "text/plain");
  14481. });
  14482. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14483. auto se = detail::scope_exit([&] {
  14484. svr.stop();
  14485. t.join();
  14486. ASSERT_FALSE(svr.is_running());
  14487. });
  14488. svr.wait_until_ready();
  14489. Client cli(HOST, PORT);
  14490. auto res = cli.Get(
  14491. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  14492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14493. EXPECT_EQ(StatusCode::OK_200, res->status);
  14494. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  14495. // by the closest hop) is used. The leftmost entry is fully client-controlled
  14496. // and must not be selected.
  14497. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  14498. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  14499. }
  14500. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  14501. Server svr;
  14502. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14503. std::string observed_remote_addr;
  14504. svr.Get("/ip", [&](const Request &req, Response &res) {
  14505. observed_remote_addr = req.remote_addr;
  14506. res.set_content("ok", "text/plain");
  14507. });
  14508. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14509. auto se = detail::scope_exit([&] {
  14510. svr.stop();
  14511. t.join();
  14512. ASSERT_FALSE(svr.is_running());
  14513. });
  14514. svr.wait_until_ready();
  14515. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14516. // a forged address and the trusted proxy's own address; the forged value must
  14517. // not win over the address the trusted proxy actually recorded.
  14518. Client cli(HOST, PORT);
  14519. auto res = cli.Get(
  14520. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14522. EXPECT_EQ(StatusCode::OK_200, res->status);
  14523. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14524. }
  14525. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14526. Server svr;
  14527. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14528. std::string observed_remote_addr;
  14529. std::string observed_xff;
  14530. svr.Get("/ip", [&](const Request &req, Response &res) {
  14531. observed_remote_addr = req.remote_addr;
  14532. observed_xff = req.get_header_value("X-Forwarded-For");
  14533. res.set_content("ok", "text/plain");
  14534. });
  14535. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14536. auto se = detail::scope_exit([&] {
  14537. svr.stop();
  14538. t.join();
  14539. ASSERT_FALSE(svr.is_running());
  14540. });
  14541. svr.wait_until_ready();
  14542. Client cli(HOST, PORT);
  14543. auto res = cli.Get(
  14544. "/ip",
  14545. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14547. EXPECT_EQ(StatusCode::OK_200, res->status);
  14548. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14549. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14550. }
  14551. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14552. Server svr;
  14553. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14554. std::string observed_remote_addr;
  14555. std::string observed_xff;
  14556. svr.Get("/ip", [&](const Request &req, Response &res) {
  14557. observed_remote_addr = req.remote_addr;
  14558. observed_xff = req.get_header_value("X-Forwarded-For");
  14559. res.set_content("ok", "text/plain");
  14560. });
  14561. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14562. auto se = detail::scope_exit([&] {
  14563. svr.stop();
  14564. t.join();
  14565. ASSERT_FALSE(svr.is_running());
  14566. });
  14567. svr.wait_until_ready();
  14568. std::string raw_req =
  14569. "GET /ip HTTP/1.1\r\n"
  14570. "Host: localhost\r\n"
  14571. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14572. "Connection: close\r\n"
  14573. "\r\n";
  14574. std::string out;
  14575. ASSERT_TRUE(send_request(5, raw_req, &out));
  14576. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14577. // Header parser trims surrounding whitespace of the header value
  14578. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14579. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14580. }
  14581. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  14582. // one comma-joined value, in the order received. Proxies such as HAProxy append
  14583. // their own X-Forwarded-For as a separate field line rather than extending the
  14584. // one the client sent, so every occurrence has to be taken into account.
  14585. // Reading only the first one hands back the address the client chose.
  14586. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  14587. Server svr;
  14588. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14589. std::string observed_remote_addr;
  14590. size_t observed_xff_count = 0;
  14591. svr.Get("/ip", [&](const Request &req, Response &res) {
  14592. observed_remote_addr = req.remote_addr;
  14593. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  14594. res.set_content("ok", "text/plain");
  14595. });
  14596. auto port = svr.bind_to_any_port(HOST);
  14597. thread t = thread([&]() { svr.listen_after_bind(); });
  14598. auto se = detail::scope_exit([&] {
  14599. svr.stop();
  14600. t.join();
  14601. ASSERT_FALSE(svr.is_running());
  14602. });
  14603. svr.wait_until_ready();
  14604. // The client supplies the first field line; the trusted proxy appends the
  14605. // address it observed as a second one.
  14606. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  14607. "Host: localhost\r\n"
  14608. "X-Forwarded-For: 1.2.3.4\r\n"
  14609. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  14610. "Connection: close\r\n"
  14611. "\r\n";
  14612. std::string out;
  14613. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14614. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14615. EXPECT_EQ(observed_xff_count, 2U);
  14616. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14617. // The same chain spread over one field line per hop derives the same client
  14618. // address, i.e. the split and the comma-joined representations agree.
  14619. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  14620. "Host: localhost\r\n"
  14621. "X-Forwarded-For: 1.2.3.4\r\n"
  14622. "X-Forwarded-For: 198.51.100.23\r\n"
  14623. "X-Forwarded-For: 192.0.2.45\r\n"
  14624. "Connection: close\r\n"
  14625. "\r\n";
  14626. out.clear();
  14627. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  14628. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14629. EXPECT_EQ(observed_xff_count, 3U);
  14630. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14631. }
  14632. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14633. // crash the server (it used to call front() on an empty vector inside
  14634. // get_client_ip). The connection-level remote address must be retained instead.
  14635. static void run_malformed_xff_test(const std::string &xff_value) {
  14636. Server svr;
  14637. svr.set_trusted_proxies({"192.0.2.45"});
  14638. std::string observed_remote_addr;
  14639. svr.Get("/ip", [&](const Request &req, Response &res) {
  14640. observed_remote_addr = req.remote_addr;
  14641. res.set_content("ok", "text/plain");
  14642. });
  14643. int port = 0;
  14644. thread t = thread([&]() {
  14645. port = svr.bind_to_any_port(HOST);
  14646. svr.listen_after_bind();
  14647. });
  14648. auto se = detail::scope_exit([&] {
  14649. svr.stop();
  14650. t.join();
  14651. ASSERT_FALSE(svr.is_running());
  14652. });
  14653. svr.wait_until_ready();
  14654. Client cli(HOST, port);
  14655. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  14656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14657. EXPECT_EQ(StatusCode::OK_200, res->status);
  14658. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14659. observed_remote_addr == "127.0.0.1");
  14660. }
  14661. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  14662. run_malformed_xff_test("");
  14663. }
  14664. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  14665. run_malformed_xff_test(",");
  14666. }
  14667. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  14668. run_malformed_xff_test(", , ,");
  14669. }
  14670. // The same rule applies to Accept: a request whose acceptable types are spread
  14671. // over several field lines must be negotiated against all of them.
  14672. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  14673. // case-insensitive connection options. Comparing the whole field value against
  14674. // one option misses a client that sends several of them, and misses every
  14675. // casing but the one written in the comparison.
  14676. //
  14677. // Sends req, reads the response, then reuses the same socket for a second
  14678. // request to find out whether the server kept the connection.
  14679. static void probe_connection_reuse(int port, const std::string &req,
  14680. bool *announced_close, bool *reusable) {
  14681. auto error = Error::Success;
  14682. auto sock = detail::create_client_socket(
  14683. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  14684. /*connection_timeout_sec=*/5, 0,
  14685. /*read_timeout_sec=*/1, 0,
  14686. /*write_timeout_sec=*/5, 0, std::string(), error);
  14687. ASSERT_NE(sock, INVALID_SOCKET);
  14688. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  14689. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  14690. "Host: localhost\r\n"
  14691. "Connection: close\r\n"
  14692. "\r\n";
  14693. std::string first_response;
  14694. std::string second_response;
  14695. detail::process_client_socket(
  14696. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  14697. [&](Stream &strm) {
  14698. if (strm.write(req.data(), req.size()) !=
  14699. static_cast<ssize_t>(req.size())) {
  14700. return false;
  14701. }
  14702. char buf[512];
  14703. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  14704. // Headers plus the two-byte body of the handler below
  14705. while (reader.getline()) {
  14706. first_response += reader.ptr();
  14707. if (first_response.find("ok") != std::string::npos) { break; }
  14708. }
  14709. if (strm.write(second.data(), second.size()) !=
  14710. static_cast<ssize_t>(second.size())) {
  14711. return true;
  14712. }
  14713. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  14714. while (reader2.getline()) {
  14715. second_response += reader2.ptr();
  14716. if (second_response.find("ok") != std::string::npos) { break; }
  14717. }
  14718. return true;
  14719. });
  14720. *announced_close =
  14721. first_response.find("Connection: close") != std::string::npos;
  14722. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  14723. }
  14724. class ConnectionTokenTest : public ::testing::Test {
  14725. protected:
  14726. void SetUp() override {
  14727. svr_.Get("/keepalive", [](const Request &, Response &res) {
  14728. res.set_content("ok", "text/plain");
  14729. });
  14730. port_ = svr_.bind_to_any_port(HOST);
  14731. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14732. svr_.wait_until_ready();
  14733. }
  14734. void TearDown() override {
  14735. svr_.stop();
  14736. if (thread_.joinable()) { thread_.join(); }
  14737. }
  14738. Server svr_;
  14739. int port_ = 0;
  14740. thread thread_;
  14741. };
  14742. // "close" alongside another option still closes the connection, and the
  14743. // response says so rather than leaving the peer to discover it.
  14744. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  14745. bool announced_close = false;
  14746. bool reusable = true;
  14747. probe_connection_reuse(port_,
  14748. "GET /keepalive HTTP/1.1\r\n"
  14749. "Host: localhost\r\n"
  14750. "Connection: keep-alive, close\r\n"
  14751. "\r\n",
  14752. &announced_close, &reusable);
  14753. EXPECT_TRUE(announced_close);
  14754. EXPECT_FALSE(reusable);
  14755. }
  14756. // "close" split over two field lines is the same list, so it is honored too.
  14757. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  14758. bool announced_close = false;
  14759. bool reusable = true;
  14760. probe_connection_reuse(port_,
  14761. "GET /keepalive HTTP/1.1\r\n"
  14762. "Host: localhost\r\n"
  14763. "Connection: keep-alive\r\n"
  14764. "Connection: close\r\n"
  14765. "\r\n",
  14766. &announced_close, &reusable);
  14767. EXPECT_TRUE(announced_close);
  14768. EXPECT_FALSE(reusable);
  14769. }
  14770. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  14771. // keep-alive in the spelling everyone actually sends keeps its connection.
  14772. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  14773. bool announced_close = false;
  14774. bool reusable = false;
  14775. probe_connection_reuse(port_,
  14776. "GET /keepalive HTTP/1.0\r\n"
  14777. "Host: localhost\r\n"
  14778. "Connection: keep-alive\r\n"
  14779. "\r\n",
  14780. &announced_close, &reusable);
  14781. EXPECT_FALSE(announced_close);
  14782. EXPECT_TRUE(reusable);
  14783. }
  14784. // A token the value merely contains is not the token itself.
  14785. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  14786. bool announced_close = false;
  14787. bool reusable = false;
  14788. probe_connection_reuse(port_,
  14789. "GET /keepalive HTTP/1.1\r\n"
  14790. "Host: localhost\r\n"
  14791. "Connection: notclose\r\n"
  14792. "\r\n",
  14793. &announced_close, &reusable);
  14794. EXPECT_FALSE(announced_close);
  14795. EXPECT_TRUE(reusable);
  14796. }
  14797. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  14798. Server svr;
  14799. std::vector<std::string> observed_types;
  14800. svr.Get("/", [&](const Request &req, Response &res) {
  14801. observed_types = req.accept_content_types;
  14802. res.set_content("ok", "text/plain");
  14803. });
  14804. auto port = svr.bind_to_any_port(HOST);
  14805. thread t = thread([&]() { svr.listen_after_bind(); });
  14806. auto se = detail::scope_exit([&] {
  14807. svr.stop();
  14808. t.join();
  14809. ASSERT_FALSE(svr.is_running());
  14810. });
  14811. svr.wait_until_ready();
  14812. Client cli(HOST, port);
  14813. Headers headers;
  14814. headers.emplace("Accept", "text/plain;q=0.5");
  14815. headers.emplace("Accept", "application/json");
  14816. auto res = cli.Get("/", headers);
  14817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14818. EXPECT_EQ(StatusCode::OK_200, res->status);
  14819. // Sorted by q-value, so the second field line's type comes first
  14820. ASSERT_EQ(2U, observed_types.size());
  14821. EXPECT_EQ("application/json", observed_types[0]);
  14822. EXPECT_EQ("text/plain", observed_types[1]);
  14823. }
  14824. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  14825. // empty field line must not contribute a bare comma to the combined value.
  14826. // parse_accept_header() rejects a leading comma outright, so a stray one would
  14827. // turn a legal request into 400 Bad Request.
  14828. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  14829. Server svr;
  14830. std::vector<std::string> observed_types;
  14831. svr.Get("/", [&](const Request &req, Response &res) {
  14832. observed_types = req.accept_content_types;
  14833. res.set_content("ok", "text/plain");
  14834. });
  14835. auto port = svr.bind_to_any_port(HOST);
  14836. thread t = thread([&]() { svr.listen_after_bind(); });
  14837. auto se = detail::scope_exit([&] {
  14838. svr.stop();
  14839. t.join();
  14840. ASSERT_FALSE(svr.is_running());
  14841. });
  14842. svr.wait_until_ready();
  14843. // Empty first field line, then a real one
  14844. std::string raw_req = "GET / HTTP/1.1\r\n"
  14845. "Host: localhost\r\n"
  14846. "Accept:\r\n"
  14847. "Accept: application/json\r\n"
  14848. "Connection: close\r\n"
  14849. "\r\n";
  14850. std::string out;
  14851. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14852. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14853. ASSERT_EQ(1U, observed_types.size());
  14854. EXPECT_EQ("application/json", observed_types[0]);
  14855. }
  14856. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14857. // An encoding offered on a later Accept-Encoding field line is still offered.
  14858. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  14859. Server svr;
  14860. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14861. res.set_content(std::string(1024, 'x'), "text/plain");
  14862. });
  14863. auto port = svr.bind_to_any_port(HOST);
  14864. thread t = thread([&]() { svr.listen_after_bind(); });
  14865. auto se = detail::scope_exit([&] {
  14866. svr.stop();
  14867. t.join();
  14868. ASSERT_FALSE(svr.is_running());
  14869. });
  14870. svr.wait_until_ready();
  14871. Client cli(HOST, port);
  14872. cli.set_decompress(false);
  14873. Headers headers;
  14874. headers.emplace("Accept-Encoding", "identity");
  14875. headers.emplace("Accept-Encoding", "gzip");
  14876. auto res = cli.Get("/", headers);
  14877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14878. EXPECT_EQ(StatusCode::OK_200, res->status);
  14879. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  14880. }
  14881. #endif
  14882. #ifndef _WIN32
  14883. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  14884. Server svr;
  14885. svr.Post("/post", [&](const Request &req, Response &res) {
  14886. res.set_content(req.body, "text/plain");
  14887. });
  14888. svr.Put("/put", [&](const Request &req, Response &res) {
  14889. res.set_content(req.body, "text/plain");
  14890. });
  14891. svr.Patch("/patch", [&](const Request &req, Response &res) {
  14892. res.set_content(req.body, "text/plain");
  14893. });
  14894. svr.Delete("/delete", [&](const Request &req, Response &res) {
  14895. res.set_content(req.body, "text/plain");
  14896. });
  14897. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14898. auto se = detail::scope_exit([&] {
  14899. svr.stop();
  14900. t.join();
  14901. ASSERT_FALSE(svr.is_running());
  14902. });
  14903. svr.wait_until_ready();
  14904. std::string resp;
  14905. // POST without Content-Length
  14906. ASSERT_TRUE(send_request(5,
  14907. "POST /post HTTP/1.1\r\n"
  14908. "Host: localhost\r\n"
  14909. "Connection: close\r\n"
  14910. "\r\n",
  14911. &resp));
  14912. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14913. // PUT without Content-Length
  14914. resp.clear();
  14915. ASSERT_TRUE(send_request(5,
  14916. "PUT /put HTTP/1.1\r\n"
  14917. "Host: localhost\r\n"
  14918. "Connection: close\r\n"
  14919. "\r\n",
  14920. &resp));
  14921. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14922. // PATCH without Content-Length
  14923. resp.clear();
  14924. ASSERT_TRUE(send_request(5,
  14925. "PATCH /patch HTTP/1.1\r\n"
  14926. "Host: localhost\r\n"
  14927. "Connection: close\r\n"
  14928. "\r\n",
  14929. &resp));
  14930. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14931. // DELETE without Content-Length
  14932. resp.clear();
  14933. ASSERT_TRUE(send_request(5,
  14934. "DELETE /delete HTTP/1.1\r\n"
  14935. "Host: localhost\r\n"
  14936. "Connection: close\r\n"
  14937. "\r\n",
  14938. &resp));
  14939. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14940. }
  14941. #endif
  14942. //==============================================================================
  14943. // open_stream() Tests
  14944. //==============================================================================
  14945. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  14946. std::string result;
  14947. char buf[8192];
  14948. ssize_t n;
  14949. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14950. result.append(buf, static_cast<size_t>(n));
  14951. }
  14952. return result;
  14953. }
  14954. // Mock stream for unit tests
  14955. class MockStream : public Stream {
  14956. public:
  14957. std::string data;
  14958. size_t pos = 0;
  14959. ssize_t error_after = -1; // -1 = no error
  14960. explicit MockStream(const std::string &d, ssize_t err = -1)
  14961. : data(d), error_after(err) {}
  14962. bool is_readable() const override { return true; }
  14963. bool wait_readable() const override { return true; }
  14964. bool wait_writable() const override { return true; }
  14965. ssize_t read(char *ptr, size_t size) override {
  14966. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  14967. if (pos >= data.size()) return 0;
  14968. size_t limit =
  14969. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  14970. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  14971. std::memcpy(ptr, data.data() + pos, to_read);
  14972. pos += to_read;
  14973. return static_cast<ssize_t>(to_read);
  14974. }
  14975. ssize_t write(const char *, size_t) override { return -1; }
  14976. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  14977. ip = "127.0.0.1";
  14978. port = 0;
  14979. }
  14980. void get_local_ip_and_port(std::string &ip, int &port) const override {
  14981. ip = "127.0.0.1";
  14982. port = 0;
  14983. }
  14984. socket_t socket() const override { return INVALID_SOCKET; }
  14985. time_t duration() const override { return 0; }
  14986. };
  14987. TEST(StreamHandleTest, Basic) {
  14988. ClientImpl::StreamHandle handle;
  14989. EXPECT_FALSE(handle.is_valid());
  14990. handle.response = detail::make_unique<Response>();
  14991. handle.error = Error::Connection;
  14992. EXPECT_FALSE(handle.is_valid());
  14993. handle.error = Error::Success;
  14994. EXPECT_TRUE(handle.is_valid());
  14995. }
  14996. TEST(BodyReaderTest, Basic) {
  14997. MockStream stream("Hello, World!");
  14998. detail::BodyReader reader;
  14999. reader.stream = &stream;
  15000. reader.content_length = 13;
  15001. char buf[32];
  15002. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  15003. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  15004. EXPECT_TRUE(reader.eof);
  15005. }
  15006. TEST(BodyReaderTest, NoStream) {
  15007. detail::BodyReader reader;
  15008. char buf[32];
  15009. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15010. EXPECT_EQ(Error::Connection, reader.last_error);
  15011. }
  15012. TEST(BodyReaderTest, Error) {
  15013. MockStream stream("Hello, World!", 5);
  15014. detail::BodyReader reader;
  15015. reader.stream = &stream;
  15016. reader.content_length = 13;
  15017. char buf[32];
  15018. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  15019. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15020. EXPECT_EQ(Error::Read, reader.last_error);
  15021. }
  15022. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  15023. // Mock-based StreamHandle tests relying on private internals are removed.
  15024. class OpenStreamTest : public ::testing::Test {
  15025. protected:
  15026. void SetUp() override {
  15027. svr_.Get("/hello", [](const Request &, Response &res) {
  15028. res.set_content("Hello World!", "text/plain");
  15029. });
  15030. svr_.Get("/large", [](const Request &, Response &res) {
  15031. res.set_content(std::string(10000, 'X'), "text/plain");
  15032. });
  15033. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  15034. res.set_content("Hello World!", "image/jpeg");
  15035. res.set_header("Content-Encoding", "UTF-8");
  15036. });
  15037. svr_.Get("/chunked", [](const Request &, Response &res) {
  15038. res.set_chunked_content_provider("text/plain",
  15039. [](size_t offset, DataSink &sink) {
  15040. if (offset < 15) {
  15041. sink.write("chunk", 5);
  15042. return true;
  15043. }
  15044. sink.done();
  15045. return true;
  15046. });
  15047. });
  15048. svr_.Get("/compressible", [](const Request &, Response &res) {
  15049. res.set_chunked_content_provider("text/plain", [](size_t offset,
  15050. DataSink &sink) {
  15051. if (offset < 100 * 1024) {
  15052. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  15053. sink.write(chunk.data(), chunk.size());
  15054. return true;
  15055. }
  15056. sink.done();
  15057. return true;
  15058. });
  15059. });
  15060. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  15061. [](const Request & /*req*/, Response &res) {
  15062. auto i = new int(0);
  15063. res.set_header("Trailer", "Content-Length, X-Allowed");
  15064. res.set_chunked_content_provider(
  15065. "text/plain",
  15066. [i](size_t /*offset*/, DataSink &sink) {
  15067. switch (*i) {
  15068. case 0: sink.os << "123"; break;
  15069. case 1: sink.os << "456"; break;
  15070. case 2: sink.os << "789"; break;
  15071. case 3: {
  15072. sink.done_with_trailer(
  15073. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  15074. } break;
  15075. }
  15076. (*i)++;
  15077. return true;
  15078. },
  15079. [i](bool success) {
  15080. EXPECT_TRUE(success);
  15081. delete i;
  15082. });
  15083. });
  15084. // Echo headers endpoint for header-related tests
  15085. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  15086. std::string body;
  15087. for (const auto &h : req.headers) {
  15088. body.append(h.first);
  15089. body.push_back(':');
  15090. body.append(h.second);
  15091. body.push_back('\n');
  15092. }
  15093. res.set_content(body, "text/plain");
  15094. });
  15095. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  15096. std::string body;
  15097. for (const auto &h : req.headers) {
  15098. body.append(h.first);
  15099. body.push_back(':');
  15100. body.append(h.second);
  15101. body.push_back('\n');
  15102. }
  15103. res.set_content(body, "text/plain");
  15104. });
  15105. port_ = svr_.bind_to_any_port("127.0.0.1");
  15106. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15107. svr_.wait_until_ready();
  15108. }
  15109. void TearDown() override {
  15110. svr_.stop();
  15111. if (thread_.joinable()) thread_.join();
  15112. }
  15113. Server svr_;
  15114. std::thread thread_;
  15115. int port_ = 0;
  15116. };
  15117. TEST_F(OpenStreamTest, Basic) {
  15118. Client cli("127.0.0.1", port_);
  15119. auto handle = cli.open_stream("GET", "/hello");
  15120. EXPECT_TRUE(handle.is_valid());
  15121. EXPECT_EQ("Hello World!", read_all(handle));
  15122. }
  15123. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  15124. Client cli("127.0.0.1", port_);
  15125. auto handle = cli.open_stream("GET", "/unknown-encoding");
  15126. ASSERT_TRUE(handle.is_valid());
  15127. EXPECT_EQ("Hello World!", read_all(handle));
  15128. }
  15129. TEST_F(OpenStreamTest, SmallBuffer) {
  15130. Client cli("127.0.0.1", port_);
  15131. auto handle = cli.open_stream("GET", "/hello");
  15132. std::string result;
  15133. char buf[4];
  15134. ssize_t n;
  15135. while ((n = handle.read(buf, sizeof(buf))) > 0)
  15136. result.append(buf, static_cast<size_t>(n));
  15137. EXPECT_EQ("Hello World!", result);
  15138. }
  15139. TEST_F(OpenStreamTest, DefaultHeaders) {
  15140. Client cli("127.0.0.1", port_);
  15141. // open_stream GET should include Host, User-Agent and Accept-Encoding
  15142. {
  15143. auto handle = cli.open_stream("GET", "/echo-headers");
  15144. ASSERT_TRUE(handle.is_valid());
  15145. auto body = read_all(handle);
  15146. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  15147. std::string::npos);
  15148. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  15149. std::string::npos);
  15150. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  15151. }
  15152. // open_stream POST with body and no explicit content_type should NOT add
  15153. // text/plain Content-Type (behavior differs from non-streaming path), but
  15154. // should include Content-Length
  15155. {
  15156. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  15157. ASSERT_TRUE(handle.is_valid());
  15158. auto body = read_all(handle);
  15159. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  15160. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  15161. }
  15162. // open_stream POST with explicit Content-Type should preserve it
  15163. {
  15164. auto handle = cli.open_stream("POST", "/echo-headers", {},
  15165. {{"Content-Type", "application/custom"}},
  15166. "{}", "application/custom");
  15167. ASSERT_TRUE(handle.is_valid());
  15168. auto body = read_all(handle);
  15169. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  15170. }
  15171. // User-specified User-Agent must not be overwritten for stream API
  15172. {
  15173. auto handle = cli.open_stream("GET", "/echo-headers", {},
  15174. {{"User-Agent", "MyAgent/1.2"}});
  15175. ASSERT_TRUE(handle.is_valid());
  15176. auto body = read_all(handle);
  15177. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  15178. }
  15179. }
  15180. TEST_F(OpenStreamTest, Large) {
  15181. Client cli("127.0.0.1", port_);
  15182. auto handle = cli.open_stream("GET", "/large");
  15183. EXPECT_EQ(10000u, read_all(handle).size());
  15184. }
  15185. TEST_F(OpenStreamTest, ConnectionError) {
  15186. Client cli("127.0.0.1", 9999);
  15187. auto handle = cli.open_stream("GET", "/hello");
  15188. EXPECT_FALSE(handle.is_valid());
  15189. }
  15190. TEST_F(OpenStreamTest, Chunked) {
  15191. Client cli("127.0.0.1", port_);
  15192. auto handle = cli.open_stream("GET", "/chunked");
  15193. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15194. "Transfer-Encoding") == "chunked");
  15195. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  15196. }
  15197. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  15198. Client cli("127.0.0.1", port_);
  15199. auto handle =
  15200. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  15201. ASSERT_TRUE(handle.is_valid());
  15202. // Consume body to allow trailers to be received/parsed
  15203. auto body = read_all(handle);
  15204. // Explicitly parse trailers (ensure trailers are available for assertion)
  15205. handle.parse_trailers_if_needed();
  15206. EXPECT_EQ(std::string("123456789"), body);
  15207. // The response should include a Trailer header declaring both names
  15208. ASSERT_TRUE(handle.response);
  15209. EXPECT_TRUE(handle.response->has_header("Trailer"));
  15210. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  15211. handle.response->get_header_value("Trailer"));
  15212. // Prohibited trailer must not be present
  15213. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  15214. // Allowed trailer should be present
  15215. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  15216. EXPECT_EQ(std::string("yes"),
  15217. handle.response->get_trailer_value("X-Allowed"));
  15218. // Verify trailers are NOT present as regular headers
  15219. EXPECT_EQ(std::string(""),
  15220. handle.response->get_header_value("Content-Length"));
  15221. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  15222. }
  15223. static std::thread serve_single_response(std::promise<int> &port_promise,
  15224. const std::string &response) {
  15225. return std::thread([&port_promise, response] {
  15226. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15227. default_socket_options(srv);
  15228. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  15229. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  15230. sockaddr_in addr{};
  15231. addr.sin_family = AF_INET;
  15232. addr.sin_port = htons(0); // Let OS assign a free port
  15233. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15234. int opt = 1;
  15235. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  15236. #ifdef _WIN32
  15237. reinterpret_cast<const char *>(&opt),
  15238. #else
  15239. &opt,
  15240. #endif
  15241. sizeof(opt));
  15242. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  15243. ::listen(srv, 1) != 0) {
  15244. port_promise.set_value(-1);
  15245. detail::close_socket(srv);
  15246. return;
  15247. }
  15248. socklen_t addr_len = sizeof(addr);
  15249. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  15250. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  15251. sockaddr_in cli_addr{};
  15252. socklen_t cli_len = sizeof(cli_addr);
  15253. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15254. if (cli != INVALID_SOCKET) {
  15255. // Read the complete HTTP request (until the blank line that terminates
  15256. // headers) before sending the response. If the server closes the socket
  15257. // while the client's request data is still unread in the kernel receive
  15258. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  15259. // connection on both sides: it discards the client's receive buffer
  15260. // (which already holds our response) and causes any in-progress write on
  15261. // the client to fail with ECONNRESET. Reading all request data first
  15262. // ensures close() emits a graceful FIN.
  15263. {
  15264. char rbuf[256];
  15265. std::string req;
  15266. while (req.find("\r\n\r\n") == std::string::npos) {
  15267. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  15268. if (n <= 0) { break; }
  15269. req.append(rbuf, static_cast<size_t>(n));
  15270. }
  15271. }
  15272. ::send(cli,
  15273. #ifdef _WIN32
  15274. static_cast<const char *>(response.c_str()),
  15275. static_cast<int>(response.size()),
  15276. #else
  15277. response.c_str(), response.size(),
  15278. #endif
  15279. 0);
  15280. detail::close_socket(cli);
  15281. }
  15282. detail::close_socket(srv);
  15283. });
  15284. }
  15285. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  15286. #ifndef _WIN32
  15287. signal(SIGPIPE, SIG_IGN);
  15288. #endif
  15289. std::promise<int> port_promise;
  15290. auto port_future = port_promise.get_future();
  15291. auto server_thread =
  15292. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  15293. "Content-Type: text/plain\r\n"
  15294. "Content-Length: not-a-number\r\n"
  15295. "Connection: close\r\n"
  15296. "\r\n"
  15297. "hello");
  15298. auto port = port_future.get();
  15299. ASSERT_GT(port, 0);
  15300. Client cli("127.0.0.1", port);
  15301. auto handle = cli.open_stream("GET", "/");
  15302. EXPECT_FALSE(handle.is_valid());
  15303. server_thread.join();
  15304. }
  15305. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  15306. #ifndef _WIN32
  15307. signal(SIGPIPE, SIG_IGN);
  15308. #endif
  15309. std::promise<int> port_promise;
  15310. auto port_future = port_promise.get_future();
  15311. auto server_thread = serve_single_response(
  15312. port_promise, "HTTP/1.1 200 OK\r\n"
  15313. "Content-Type: text/plain\r\n"
  15314. "Content-Length: 99999999999999999999999999\r\n"
  15315. "Connection: close\r\n"
  15316. "\r\n"
  15317. "hello");
  15318. auto port = port_future.get();
  15319. ASSERT_GT(port, 0);
  15320. // Historically std::stoull would throw std::out_of_range here and crash
  15321. // the process, then parsing silently clamped to a bogus framing length and
  15322. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  15323. // so the stream fails to open, matching the not-a-number case above. The
  15324. // process still must NOT terminate.
  15325. Client cli("127.0.0.1", port);
  15326. auto handle = cli.open_stream("GET", "/");
  15327. EXPECT_FALSE(handle.is_valid());
  15328. server_thread.join();
  15329. }
  15330. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15331. TEST_F(OpenStreamTest, Gzip) {
  15332. Client cli("127.0.0.1", port_);
  15333. auto handle = cli.open_stream("GET", "/compressible", {},
  15334. {{"Accept-Encoding", "gzip"}});
  15335. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  15336. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15337. }
  15338. #endif
  15339. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15340. TEST_F(OpenStreamTest, Brotli) {
  15341. Client cli("127.0.0.1", port_);
  15342. auto handle =
  15343. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  15344. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  15345. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15346. }
  15347. #endif
  15348. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15349. TEST_F(OpenStreamTest, Zstd) {
  15350. Client cli("127.0.0.1", port_);
  15351. auto handle = cli.open_stream("GET", "/compressible", {},
  15352. {{"Accept-Encoding", "zstd"}});
  15353. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  15354. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15355. }
  15356. #endif
  15357. #ifdef CPPHTTPLIB_SSL_ENABLED
  15358. class SSLOpenStreamTest : public ::testing::Test {
  15359. protected:
  15360. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  15361. void SetUp() override {
  15362. svr_.Get("/hello", [](const Request &, Response &res) {
  15363. res.set_content("Hello SSL World!", "text/plain");
  15364. });
  15365. svr_.Get("/chunked", [](const Request &, Response &res) {
  15366. res.set_chunked_content_provider("text/plain",
  15367. [](size_t offset, DataSink &sink) {
  15368. if (offset < 15) {
  15369. sink.write("chunk", 5);
  15370. return true;
  15371. }
  15372. sink.done();
  15373. return true;
  15374. });
  15375. });
  15376. svr_.Post("/echo", [](const Request &req, Response &res) {
  15377. res.set_content(req.body, req.get_header_value("Content-Type"));
  15378. });
  15379. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  15380. std::string body = req.body;
  15381. res.set_chunked_content_provider(
  15382. "text/plain", [body](size_t offset, DataSink &sink) {
  15383. if (offset < body.size()) {
  15384. sink.write(body.data() + offset, body.size() - offset);
  15385. }
  15386. sink.done();
  15387. return true;
  15388. });
  15389. });
  15390. port_ = svr_.bind_to_any_port("127.0.0.1");
  15391. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15392. svr_.wait_until_ready();
  15393. }
  15394. void TearDown() override {
  15395. svr_.stop();
  15396. if (thread_.joinable()) thread_.join();
  15397. }
  15398. SSLServer svr_;
  15399. std::thread thread_;
  15400. int port_ = 0;
  15401. };
  15402. TEST_F(SSLOpenStreamTest, Basic) {
  15403. SSLClient cli("127.0.0.1", port_);
  15404. cli.enable_server_certificate_verification(false);
  15405. auto handle = cli.open_stream("GET", "/hello");
  15406. ASSERT_TRUE(handle.is_valid());
  15407. EXPECT_EQ("Hello SSL World!", read_all(handle));
  15408. }
  15409. TEST_F(SSLOpenStreamTest, Chunked) {
  15410. SSLClient cli("127.0.0.1", port_);
  15411. cli.enable_server_certificate_verification(false);
  15412. auto handle = cli.open_stream("GET", "/chunked");
  15413. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15414. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15415. "Transfer-Encoding") == "chunked");
  15416. auto body = read_all(handle);
  15417. EXPECT_EQ("chunkchunkchunk", body);
  15418. }
  15419. TEST_F(SSLOpenStreamTest, Post) {
  15420. SSLClient cli("127.0.0.1", port_);
  15421. cli.enable_server_certificate_verification(false);
  15422. auto handle =
  15423. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  15424. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15425. EXPECT_EQ(200, handle.response->status);
  15426. auto body = read_all(handle);
  15427. EXPECT_EQ("Hello SSL POST", body);
  15428. }
  15429. TEST_F(SSLOpenStreamTest, PostChunked) {
  15430. SSLClient cli("127.0.0.1", port_);
  15431. cli.enable_server_certificate_verification(false);
  15432. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  15433. "Chunked SSL Data", "text/plain");
  15434. ASSERT_TRUE(handle.is_valid());
  15435. EXPECT_EQ(200, handle.response->status);
  15436. auto body = read_all(handle);
  15437. EXPECT_EQ("Chunked SSL Data", body);
  15438. }
  15439. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  15440. // Content-Length is terminated by the server closing the connection. When the
  15441. // SSL peer sends a close_notify after the body, the client must treat it as a
  15442. // clean EOF and return a successful response rather than an error.
  15443. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  15444. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15445. ASSERT_TRUE(svr.is_valid());
  15446. svr.set_keep_alive_max_count(1);
  15447. const std::string expected_body = "Hello from connection-close response!";
  15448. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  15449. res.set_content_provider("text/plain",
  15450. [&](size_t offset, DataSink &sink) -> bool {
  15451. if (offset < expected_body.size()) {
  15452. sink.write(expected_body.data() + offset,
  15453. expected_body.size() - offset);
  15454. }
  15455. sink.done();
  15456. return true;
  15457. });
  15458. });
  15459. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  15460. auto se = detail::scope_exit([&] {
  15461. svr.stop();
  15462. listen_thread.join();
  15463. ASSERT_FALSE(svr.is_running());
  15464. });
  15465. svr.wait_until_ready();
  15466. SSLClient cli(HOST, PORT);
  15467. cli.enable_server_certificate_verification(false);
  15468. auto res = cli.Get("/no-content-length");
  15469. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  15470. EXPECT_EQ(StatusCode::OK_200, res->status);
  15471. EXPECT_EQ(expected_body, res->body);
  15472. }
  15473. #endif // CPPHTTPLIB_SSL_ENABLED
  15474. //==============================================================================
  15475. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  15476. // results for various scenarios.
  15477. //==============================================================================
  15478. TEST(ParityTest, GetVsOpenStream) {
  15479. Server svr;
  15480. const std::string path = "/parity";
  15481. const std::string content = "Parity test content: hello world";
  15482. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15483. res.set_content(content, "text/plain");
  15484. });
  15485. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15486. auto se = detail::scope_exit([&] {
  15487. svr.stop();
  15488. t.join();
  15489. ASSERT_FALSE(svr.is_running());
  15490. });
  15491. svr.wait_until_ready();
  15492. Client cli(HOST, PORT);
  15493. // Non-stream path
  15494. auto r1 = cli.Get(path);
  15495. ASSERT_TRUE(r1);
  15496. EXPECT_EQ(StatusCode::OK_200, r1->status);
  15497. // Stream path
  15498. auto h = cli.open_stream("GET", path);
  15499. ASSERT_TRUE(h.is_valid());
  15500. EXPECT_EQ(r1->body, read_all(h));
  15501. }
  15502. // Helper to compress data with provided compressor type T
  15503. template <typename Compressor>
  15504. static std::string compress_payload_for_parity(const std::string &in) {
  15505. std::string out;
  15506. Compressor compressor;
  15507. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  15508. [&](const char *data, size_t n) {
  15509. out.append(data, n);
  15510. return true;
  15511. });
  15512. EXPECT_TRUE(ok);
  15513. return out;
  15514. }
  15515. // Helper function for compression parity tests
  15516. template <typename Compressor>
  15517. static void test_compression_parity(const std::string &original,
  15518. const std::string &path,
  15519. const std::string &encoding) {
  15520. const std::string compressed =
  15521. compress_payload_for_parity<Compressor>(original);
  15522. Server svr;
  15523. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15524. res.set_content(compressed, "application/octet-stream");
  15525. res.set_header("Content-Encoding", encoding);
  15526. });
  15527. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  15528. auto se = detail::scope_exit([&] {
  15529. svr.stop();
  15530. t.join();
  15531. ASSERT_FALSE(svr.is_running());
  15532. });
  15533. svr.wait_until_ready();
  15534. Client cli(HOST, PORT);
  15535. // Non-streaming
  15536. {
  15537. auto res = cli.Get(path);
  15538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15539. EXPECT_EQ(StatusCode::OK_200, res->status);
  15540. EXPECT_EQ(original, res->body);
  15541. }
  15542. // Streaming
  15543. {
  15544. auto h = cli.open_stream("GET", path);
  15545. ASSERT_TRUE(h.is_valid());
  15546. EXPECT_EQ(original, read_all(h));
  15547. }
  15548. }
  15549. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15550. TEST(ParityTest, Gzip) {
  15551. test_compression_parity<detail::gzip_compressor>(
  15552. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  15553. }
  15554. #endif
  15555. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15556. TEST(ParityTest, Brotli) {
  15557. test_compression_parity<detail::brotli_compressor>(
  15558. "Hello, brotli parity test payload", "/parity-br", "br");
  15559. }
  15560. #endif
  15561. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15562. TEST(ParityTest, Zstd) {
  15563. test_compression_parity<detail::zstd_compressor>(
  15564. "Zstandard parity test payload", "/parity-zstd", "zstd");
  15565. }
  15566. #endif
  15567. //==============================================================================
  15568. // New Stream API Tests
  15569. //==============================================================================
  15570. inline std::string read_body(httplib::stream::Result &result) {
  15571. std::string body;
  15572. while (result.next()) {
  15573. body.append(result.data(), result.size());
  15574. }
  15575. return body;
  15576. }
  15577. TEST(ClientConnectionTest, Basic) {
  15578. httplib::ClientConnection conn;
  15579. EXPECT_FALSE(conn.is_open());
  15580. conn.sock = 1;
  15581. EXPECT_TRUE(conn.is_open());
  15582. httplib::ClientConnection conn2(std::move(conn));
  15583. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  15584. conn2.sock = INVALID_SOCKET;
  15585. }
  15586. // Unified test server for all stream::* tests
  15587. class StreamApiTest : public ::testing::Test {
  15588. protected:
  15589. void SetUp() override {
  15590. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15591. res.set_content("Hello World!", "text/plain");
  15592. });
  15593. svr_.Get("/echo-params",
  15594. [](const httplib::Request &req, httplib::Response &res) {
  15595. std::string r;
  15596. for (const auto &p : req.params) {
  15597. if (!r.empty()) r += "&";
  15598. r += p.first + "=" + p.second;
  15599. }
  15600. res.set_content(r, "text/plain");
  15601. });
  15602. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15603. res.set_content(req.body, req.get_header_value("Content-Type"));
  15604. });
  15605. svr_.Post("/echo-headers",
  15606. [](const httplib::Request &req, httplib::Response &res) {
  15607. std::string r;
  15608. for (const auto &h : req.headers)
  15609. r += h.first + ": " + h.second + "\n";
  15610. res.set_content(r, "text/plain");
  15611. });
  15612. svr_.Post("/echo-params",
  15613. [](const httplib::Request &req, httplib::Response &res) {
  15614. std::string r = "params:";
  15615. for (const auto &p : req.params)
  15616. r += p.first + "=" + p.second + ";";
  15617. res.set_content(r + " body:" + req.body, "text/plain");
  15618. });
  15619. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  15620. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  15621. });
  15622. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15623. res.set_content("PUT:" + req.body, "text/plain");
  15624. });
  15625. svr_.Patch("/echo",
  15626. [](const httplib::Request &req, httplib::Response &res) {
  15627. res.set_content("PATCH:" + req.body, "text/plain");
  15628. });
  15629. svr_.Delete(
  15630. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  15631. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  15632. "text/plain");
  15633. });
  15634. svr_.Get("/head-test",
  15635. [](const httplib::Request &, httplib::Response &res) {
  15636. res.set_content("body for HEAD", "text/plain");
  15637. });
  15638. svr_.Options("/options",
  15639. [](const httplib::Request &, httplib::Response &res) {
  15640. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  15641. });
  15642. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  15643. svr_.wait_until_ready();
  15644. }
  15645. void TearDown() override {
  15646. svr_.stop();
  15647. if (thread_.joinable()) thread_.join();
  15648. }
  15649. httplib::Server svr_;
  15650. std::thread thread_;
  15651. };
  15652. // stream::Get tests
  15653. TEST_F(StreamApiTest, GetBasic) {
  15654. httplib::Client cli(HOST, PORT);
  15655. auto result = httplib::stream::Get(cli, "/hello");
  15656. ASSERT_TRUE(result.is_valid());
  15657. EXPECT_EQ(200, result.status());
  15658. EXPECT_EQ("Hello World!", read_body(result));
  15659. }
  15660. TEST_F(StreamApiTest, GetWithParams) {
  15661. httplib::Client cli(HOST, PORT);
  15662. httplib::Params params{{"foo", "bar"}};
  15663. auto result = httplib::stream::Get(cli, "/echo-params", params);
  15664. ASSERT_TRUE(result.is_valid());
  15665. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  15666. }
  15667. TEST_F(StreamApiTest, GetConnectionError) {
  15668. httplib::Client cli(HOST, 9999);
  15669. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  15670. }
  15671. TEST_F(StreamApiTest, Get404) {
  15672. httplib::Client cli(HOST, PORT);
  15673. auto result = httplib::stream::Get(cli, "/nonexistent");
  15674. EXPECT_TRUE(result.is_valid());
  15675. EXPECT_EQ(404, result.status());
  15676. }
  15677. // stream::Post tests
  15678. TEST_F(StreamApiTest, PostBasic) {
  15679. httplib::Client cli(HOST, PORT);
  15680. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  15681. "application/json");
  15682. ASSERT_TRUE(result.is_valid());
  15683. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  15684. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  15685. }
  15686. TEST_F(StreamApiTest, PostWithHeaders) {
  15687. httplib::Client cli(HOST, PORT);
  15688. httplib::Headers headers{{"X-Custom", "value"}};
  15689. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  15690. "text/plain");
  15691. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  15692. }
  15693. TEST_F(StreamApiTest, PostWithParams) {
  15694. httplib::Client cli(HOST, PORT);
  15695. httplib::Params params{{"k", "v"}};
  15696. auto result =
  15697. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  15698. auto body = read_body(result);
  15699. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  15700. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  15701. }
  15702. TEST_F(StreamApiTest, PostLarge) {
  15703. httplib::Client cli(HOST, PORT);
  15704. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  15705. size_t total = 0;
  15706. while (result.next()) {
  15707. total += result.size();
  15708. }
  15709. EXPECT_EQ(100u * 1024u, total);
  15710. }
  15711. // stream::Put/Patch tests
  15712. TEST_F(StreamApiTest, PutAndPatch) {
  15713. httplib::Client cli(HOST, PORT);
  15714. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  15715. EXPECT_EQ("PUT:test", read_body(put));
  15716. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  15717. EXPECT_EQ("PATCH:test", read_body(patch));
  15718. }
  15719. // stream::Delete tests
  15720. TEST_F(StreamApiTest, Delete) {
  15721. httplib::Client cli(HOST, PORT);
  15722. auto del1 = httplib::stream::Delete(cli, "/resource");
  15723. EXPECT_EQ("Deleted", read_body(del1));
  15724. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  15725. EXPECT_EQ("Deleted:data", read_body(del2));
  15726. }
  15727. // stream::Head/Options tests
  15728. TEST_F(StreamApiTest, HeadAndOptions) {
  15729. httplib::Client cli(HOST, PORT);
  15730. auto head = httplib::stream::Head(cli, "/head-test");
  15731. EXPECT_TRUE(head.is_valid());
  15732. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  15733. auto opts = httplib::stream::Options(cli, "/options");
  15734. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  15735. }
  15736. // SSL stream::* tests
  15737. #ifdef CPPHTTPLIB_SSL_ENABLED
  15738. class SSLStreamApiTest : public ::testing::Test {
  15739. protected:
  15740. void SetUp() override {
  15741. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15742. res.set_content("Hello SSL!", "text/plain");
  15743. });
  15744. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15745. res.set_content(req.body, "text/plain");
  15746. });
  15747. port_ = svr_.bind_to_any_port("127.0.0.1");
  15748. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15749. svr_.wait_until_ready();
  15750. }
  15751. void TearDown() override {
  15752. svr_.stop();
  15753. if (thread_.joinable()) thread_.join();
  15754. }
  15755. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  15756. std::thread thread_;
  15757. int port_ = 0;
  15758. };
  15759. TEST_F(SSLStreamApiTest, GetAndPost) {
  15760. httplib::SSLClient cli("127.0.0.1", port_);
  15761. cli.enable_server_certificate_verification(false);
  15762. auto get = httplib::stream::Get(cli, "/hello");
  15763. EXPECT_EQ("Hello SSL!", read_body(get));
  15764. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  15765. EXPECT_EQ("test", read_body(post));
  15766. }
  15767. #endif
  15768. // Tests for Error::Timeout and Error::ConnectionClosed error types
  15769. // These errors are set in SocketStream/SSLSocketStream and propagated through
  15770. // BodyReader
  15771. TEST(ErrorHandlingTest, StreamReadTimeout) {
  15772. // Test that read timeout during streaming is detected
  15773. // Use a large content-length response where server delays mid-stream
  15774. Server svr;
  15775. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15776. // Send a large response with delay in the middle
  15777. res.set_content_provider(
  15778. 1000, // content_length
  15779. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  15780. if (offset < 100) {
  15781. // Send first 100 bytes immediately
  15782. std::string data(100, 'A');
  15783. sink.write(data.c_str(), data.size());
  15784. return true;
  15785. }
  15786. // Then delay longer than client timeout
  15787. std::this_thread::sleep_for(std::chrono::seconds(3));
  15788. std::string data(900, 'B');
  15789. sink.write(data.c_str(), data.size());
  15790. return true;
  15791. });
  15792. });
  15793. auto port = 8091;
  15794. std::thread t([&]() { svr.listen("localhost", port); });
  15795. svr.wait_until_ready();
  15796. Client cli("localhost", port);
  15797. cli.set_read_timeout(1, 0); // 1 second timeout
  15798. auto handle = cli.open_stream("GET", "/slow-stream");
  15799. ASSERT_TRUE(handle.is_valid());
  15800. char buf[256];
  15801. ssize_t total = 0;
  15802. ssize_t n;
  15803. bool got_error = false;
  15804. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15805. total += n;
  15806. }
  15807. if (n < 0) {
  15808. got_error = true;
  15809. // Should be timeout or read error
  15810. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15811. handle.get_read_error() == Error::Read)
  15812. << "Actual error: " << to_string(handle.get_read_error());
  15813. }
  15814. // Either we got an error, or we got less data than expected
  15815. EXPECT_TRUE(got_error || total < 1000)
  15816. << "Expected timeout but got all " << total << " bytes";
  15817. svr.stop();
  15818. t.join();
  15819. }
  15820. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  15821. // Test connection closed detection via BodyReader
  15822. Server svr;
  15823. std::atomic<bool> close_now{false};
  15824. svr.Get("/will-close", [&](const Request &, Response &res) {
  15825. res.set_content_provider(
  15826. 10000, // Large content_length that we won't fully send
  15827. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15828. if (offset < 100) {
  15829. std::string data(100, 'X');
  15830. sink.write(data.c_str(), data.size());
  15831. return true;
  15832. }
  15833. // Wait for signal then abort
  15834. while (!close_now) {
  15835. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15836. }
  15837. return false; // Abort - server will close connection
  15838. });
  15839. });
  15840. auto port = 8092;
  15841. std::thread t([&]() { svr.listen("localhost", port); });
  15842. svr.wait_until_ready();
  15843. Client cli("localhost", port);
  15844. auto handle = cli.open_stream("GET", "/will-close");
  15845. ASSERT_TRUE(handle.is_valid());
  15846. char buf[256];
  15847. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15848. EXPECT_GT(n, 0) << "First read should succeed";
  15849. // Signal server to close
  15850. close_now = true;
  15851. // Keep reading until error or EOF
  15852. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15853. // Keep reading
  15854. }
  15855. // Should get an error since content_length wasn't satisfied
  15856. if (n < 0) {
  15857. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15858. handle.get_read_error() == Error::Read)
  15859. << "Actual error: " << to_string(handle.get_read_error());
  15860. }
  15861. svr.stop();
  15862. t.join();
  15863. }
  15864. #ifdef CPPHTTPLIB_SSL_ENABLED
  15865. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  15866. // Test that read timeout during SSL streaming is detected
  15867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15868. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15869. res.set_content_provider(
  15870. 1000, "text/plain",
  15871. [](size_t offset, size_t /*length*/, DataSink &sink) {
  15872. if (offset < 100) {
  15873. std::string data(100, 'A');
  15874. sink.write(data.c_str(), data.size());
  15875. return true;
  15876. }
  15877. std::this_thread::sleep_for(std::chrono::seconds(3));
  15878. std::string data(900, 'B');
  15879. sink.write(data.c_str(), data.size());
  15880. return true;
  15881. });
  15882. });
  15883. auto port = 8093;
  15884. std::thread t([&]() { svr.listen("localhost", port); });
  15885. svr.wait_until_ready();
  15886. SSLClient cli("localhost", port);
  15887. cli.enable_server_certificate_verification(false);
  15888. cli.set_read_timeout(1, 0); // 1 second timeout
  15889. auto handle = cli.open_stream("GET", "/slow-stream");
  15890. ASSERT_TRUE(handle.is_valid());
  15891. char buf[256];
  15892. ssize_t total = 0;
  15893. ssize_t n;
  15894. bool got_error = false;
  15895. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15896. total += n;
  15897. }
  15898. if (n < 0) {
  15899. got_error = true;
  15900. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15901. handle.get_read_error() == Error::Read)
  15902. << "Actual error: " << to_string(handle.get_read_error());
  15903. }
  15904. EXPECT_TRUE(got_error || total < 1000)
  15905. << "Expected timeout but got all " << total << " bytes";
  15906. svr.stop();
  15907. t.join();
  15908. }
  15909. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  15910. // Test SSL connection closed detection
  15911. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15912. std::atomic<bool> close_now{false};
  15913. svr.Get("/will-close", [&](const Request &, Response &res) {
  15914. res.set_content_provider(
  15915. 10000, "text/plain",
  15916. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15917. if (offset < 100) {
  15918. std::string data(100, 'X');
  15919. sink.write(data.c_str(), data.size());
  15920. return true;
  15921. }
  15922. while (!close_now) {
  15923. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15924. }
  15925. return false;
  15926. });
  15927. });
  15928. auto port = 8094;
  15929. std::thread t([&]() { svr.listen("localhost", port); });
  15930. svr.wait_until_ready();
  15931. SSLClient cli("localhost", port);
  15932. cli.enable_server_certificate_verification(false);
  15933. auto handle = cli.open_stream("GET", "/will-close");
  15934. ASSERT_TRUE(handle.is_valid());
  15935. char buf[256];
  15936. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15937. EXPECT_GT(n, 0);
  15938. // Signal server to close
  15939. close_now = true;
  15940. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15941. // Keep reading
  15942. }
  15943. if (n < 0) {
  15944. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15945. handle.get_read_error() == Error::Read)
  15946. << "Actual error: " << to_string(handle.get_read_error());
  15947. }
  15948. svr.stop();
  15949. t.join();
  15950. }
  15951. #endif
  15952. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  15953. using namespace httplib;
  15954. // Create a test file
  15955. const char *fname = "etag_testfile.txt";
  15956. const char *content = "etag-content";
  15957. {
  15958. std::ofstream ofs(fname);
  15959. ofs << content;
  15960. ASSERT_TRUE(ofs.good());
  15961. }
  15962. Server svr;
  15963. svr.set_mount_point("/static", ".");
  15964. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15965. svr.wait_until_ready();
  15966. Client cli(HOST, PORT);
  15967. // First request: should get 200 with ETag header
  15968. auto res1 = cli.Get("/static/etag_testfile.txt");
  15969. ASSERT_TRUE(res1);
  15970. ASSERT_EQ(200, res1->status);
  15971. ASSERT_TRUE(res1->has_header("ETag"));
  15972. std::string etag = res1->get_header_value("ETag");
  15973. EXPECT_FALSE(etag.empty());
  15974. // Verify ETag format: W/"hex-hex"
  15975. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  15976. EXPECT_EQ('W', etag[0]);
  15977. EXPECT_EQ('/', etag[1]);
  15978. EXPECT_EQ('"', etag[2]);
  15979. EXPECT_EQ('"', etag.back());
  15980. // Exact match: expect 304 Not Modified
  15981. Headers h2 = {{"If-None-Match", etag}};
  15982. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  15983. ASSERT_TRUE(res2);
  15984. EXPECT_EQ(304, res2->status);
  15985. // Wildcard match: expect 304 Not Modified
  15986. Headers h3 = {{"If-None-Match", "*"}};
  15987. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  15988. ASSERT_TRUE(res3);
  15989. EXPECT_EQ(304, res3->status);
  15990. // Non-matching ETag: expect 200
  15991. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  15992. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  15993. ASSERT_TRUE(res4);
  15994. EXPECT_EQ(200, res4->status);
  15995. // Multiple ETags with one matching: expect 304
  15996. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  15997. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  15998. ASSERT_TRUE(res5);
  15999. EXPECT_EQ(304, res5->status);
  16000. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  16001. // that equivalent to the single comma-separated list above, so the match on
  16002. // the second line must still be found.
  16003. Headers h6;
  16004. h6.emplace("If-None-Match", "W/\"other\"");
  16005. h6.emplace("If-None-Match", etag);
  16006. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  16007. ASSERT_TRUE(res6);
  16008. EXPECT_EQ(304, res6->status);
  16009. svr.stop();
  16010. t.join();
  16011. std::remove(fname);
  16012. }
  16013. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  16014. using namespace httplib;
  16015. Server svr;
  16016. svr.set_mount_point("/static", ".");
  16017. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16018. svr.wait_until_ready();
  16019. Client cli(HOST, PORT);
  16020. // Send If-None-Match: * to a non-existent file
  16021. Headers h = {{"If-None-Match", "*"}};
  16022. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  16023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16024. EXPECT_EQ(404, res->status);
  16025. svr.stop();
  16026. t.join();
  16027. }
  16028. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  16029. using namespace httplib;
  16030. // Create a test file
  16031. const char *fname = "etag_boundary_testfile.txt";
  16032. const char *content = "boundary-test";
  16033. {
  16034. std::ofstream ofs(fname);
  16035. ofs << content;
  16036. ASSERT_TRUE(ofs.good());
  16037. }
  16038. Server svr;
  16039. svr.set_mount_point("/static", ".");
  16040. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16041. svr.wait_until_ready();
  16042. Client cli(HOST, PORT);
  16043. // Get the actual ETag
  16044. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  16045. ASSERT_TRUE(res1);
  16046. ASSERT_EQ(200, res1->status);
  16047. ASSERT_TRUE(res1->has_header("ETag"));
  16048. std::string etag = res1->get_header_value("ETag");
  16049. // Test 1: Very long ETag value (longer than actual ETag)
  16050. // Should NOT match and return 200 (not trigger out-of-bounds read)
  16051. Headers h1 = {{"If-None-Match", "W/"
  16052. "\"very-long-etag-value-that-is-much-longer-"
  16053. "than-the-actual-etag-value\""}};
  16054. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  16055. ASSERT_TRUE(res2);
  16056. EXPECT_EQ(200, res2->status); // Should not match
  16057. // Test 2: Long string followed by wildcard
  16058. // Should match on "*" and return 304 (without out-of-bounds read on the long
  16059. // string)
  16060. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  16061. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  16062. ASSERT_TRUE(res3);
  16063. EXPECT_EQ(304, res3->status); // Should match on "*"
  16064. // Test 3: Wildcard followed by long string
  16065. // Should match on "*" immediately and return 304
  16066. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  16067. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  16068. ASSERT_TRUE(res4);
  16069. EXPECT_EQ(304, res4->status); // Should match on "*"
  16070. // Test 4: Multiple long non-matching values
  16071. // Should NOT match and return 200 (test that all comparisons are safe)
  16072. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  16073. "W/\"second-long-non-matching-value\", "
  16074. "W/\"third-long-non-matching-value\""}};
  16075. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  16076. ASSERT_TRUE(res5);
  16077. EXPECT_EQ(200, res5->status); // Should not match
  16078. // Test 5: Single character that is not "*" (edge case)
  16079. Headers h5 = {{"If-None-Match", "X"}};
  16080. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  16081. ASSERT_TRUE(res6);
  16082. EXPECT_EQ(200, res6->status); // Should not match
  16083. svr.stop();
  16084. t.join();
  16085. std::remove(fname);
  16086. }
  16087. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  16088. using namespace httplib;
  16089. // Create a test file
  16090. const char *fname = "ims_testfile.txt";
  16091. const char *content = "if-modified-since-test";
  16092. {
  16093. std::ofstream ofs(fname);
  16094. ofs << content;
  16095. ASSERT_TRUE(ofs.good());
  16096. }
  16097. Server svr;
  16098. svr.set_mount_point("/static", ".");
  16099. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16100. svr.wait_until_ready();
  16101. Client cli(HOST, PORT);
  16102. // First request: should get 200 with Last-Modified header
  16103. auto res1 = cli.Get("/static/ims_testfile.txt");
  16104. ASSERT_TRUE(res1);
  16105. ASSERT_EQ(200, res1->status);
  16106. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16107. std::string last_modified = res1->get_header_value("Last-Modified");
  16108. EXPECT_FALSE(last_modified.empty());
  16109. // If-Modified-Since with same time: expect 304
  16110. Headers h2 = {{"If-Modified-Since", last_modified}};
  16111. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  16112. ASSERT_TRUE(res2);
  16113. EXPECT_EQ(304, res2->status);
  16114. // If-Modified-Since with future time: expect 304
  16115. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16116. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  16117. ASSERT_TRUE(res3);
  16118. EXPECT_EQ(304, res3->status);
  16119. // If-Modified-Since with past time: expect 200
  16120. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16121. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  16122. ASSERT_TRUE(res4);
  16123. EXPECT_EQ(200, res4->status);
  16124. // If-None-Match takes precedence over If-Modified-Since
  16125. // (send matching ETag with old If-Modified-Since -> should still be 304)
  16126. ASSERT_TRUE(res1->has_header("ETag"));
  16127. std::string etag = res1->get_header_value("ETag");
  16128. Headers h5 = {{"If-None-Match", etag},
  16129. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16130. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  16131. ASSERT_TRUE(res5);
  16132. EXPECT_EQ(304, res5->status);
  16133. svr.stop();
  16134. t.join();
  16135. std::remove(fname);
  16136. }
  16137. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  16138. using namespace httplib;
  16139. Server svr;
  16140. // Endpoint that returns compressible content
  16141. svr.Get("/compressible", [](const Request &, Response &res) {
  16142. // Return a large enough body to trigger compression
  16143. std::string body(1000, 'a');
  16144. res.set_content(body, "text/plain");
  16145. });
  16146. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16147. svr.wait_until_ready();
  16148. Client cli(HOST, PORT);
  16149. // Request with gzip support: should get Vary header when compressed
  16150. cli.set_compress(true);
  16151. auto res1 = cli.Get("/compressible");
  16152. ASSERT_TRUE(res1);
  16153. EXPECT_EQ(200, res1->status);
  16154. // If Content-Encoding is set, Vary should also be set
  16155. if (res1->has_header("Content-Encoding")) {
  16156. EXPECT_TRUE(res1->has_header("Vary"));
  16157. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  16158. }
  16159. // Request without Accept-Encoding header: should not have compression
  16160. Headers h_no_compress;
  16161. auto res2 = cli.Get("/compressible", h_no_compress);
  16162. ASSERT_TRUE(res2);
  16163. EXPECT_EQ(200, res2->status);
  16164. // Verify Vary header is present when compression is applied
  16165. // (the exact behavior depends on server configuration)
  16166. svr.stop();
  16167. t.join();
  16168. }
  16169. TEST(ETagTest, IfRangeWithETag) {
  16170. using namespace httplib;
  16171. // Create a test file with known content
  16172. const char *fname = "if_range_testfile.txt";
  16173. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  16174. {
  16175. std::ofstream ofs(fname);
  16176. ofs << content;
  16177. ASSERT_TRUE(ofs.good());
  16178. }
  16179. Server svr;
  16180. svr.set_mount_point("/static", ".");
  16181. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16182. svr.wait_until_ready();
  16183. Client cli(HOST, PORT);
  16184. // First request: get ETag
  16185. auto res1 = cli.Get("/static/if_range_testfile.txt");
  16186. ASSERT_TRUE(res1);
  16187. ASSERT_EQ(200, res1->status);
  16188. ASSERT_TRUE(res1->has_header("ETag"));
  16189. std::string etag = res1->get_header_value("ETag");
  16190. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  16191. // Since our server generates weak ETags (W/"..."), If-Range with our
  16192. // ETag should NOT result in partial content - it should return full content.
  16193. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  16194. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  16195. ASSERT_TRUE(res2);
  16196. // Weak ETag in If-Range -> full content (200), not partial (206)
  16197. EXPECT_EQ(200, res2->status);
  16198. EXPECT_EQ(content, res2->body);
  16199. EXPECT_FALSE(res2->has_header("Content-Range"));
  16200. // Range request with non-matching If-Range (ETag): should get 200 (full
  16201. // content)
  16202. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  16203. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  16204. ASSERT_TRUE(res3);
  16205. EXPECT_EQ(200, res3->status);
  16206. EXPECT_EQ(content, res3->body);
  16207. EXPECT_FALSE(res3->has_header("Content-Range"));
  16208. // Range request with strong ETag (hypothetical - our server doesn't generate
  16209. // strong ETags, but if client sends a strong ETag that doesn't match, it
  16210. // should return full content)
  16211. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  16212. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  16213. ASSERT_TRUE(res4);
  16214. EXPECT_EQ(200, res4->status);
  16215. EXPECT_EQ(content, res4->body);
  16216. EXPECT_FALSE(res4->has_header("Content-Range"));
  16217. svr.stop();
  16218. t.join();
  16219. std::remove(fname);
  16220. }
  16221. TEST(ETagTest, IfRangeWithDate) {
  16222. using namespace httplib;
  16223. // Create a test file
  16224. const char *fname = "if_range_date_testfile.txt";
  16225. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  16226. {
  16227. std::ofstream ofs(fname);
  16228. ofs << content;
  16229. ASSERT_TRUE(ofs.good());
  16230. }
  16231. Server svr;
  16232. svr.set_mount_point("/static", ".");
  16233. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16234. svr.wait_until_ready();
  16235. Client cli(HOST, PORT);
  16236. // First request: get Last-Modified
  16237. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  16238. ASSERT_TRUE(res1);
  16239. ASSERT_EQ(200, res1->status);
  16240. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16241. std::string last_modified = res1->get_header_value("Last-Modified");
  16242. // Range request with matching If-Range (date): should get 206
  16243. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  16244. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  16245. ASSERT_TRUE(res2);
  16246. EXPECT_EQ(206, res2->status);
  16247. EXPECT_EQ("FGHIJ", res2->body);
  16248. // Range request with old If-Range date: should get 200 (full content)
  16249. Headers h3 = {{"Range", "bytes=5-9"},
  16250. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16251. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  16252. ASSERT_TRUE(res3);
  16253. EXPECT_EQ(200, res3->status);
  16254. EXPECT_EQ(content, res3->body);
  16255. // Range request with future If-Range date: should get 206
  16256. Headers h4 = {{"Range", "bytes=0-4"},
  16257. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16258. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  16259. ASSERT_TRUE(res4);
  16260. EXPECT_EQ(206, res4->status);
  16261. EXPECT_EQ("ABCDE", res4->body);
  16262. svr.stop();
  16263. t.join();
  16264. std::remove(fname);
  16265. }
  16266. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  16267. using namespace httplib;
  16268. const char *fname = "etag_malformed.txt";
  16269. const char *content = "malformed-etag";
  16270. {
  16271. std::ofstream ofs(fname);
  16272. ofs << content;
  16273. ASSERT_TRUE(ofs.good());
  16274. }
  16275. Server svr;
  16276. svr.set_mount_point("/static", ".");
  16277. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16278. svr.wait_until_ready();
  16279. Client cli(HOST, PORT);
  16280. // baseline: should get 200 and an ETag
  16281. auto res1 = cli.Get("/static/etag_malformed.txt");
  16282. ASSERT_TRUE(res1);
  16283. ASSERT_EQ(200, res1->status);
  16284. ASSERT_TRUE(res1->has_header("ETag"));
  16285. // Malformed ETag value (missing quotes) should be treated as non-matching
  16286. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  16287. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  16288. ASSERT_TRUE(res_bad);
  16289. EXPECT_EQ(200, res_bad->status);
  16290. // Whitespace-only header value should be considered invalid / non-matching
  16291. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  16292. "Host: localhost\r\n"
  16293. "If-None-Match: \r\n"
  16294. "Connection: close\r\n"
  16295. "\r\n";
  16296. std::string out;
  16297. ASSERT_TRUE(send_request(5, raw_req, &out));
  16298. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16299. svr.stop();
  16300. t.join();
  16301. std::remove(fname);
  16302. }
  16303. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  16304. using namespace httplib;
  16305. const char *fname = "ims_invalid_format.txt";
  16306. const char *content = "ims-bad-format";
  16307. {
  16308. std::ofstream ofs(fname);
  16309. ofs << content;
  16310. ASSERT_TRUE(ofs.good());
  16311. }
  16312. Server svr;
  16313. svr.set_mount_point("/static", ".");
  16314. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16315. svr.wait_until_ready();
  16316. Client cli(HOST, PORT);
  16317. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  16318. ASSERT_TRUE(res1);
  16319. ASSERT_EQ(200, res1->status);
  16320. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16321. // If-Modified-Since with invalid format should not result in 304
  16322. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  16323. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  16324. ASSERT_TRUE(res_bad);
  16325. EXPECT_EQ(200, res_bad->status);
  16326. // If-Range with invalid date format should be treated as mismatch -> full
  16327. // content (200)
  16328. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  16329. {"If-Range", "invalid-date"}};
  16330. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  16331. ASSERT_TRUE(res_ifrange);
  16332. EXPECT_EQ(200, res_ifrange->status);
  16333. svr.stop();
  16334. t.join();
  16335. std::remove(fname);
  16336. }
  16337. TEST(ETagTest, IfRangeWithMalformedETag) {
  16338. using namespace httplib;
  16339. const char *fname = "ifrange_malformed.txt";
  16340. const std::string content = "0123456789";
  16341. {
  16342. std::ofstream ofs(fname);
  16343. ofs << content;
  16344. ASSERT_TRUE(ofs.good());
  16345. }
  16346. Server svr;
  16347. svr.set_mount_point("/static", ".");
  16348. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16349. svr.wait_until_ready();
  16350. Client cli(HOST, PORT);
  16351. // First request: get ETag
  16352. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  16353. ASSERT_TRUE(res1);
  16354. ASSERT_EQ(200, res1->status);
  16355. ASSERT_TRUE(res1->has_header("ETag"));
  16356. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  16357. // full content (200)
  16358. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  16359. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  16360. ASSERT_TRUE(res2);
  16361. EXPECT_EQ(200, res2->status);
  16362. EXPECT_EQ(content, res2->body);
  16363. svr.stop();
  16364. t.join();
  16365. std::remove(fname);
  16366. }
  16367. TEST(ETagTest, ExtremeLargeDateValues) {
  16368. using namespace httplib;
  16369. const char *fname = "ims_extreme_date.txt";
  16370. const char *content = "ims-extreme-date";
  16371. {
  16372. std::ofstream ofs(fname);
  16373. ofs << content;
  16374. ASSERT_TRUE(ofs.good());
  16375. }
  16376. Server svr;
  16377. svr.set_mount_point("/static", ".");
  16378. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16379. svr.wait_until_ready();
  16380. Client cli(HOST, PORT);
  16381. auto res1 = cli.Get(std::string("/static/") + fname);
  16382. ASSERT_TRUE(res1);
  16383. ASSERT_EQ(200, res1->status);
  16384. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16385. // Extremely large year that may overflow date parsing routines.
  16386. Headers h_large_date = {
  16387. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16388. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  16389. ASSERT_TRUE(res_bad);
  16390. // Expect server to treat this as invalid/mismatch and return full content
  16391. EXPECT_EQ(200, res_bad->status);
  16392. // If-Range with extremely large date should be treated as mismatch -> full
  16393. // content (200)
  16394. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  16395. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16396. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  16397. ASSERT_TRUE(res_ifrange);
  16398. EXPECT_EQ(200, res_ifrange->status);
  16399. svr.stop();
  16400. t.join();
  16401. std::remove(fname);
  16402. }
  16403. TEST(ETagTest, NegativeFileModificationTime) {
  16404. using namespace httplib;
  16405. const char *fname = "ims_negative_mtime.txt";
  16406. const std::string content = "negative-mtime";
  16407. {
  16408. std::ofstream ofs(fname);
  16409. ofs << content;
  16410. ASSERT_TRUE(ofs.good());
  16411. }
  16412. // Try to set file mtime to a negative value. This may fail on some
  16413. // platforms/filesystems; if it fails, the test will still verify server
  16414. // behaves safely by performing a regular conditional request.
  16415. #if defined(__APPLE__) || defined(__linux__)
  16416. bool set_negative = false;
  16417. do {
  16418. struct timeval times[2];
  16419. // access time: now
  16420. times[0].tv_sec = time(nullptr);
  16421. times[0].tv_usec = 0;
  16422. // modification time: negative (e.g., -1)
  16423. times[1].tv_sec = -1;
  16424. times[1].tv_usec = 0;
  16425. if (utimes(fname, times) == 0) { set_negative = true; }
  16426. } while (0);
  16427. #else
  16428. bool set_negative = false;
  16429. #endif
  16430. Server svr;
  16431. svr.set_mount_point("/static", ".");
  16432. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16433. svr.wait_until_ready();
  16434. Client cli(HOST, PORT);
  16435. auto res1 = cli.Get(std::string("/static/") + fname);
  16436. ASSERT_TRUE(res1);
  16437. ASSERT_EQ(200, res1->status);
  16438. bool has_last_modified = res1->has_header("Last-Modified");
  16439. std::string last_modified;
  16440. if (has_last_modified) {
  16441. last_modified = res1->get_header_value("Last-Modified");
  16442. }
  16443. if (set_negative) {
  16444. // If we successfully set a negative mtime, ensure server returns a
  16445. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  16446. // with an old date and ensure server handles it without crash.
  16447. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  16448. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  16449. ASSERT_TRUE(res2);
  16450. // Behavior may vary; at minimum ensure server responds (200 or 304).
  16451. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  16452. } else {
  16453. // Could not set negative mtime on this platform; fall back to verifying
  16454. // that normal invalid/malformed dates are treated safely (non-304).
  16455. Headers h_bad_date = {
  16456. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16457. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  16458. ASSERT_TRUE(res_bad);
  16459. EXPECT_EQ(200, res_bad->status);
  16460. }
  16461. svr.stop();
  16462. t.join();
  16463. std::remove(fname);
  16464. }
  16465. //==============================================================================
  16466. // SSE Parsing Tests
  16467. //==============================================================================
  16468. class SSEParsingTest : public ::testing::Test {
  16469. protected:
  16470. // Test helper that mimics SSE parsing behavior
  16471. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  16472. int &retry_ms) {
  16473. // Blank line signals end of event
  16474. if (line.empty() || line == "\r") { return true; }
  16475. // Lines starting with ':' are comments (ignored)
  16476. if (!line.empty() && line[0] == ':') { return false; }
  16477. // Find the colon separator
  16478. auto colon_pos = line.find(':');
  16479. if (colon_pos == std::string::npos) {
  16480. // Line with no colon is treated as field name with empty value
  16481. return false;
  16482. }
  16483. std::string field = line.substr(0, colon_pos);
  16484. std::string value;
  16485. // Value starts after colon, skip optional single space
  16486. if (colon_pos + 1 < line.size()) {
  16487. size_t value_start = colon_pos + 1;
  16488. if (line[value_start] == ' ') { value_start++; }
  16489. value = line.substr(value_start);
  16490. // Remove trailing \r if present
  16491. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  16492. }
  16493. // Handle known fields
  16494. if (field == "event") {
  16495. msg.event = value;
  16496. } else if (field == "data") {
  16497. // Multiple data lines are concatenated with newlines
  16498. if (!msg.data.empty()) { msg.data += "\n"; }
  16499. msg.data += value;
  16500. } else if (field == "id") {
  16501. // Empty id is valid (clears the last event ID)
  16502. msg.id = value;
  16503. } else if (field == "retry") {
  16504. // Parse retry interval in milliseconds
  16505. {
  16506. int v = 0;
  16507. auto res =
  16508. detail::from_chars(value.data(), value.data() + value.size(), v);
  16509. if (res.ec == std::errc{}) { retry_ms = v; }
  16510. }
  16511. }
  16512. // Unknown fields are ignored per SSE spec
  16513. return false;
  16514. }
  16515. };
  16516. // Test: Single-line data
  16517. TEST_F(SSEParsingTest, SingleLineData) {
  16518. sse::SSEMessage msg;
  16519. int retry_ms = 3000;
  16520. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  16521. EXPECT_EQ(msg.data, "hello");
  16522. EXPECT_EQ(msg.event, "message");
  16523. // Blank line ends event
  16524. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16525. }
  16526. // Test: Multi-line data
  16527. TEST_F(SSEParsingTest, MultiLineData) {
  16528. sse::SSEMessage msg;
  16529. int retry_ms = 3000;
  16530. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  16531. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  16532. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  16533. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  16534. }
  16535. // Test: Custom event types
  16536. TEST_F(SSEParsingTest, CustomEventType) {
  16537. sse::SSEMessage msg;
  16538. int retry_ms = 3000;
  16539. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  16540. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  16541. EXPECT_EQ(msg.event, "update");
  16542. EXPECT_EQ(msg.data, "payload");
  16543. }
  16544. // Test: Event ID handling
  16545. TEST_F(SSEParsingTest, EventIdHandling) {
  16546. sse::SSEMessage msg;
  16547. int retry_ms = 3000;
  16548. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  16549. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  16550. EXPECT_EQ(msg.id, "12345");
  16551. }
  16552. // Test: Empty event ID (clears last event ID)
  16553. TEST_F(SSEParsingTest, EmptyEventId) {
  16554. sse::SSEMessage msg;
  16555. msg.id = "previous";
  16556. int retry_ms = 3000;
  16557. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  16558. EXPECT_EQ(msg.id, "");
  16559. }
  16560. // Test: Retry field parsing
  16561. TEST_F(SSEParsingTest, RetryFieldParsing) {
  16562. sse::SSEMessage msg;
  16563. int retry_ms = 3000;
  16564. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  16565. EXPECT_EQ(retry_ms, 5000);
  16566. }
  16567. // Test: Invalid retry value
  16568. TEST_F(SSEParsingTest, InvalidRetryValue) {
  16569. sse::SSEMessage msg;
  16570. int retry_ms = 3000;
  16571. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  16572. EXPECT_EQ(retry_ms, 3000); // Unchanged
  16573. }
  16574. // Test: Comments (lines starting with :)
  16575. TEST_F(SSEParsingTest, CommentsIgnored) {
  16576. sse::SSEMessage msg;
  16577. int retry_ms = 3000;
  16578. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  16579. EXPECT_EQ(msg.data, "");
  16580. EXPECT_EQ(msg.event, "message");
  16581. }
  16582. // Test: Colon in value
  16583. TEST_F(SSEParsingTest, ColonInValue) {
  16584. sse::SSEMessage msg;
  16585. int retry_ms = 3000;
  16586. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  16587. EXPECT_EQ(msg.data, "hello:world:test");
  16588. }
  16589. // Test: Line with no colon (field name only)
  16590. TEST_F(SSEParsingTest, FieldNameOnly) {
  16591. sse::SSEMessage msg;
  16592. int retry_ms = 3000;
  16593. // According to SSE spec, this is treated as field name with empty value
  16594. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  16595. // Since we don't recognize "data" without colon, data should be empty
  16596. EXPECT_EQ(msg.data, "");
  16597. }
  16598. // Test: Trailing \r handling
  16599. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  16600. sse::SSEMessage msg;
  16601. int retry_ms = 3000;
  16602. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  16603. EXPECT_EQ(msg.data, "hello");
  16604. }
  16605. // Test: Unknown fields ignored
  16606. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  16607. sse::SSEMessage msg;
  16608. int retry_ms = 3000;
  16609. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  16610. EXPECT_EQ(msg.data, "");
  16611. EXPECT_EQ(msg.event, "message");
  16612. }
  16613. // Test: Space after colon is optional
  16614. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  16615. sse::SSEMessage msg1, msg2;
  16616. int retry_ms = 3000;
  16617. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  16618. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  16619. EXPECT_EQ(msg1.data, "hello");
  16620. EXPECT_EQ(msg2.data, "hello");
  16621. }
  16622. // Test: SSEMessage clear
  16623. TEST_F(SSEParsingTest, MessageClear) {
  16624. sse::SSEMessage msg;
  16625. msg.event = "custom";
  16626. msg.data = "some data";
  16627. msg.id = "123";
  16628. msg.clear();
  16629. EXPECT_EQ(msg.event, "message");
  16630. EXPECT_EQ(msg.data, "");
  16631. EXPECT_EQ(msg.id, "");
  16632. }
  16633. // Test: Complete event parsing
  16634. TEST_F(SSEParsingTest, CompleteEventParsing) {
  16635. sse::SSEMessage msg;
  16636. int retry_ms = 3000;
  16637. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  16638. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  16639. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  16640. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  16641. // Blank line ends event
  16642. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16643. EXPECT_EQ(msg.event, "notification");
  16644. EXPECT_EQ(msg.id, "evt-42");
  16645. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  16646. EXPECT_EQ(retry_ms, 1000);
  16647. }
  16648. //==============================================================================
  16649. // Integration Tests with Server
  16650. //==============================================================================
  16651. class SSEIntegrationTest : public ::testing::Test {
  16652. protected:
  16653. void SetUp() override {
  16654. stop_server_.store(false);
  16655. events_.clear();
  16656. server_ = httplib::detail::make_unique<Server>();
  16657. setup_server();
  16658. start_server();
  16659. }
  16660. void TearDown() override {
  16661. stop_server_.store(true);
  16662. event_cv_.notify_all();
  16663. server_->stop();
  16664. if (server_thread_.joinable()) { server_thread_.join(); }
  16665. }
  16666. void setup_server() {
  16667. // Simple SSE endpoint
  16668. server_->Get("/events", [this](const Request &req, Response &res) {
  16669. auto last_id = req.get_header_value("Last-Event-ID");
  16670. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  16671. res.set_chunked_content_provider(
  16672. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  16673. std::unique_lock<std::mutex> lock(event_mutex_);
  16674. if (event_cv_.wait_for(
  16675. lock, std::chrono::milliseconds(200), [this] {
  16676. return !events_.empty() || stop_server_.load();
  16677. })) {
  16678. if (stop_server_.load()) { return false; }
  16679. if (!events_.empty()) {
  16680. std::string event = events_.front();
  16681. events_.erase(events_.begin());
  16682. sink.write(event.data(), event.size());
  16683. return true;
  16684. }
  16685. }
  16686. return !stop_server_.load();
  16687. });
  16688. });
  16689. // Endpoint that returns error
  16690. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  16691. res.status = 500;
  16692. res.set_content("Internal Server Error", "text/plain");
  16693. });
  16694. // Endpoint for custom event types
  16695. server_->Get("/custom-events", [](const Request &, Response &res) {
  16696. res.set_chunked_content_provider(
  16697. "text/event-stream", [](size_t offset, DataSink &sink) {
  16698. if (offset == 0) {
  16699. std::string event = "event: update\ndata: updated\n\n"
  16700. "event: delete\ndata: deleted\n\n";
  16701. sink.write(event.data(), event.size());
  16702. }
  16703. return false; // End stream after sending
  16704. });
  16705. });
  16706. }
  16707. void start_server() {
  16708. port_ = server_->bind_to_any_port(HOST);
  16709. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16710. // Wait for server to start
  16711. while (!server_->is_running()) {
  16712. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16713. }
  16714. }
  16715. int get_port() const { return port_; }
  16716. void send_event(const std::string &event) {
  16717. std::lock_guard<std::mutex> lock(event_mutex_);
  16718. events_.push_back(event);
  16719. event_cv_.notify_all();
  16720. }
  16721. std::unique_ptr<Server> server_;
  16722. std::thread server_thread_;
  16723. std::mutex event_mutex_;
  16724. std::condition_variable event_cv_;
  16725. std::vector<std::string> events_;
  16726. std::atomic<bool> stop_server_{false};
  16727. std::string last_received_event_id_;
  16728. int port_ = 0;
  16729. };
  16730. // Test: Successful connection and on_open callback
  16731. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  16732. // Add a simple endpoint that sends one event and closes
  16733. server_->Get("/simple-event", [](const Request &, Response &res) {
  16734. res.set_chunked_content_provider(
  16735. "text/event-stream", [](size_t offset, DataSink &sink) {
  16736. if (offset == 0) {
  16737. std::string event = "data: hello\n\n";
  16738. sink.write(event.data(), event.size());
  16739. }
  16740. return false; // Close stream after sending
  16741. });
  16742. });
  16743. Client client("localhost", get_port());
  16744. sse::SSEClient sse(client, "/simple-event");
  16745. std::atomic<bool> open_called{false};
  16746. std::atomic<bool> message_received{false};
  16747. sse.on_open([&open_called]() { open_called.store(true); });
  16748. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  16749. if (msg.data == "hello") { message_received.store(true); }
  16750. });
  16751. sse.set_reconnect_interval(100);
  16752. sse.set_max_reconnect_attempts(1);
  16753. // Start async
  16754. sse.start_async();
  16755. // Wait for message to be processed
  16756. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16757. sse.stop();
  16758. EXPECT_TRUE(open_called.load());
  16759. EXPECT_TRUE(message_received.load());
  16760. }
  16761. // Test: on_message callback
  16762. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  16763. // Endpoint that sends multiple events then closes
  16764. server_->Get("/multi-event", [](const Request &, Response &res) {
  16765. res.set_chunked_content_provider(
  16766. "text/event-stream", [](size_t offset, DataSink &sink) {
  16767. if (offset == 0) {
  16768. std::string events = "data: message1\n\ndata: message2\n\n";
  16769. sink.write(events.data(), events.size());
  16770. }
  16771. return false;
  16772. });
  16773. });
  16774. Client client("localhost", get_port());
  16775. sse::SSEClient sse(client, "/multi-event");
  16776. std::vector<std::string> received_messages;
  16777. std::mutex messages_mutex;
  16778. sse.on_message([&](const sse::SSEMessage &msg) {
  16779. std::lock_guard<std::mutex> lock(messages_mutex);
  16780. received_messages.push_back(msg.data);
  16781. });
  16782. sse.set_reconnect_interval(100);
  16783. sse.set_max_reconnect_attempts(1);
  16784. sse.start_async();
  16785. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16786. sse.stop();
  16787. std::lock_guard<std::mutex> lock(messages_mutex);
  16788. EXPECT_GE(received_messages.size(), 2u);
  16789. if (received_messages.size() >= 2) {
  16790. EXPECT_EQ(received_messages[0], "message1");
  16791. EXPECT_EQ(received_messages[1], "message2");
  16792. }
  16793. }
  16794. // Test: on_event for specific types
  16795. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  16796. Client client("localhost", get_port());
  16797. sse::SSEClient sse(client, "/custom-events");
  16798. std::atomic<bool> update_received{false};
  16799. std::atomic<bool> delete_received{false};
  16800. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  16801. if (msg.data == "updated") { update_received.store(true); }
  16802. });
  16803. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  16804. if (msg.data == "deleted") { delete_received.store(true); }
  16805. });
  16806. sse.set_max_reconnect_attempts(1);
  16807. sse.start_async();
  16808. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  16809. sse.stop();
  16810. EXPECT_TRUE(update_received.load());
  16811. EXPECT_TRUE(delete_received.load());
  16812. }
  16813. // Test: on_error callback on connection failure
  16814. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  16815. // Connect to a non-existent port
  16816. Client client("localhost", 59999);
  16817. sse::SSEClient sse(client, "/events");
  16818. std::atomic<bool> error_called{false};
  16819. Error received_error = Error::Success;
  16820. sse.on_error([&](Error err) {
  16821. error_called.store(true);
  16822. received_error = err;
  16823. });
  16824. sse.set_reconnect_interval(50);
  16825. sse.set_max_reconnect_attempts(1);
  16826. sse.start_async();
  16827. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16828. sse.stop();
  16829. EXPECT_TRUE(error_called.load());
  16830. EXPECT_NE(received_error, Error::Success);
  16831. }
  16832. // Test: Last-Event-ID header sent on reconnect
  16833. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  16834. // Endpoint that sends event with ID
  16835. server_->Get("/event-with-id", [](const Request &, Response &res) {
  16836. res.set_chunked_content_provider(
  16837. "text/event-stream", [](size_t offset, DataSink &sink) {
  16838. if (offset == 0) {
  16839. std::string event = "id: evt-123\ndata: test\n\n";
  16840. sink.write(event.data(), event.size());
  16841. }
  16842. return false;
  16843. });
  16844. });
  16845. Client client("localhost", get_port());
  16846. sse::SSEClient sse(client, "/event-with-id");
  16847. std::atomic<bool> id_received{false};
  16848. sse.on_message([&](const sse::SSEMessage &msg) {
  16849. if (!msg.id.empty()) { id_received.store(true); }
  16850. });
  16851. sse.set_reconnect_interval(100);
  16852. sse.set_max_reconnect_attempts(1);
  16853. sse.start_async();
  16854. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16855. sse.stop();
  16856. EXPECT_TRUE(id_received.load());
  16857. EXPECT_EQ(sse.last_event_id(), "evt-123");
  16858. }
  16859. // Test: Manual stop
  16860. TEST_F(SSEIntegrationTest, ManualStop) {
  16861. // Endpoint that sends one event and stays open briefly
  16862. std::atomic<bool> handler_running{true};
  16863. server_->Get("/stay-open", [&handler_running](const Request &,
  16864. Response &res) {
  16865. res.set_chunked_content_provider(
  16866. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  16867. if (offset == 0) {
  16868. std::string event = "data: connected\n\n";
  16869. sink.write(event.data(), event.size());
  16870. }
  16871. // Keep connection open while handler_running is true
  16872. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  16873. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16874. }
  16875. return false;
  16876. });
  16877. });
  16878. Client client("localhost", get_port());
  16879. sse::SSEClient sse(client, "/stay-open");
  16880. std::atomic<bool> connected{false};
  16881. sse.on_open([&connected]() { connected.store(true); });
  16882. sse.set_reconnect_interval(100);
  16883. sse.set_max_reconnect_attempts(1);
  16884. sse.start_async();
  16885. // Wait for connection to establish
  16886. for (int i = 0; i < 20 && !connected.load(); ++i) {
  16887. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16888. }
  16889. EXPECT_TRUE(connected.load());
  16890. EXPECT_TRUE(sse.is_connected());
  16891. // Signal handler to stop
  16892. handler_running.store(false);
  16893. // Stop SSE client
  16894. sse.stop();
  16895. EXPECT_FALSE(sse.is_connected());
  16896. }
  16897. // Test: SSEClient with custom headers
  16898. TEST_F(SSEIntegrationTest, CustomHeaders) {
  16899. // Setup a server endpoint that checks for custom header
  16900. std::atomic<bool> header_received{false};
  16901. server_->Get("/header-check", [&](const Request &req, Response &res) {
  16902. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  16903. header_received.store(true);
  16904. }
  16905. res.set_chunked_content_provider("text/event-stream",
  16906. [](size_t, DataSink &) { return false; });
  16907. });
  16908. Client client("localhost", get_port());
  16909. Headers headers = {{"X-Custom-Header", "custom-value"}};
  16910. sse::SSEClient sse(client, "/header-check", headers);
  16911. sse.set_max_reconnect_attempts(1);
  16912. sse.start_async();
  16913. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16914. sse.stop();
  16915. EXPECT_TRUE(header_received.load());
  16916. }
  16917. // Test: Reconnect interval configuration
  16918. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  16919. Client client("localhost", get_port());
  16920. sse::SSEClient sse(client, "/events");
  16921. auto &result = sse.set_reconnect_interval(500);
  16922. // Builder pattern should return reference to self
  16923. EXPECT_EQ(&result, &sse);
  16924. }
  16925. // Test: Max reconnect attempts
  16926. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  16927. // Connect to non-existent port to force reconnects
  16928. Client client("localhost", 59998);
  16929. sse::SSEClient sse(client, "/events");
  16930. std::atomic<int> error_count{0};
  16931. sse.on_error([&](Error) { error_count.fetch_add(1); });
  16932. sse.set_reconnect_interval(50);
  16933. sse.set_max_reconnect_attempts(2);
  16934. auto start = std::chrono::steady_clock::now();
  16935. sse.start(); // Blocking call
  16936. auto end = std::chrono::steady_clock::now();
  16937. // Should have stopped after 2 failed attempts
  16938. EXPECT_GE(error_count.load(), 2);
  16939. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  16940. auto duration =
  16941. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  16942. #ifdef _WIN32
  16943. // Windows is much slower for socket connection failures
  16944. EXPECT_LT(duration.count(), 7000);
  16945. #else
  16946. EXPECT_LT(duration.count(), 1000);
  16947. #endif
  16948. }
  16949. // Test: Multi-line data in integration
  16950. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  16951. // Endpoint with multi-line data
  16952. server_->Get("/multiline-data", [](const Request &, Response &res) {
  16953. res.set_chunked_content_provider(
  16954. "text/event-stream", [](size_t offset, DataSink &sink) {
  16955. if (offset == 0) {
  16956. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  16957. sink.write(event.data(), event.size());
  16958. }
  16959. return false;
  16960. });
  16961. });
  16962. Client client("localhost", get_port());
  16963. sse::SSEClient sse(client, "/multiline-data");
  16964. std::string received_data;
  16965. std::mutex data_mutex;
  16966. sse.on_message([&](const sse::SSEMessage &msg) {
  16967. std::lock_guard<std::mutex> lock(data_mutex);
  16968. received_data = msg.data;
  16969. });
  16970. sse.set_reconnect_interval(100);
  16971. sse.set_max_reconnect_attempts(1);
  16972. sse.start_async();
  16973. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16974. sse.stop();
  16975. std::lock_guard<std::mutex> lock(data_mutex);
  16976. EXPECT_EQ(received_data, "line1\nline2\nline3");
  16977. }
  16978. // Test: Auto-reconnect after server disconnection
  16979. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  16980. std::atomic<int> connection_count{0};
  16981. std::atomic<int> message_count{0};
  16982. // Endpoint that sends one event and closes, forcing reconnect
  16983. server_->Get("/reconnect-test",
  16984. [&connection_count](const Request &, Response &res) {
  16985. connection_count.fetch_add(1);
  16986. res.set_chunked_content_provider(
  16987. "text/event-stream", [](size_t offset, DataSink &sink) {
  16988. if (offset == 0) {
  16989. std::string event = "data: hello\n\n";
  16990. sink.write(event.data(), event.size());
  16991. }
  16992. return false; // Close connection after sending
  16993. });
  16994. });
  16995. Client client("localhost", get_port());
  16996. sse::SSEClient sse(client, "/reconnect-test");
  16997. sse.on_message([&message_count](const sse::SSEMessage &) {
  16998. message_count.fetch_add(1);
  16999. });
  17000. sse.set_reconnect_interval(100);
  17001. sse.set_max_reconnect_attempts(3);
  17002. sse.start_async();
  17003. // Wait long enough for multiple reconnects
  17004. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17005. sse.stop();
  17006. // Should have connected multiple times (initial + reconnects)
  17007. EXPECT_GE(connection_count.load(), 2);
  17008. // Should have received messages from multiple connections
  17009. EXPECT_GE(message_count.load(), 2);
  17010. }
  17011. // Test: Last-Event-ID sent on reconnect
  17012. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  17013. std::atomic<int> connection_count{0};
  17014. std::vector<std::string> received_last_event_ids;
  17015. std::mutex id_mutex;
  17016. // Endpoint that checks Last-Event-ID header and sends event with ID
  17017. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  17018. int conn = connection_count.fetch_add(1);
  17019. // Capture the Last-Event-ID header from each connection
  17020. {
  17021. std::lock_guard<std::mutex> lock(id_mutex);
  17022. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  17023. }
  17024. res.set_chunked_content_provider(
  17025. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  17026. if (offset == 0) {
  17027. std::string event =
  17028. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  17029. sink.write(event.data(), event.size());
  17030. }
  17031. return false;
  17032. });
  17033. });
  17034. Client client("localhost", get_port());
  17035. sse::SSEClient sse(client, "/reconnect-with-id");
  17036. sse.set_reconnect_interval(100);
  17037. sse.set_max_reconnect_attempts(3);
  17038. sse.start_async();
  17039. // Wait for at least 2 connections
  17040. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17041. sse.stop();
  17042. // Verify behavior
  17043. std::lock_guard<std::mutex> lock(id_mutex);
  17044. EXPECT_GE(received_last_event_ids.size(), 2u);
  17045. // First connection should have no Last-Event-ID
  17046. if (!received_last_event_ids.empty()) {
  17047. EXPECT_EQ(received_last_event_ids[0], "");
  17048. }
  17049. // Second connection should have Last-Event-ID from first connection
  17050. if (received_last_event_ids.size() >= 2) {
  17051. EXPECT_EQ(received_last_event_ids[1], "event-0");
  17052. }
  17053. }
  17054. // Test: set_headers updates headers used on reconnect
  17055. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  17056. std::vector<std::string> received_tokens;
  17057. std::mutex token_mutex;
  17058. // Endpoint that captures Authorization header
  17059. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  17060. {
  17061. std::lock_guard<std::mutex> lock(token_mutex);
  17062. received_tokens.push_back(req.get_header_value("Authorization"));
  17063. }
  17064. res.set_chunked_content_provider(
  17065. "text/event-stream", [](size_t offset, DataSink &sink) {
  17066. if (offset == 0) {
  17067. std::string event = "data: hello\n\n";
  17068. sink.write(event.data(), event.size());
  17069. }
  17070. return false; // Close connection to trigger reconnect
  17071. });
  17072. });
  17073. Client client("localhost", get_port());
  17074. Headers headers = {{"Authorization", "Bearer old-token"}};
  17075. sse::SSEClient sse(client, "/auth-check", headers);
  17076. // Update headers on each successful connection
  17077. sse.on_open(
  17078. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  17079. sse.set_reconnect_interval(100);
  17080. sse.set_max_reconnect_attempts(3);
  17081. sse.start_async();
  17082. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17083. sse.stop();
  17084. std::lock_guard<std::mutex> lock(token_mutex);
  17085. ASSERT_GE(received_tokens.size(), 2u);
  17086. // First connection uses original header
  17087. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  17088. // Second connection uses updated header from set_headers
  17089. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  17090. }
  17091. // Test: 401 allows reconnection (so on_error can refresh headers)
  17092. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  17093. std::atomic<int> connection_count{0};
  17094. // Endpoint: returns 401 on first attempt, 200 on second
  17095. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  17096. int conn = connection_count.fetch_add(1);
  17097. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  17098. res.status = StatusCode::Unauthorized_401;
  17099. res.set_content("Unauthorized", "text/plain");
  17100. return;
  17101. }
  17102. res.set_chunked_content_provider(
  17103. "text/event-stream", [](size_t offset, DataSink &sink) {
  17104. if (offset == 0) {
  17105. std::string event = "data: authenticated\n\n";
  17106. sink.write(event.data(), event.size());
  17107. }
  17108. return false;
  17109. });
  17110. });
  17111. Client client("localhost", get_port());
  17112. Headers headers = {{"Authorization", "Bearer expired"}};
  17113. sse::SSEClient sse(client, "/auth-retry", headers);
  17114. std::atomic<bool> message_received{false};
  17115. // Refresh token on error
  17116. sse.on_error(
  17117. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  17118. sse.on_message([&](const sse::SSEMessage &msg) {
  17119. if (msg.data == "authenticated") { message_received.store(true); }
  17120. });
  17121. sse.set_reconnect_interval(100);
  17122. sse.set_max_reconnect_attempts(3);
  17123. sse.start_async();
  17124. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17125. sse.stop();
  17126. // Should have reconnected after 401 and succeeded with new token
  17127. EXPECT_GE(connection_count.load(), 2);
  17128. EXPECT_TRUE(message_received.load());
  17129. }
  17130. TEST(Issue2318Test, EmptyHostString) {
  17131. {
  17132. httplib::Client cli_empty("", PORT);
  17133. auto res = cli_empty.Get("/");
  17134. ASSERT_FALSE(res);
  17135. EXPECT_EQ(httplib::Error::Connection, res.error());
  17136. }
  17137. {
  17138. httplib::Client cli(" ", PORT);
  17139. auto res = cli.Get("/");
  17140. ASSERT_FALSE(res);
  17141. EXPECT_EQ(httplib::Error::Connection, res.error());
  17142. }
  17143. }
  17144. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17145. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  17146. Server svr;
  17147. // Set a small payload limit (1KB)
  17148. svr.set_payload_max_length(1024);
  17149. svr.Post("/test", [&](const Request &req, Response &res) {
  17150. res.set_content("Body size: " + std::to_string(req.body.size()),
  17151. "text/plain");
  17152. });
  17153. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17154. auto se = detail::scope_exit([&] {
  17155. svr.stop();
  17156. listen_thread.join();
  17157. });
  17158. svr.wait_until_ready();
  17159. // Create data that compresses well but exceeds limit when decompressed
  17160. // 8KB of repeated null bytes compresses to a very small size
  17161. std::string original_data(8 * 1024, '\0');
  17162. // Compress the data using gzip
  17163. std::string compressed_data;
  17164. detail::gzip_compressor compressor;
  17165. compressor.compress(original_data.data(), original_data.size(), true,
  17166. [&](const char *data, size_t size) {
  17167. compressed_data.append(data, size);
  17168. return true;
  17169. });
  17170. // Verify compression worked (compressed should be much smaller)
  17171. ASSERT_LT(compressed_data.size(), original_data.size());
  17172. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  17173. // Send compressed data with Content-Encoding: gzip
  17174. Client cli(HOST, PORT);
  17175. Headers headers = {{"Content-Encoding", "gzip"}};
  17176. auto res =
  17177. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  17178. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  17179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17180. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  17181. }
  17182. #endif
  17183. // ============================================================================
  17184. // OpenSSL-Specific Tests
  17185. // ============================================================================
  17186. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17187. X509 *readCertificate(const std::string &strFileName) {
  17188. std::ifstream inStream(strFileName);
  17189. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  17190. std::istreambuf_iterator<char>());
  17191. if (strCertPEM.empty()) return (nullptr);
  17192. BIO *pbCert = BIO_new(BIO_s_mem());
  17193. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  17194. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  17195. BIO_free(pbCert);
  17196. return (pCert);
  17197. }
  17198. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  17199. std::ifstream inStream(strFileName);
  17200. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  17201. std::istreambuf_iterator<char>());
  17202. if (strPrivateKeyPEM.empty()) return (nullptr);
  17203. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  17204. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  17205. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  17206. BIO_free(pbPrivKey);
  17207. return (pPrivateKey);
  17208. }
  17209. TEST(BindServerTest, UpdateCerts) {
  17210. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17211. int port = svr.bind_to_any_port("0.0.0.0");
  17212. ASSERT_TRUE(svr.is_valid());
  17213. ASSERT_TRUE(port > 0);
  17214. X509 *cert = readCertificate(SERVER_CERT_FILE);
  17215. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  17216. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  17217. ASSERT_TRUE(cert != nullptr);
  17218. ASSERT_TRUE(ca_cert != nullptr);
  17219. ASSERT_TRUE(key != nullptr);
  17220. X509_STORE *cert_store = X509_STORE_new();
  17221. X509_STORE_add_cert(cert_store, ca_cert);
  17222. // svr.update_certs(cert, key, cert_store); // deprecated
  17223. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  17224. CLIENT_CA_CERT_FILE);
  17225. ASSERT_TRUE(svr.is_valid());
  17226. svr.stop();
  17227. X509_STORE_free(cert_store);
  17228. X509_free(cert);
  17229. X509_free(ca_cert);
  17230. EVP_PKEY_free(key);
  17231. }
  17232. // Test that update_certs() updates client CA list correctly
  17233. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  17234. // Start with file-based constructor
  17235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17236. ASSERT_TRUE(svr.is_valid());
  17237. // Initially no client CA list should be set
  17238. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17239. ASSERT_TRUE(ssl_ctx != nullptr);
  17240. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  17241. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  17242. EXPECT_EQ(0, count_before);
  17243. // Now update with client CA (PEM string)
  17244. std::string cert_pem, key_pem, ca_pem;
  17245. read_file(SERVER_CERT_FILE, cert_pem);
  17246. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  17247. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  17248. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  17249. ASSERT_TRUE(svr.is_valid());
  17250. // Now client CA list should be set
  17251. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  17252. ASSERT_TRUE(ca_list_after != nullptr);
  17253. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  17254. }
  17255. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  17256. // Test that the file-path SSLServer constructor properly sets the client CA
  17257. // list that is sent to clients during the TLS handshake (CertificateRequest)
  17258. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17259. ASSERT_TRUE(svr.is_valid());
  17260. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17261. ASSERT_TRUE(ssl_ctx != nullptr);
  17262. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  17263. ASSERT_TRUE(ca_list != nullptr);
  17264. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  17265. }
  17266. #endif
  17267. // ============================================================================
  17268. // MbedTLS-Specific Tests
  17269. // ============================================================================
  17270. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  17271. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  17272. using namespace httplib::tls;
  17273. // Track if callback was invoked
  17274. bool callback_invoked = false;
  17275. // The callback receives void* ctx which is actually MbedTlsContext*
  17276. // We can access the mbedtls_ssl_config via the context
  17277. auto setup_callback = [&callback_invoked](void *ctx) {
  17278. callback_invoked = true;
  17279. // Cast to MbedTlsContext* to access the ssl config
  17280. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  17281. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  17282. // Use static variables to hold certificate data (simplified for test)
  17283. static mbedtls_x509_crt own_cert;
  17284. static mbedtls_pk_context own_key;
  17285. static mbedtls_x509_crt ca_chain;
  17286. static bool initialized = false;
  17287. if (!initialized) {
  17288. mbedtls_x509_crt_init(&own_cert);
  17289. mbedtls_pk_init(&own_key);
  17290. mbedtls_x509_crt_init(&ca_chain);
  17291. // Load server certificate
  17292. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  17293. return false;
  17294. }
  17295. // Load server private key.
  17296. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  17297. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  17298. #if MBEDTLS_VERSION_MAJOR == 3
  17299. ,
  17300. mbedtls_ctr_drbg_random, nullptr
  17301. #endif
  17302. ) != 0) {
  17303. return false;
  17304. }
  17305. // Load CA chain for client verification
  17306. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  17307. return false;
  17308. }
  17309. initialized = true;
  17310. }
  17311. // Configure the SSL config
  17312. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  17313. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  17314. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17315. // Set minimum TLS version using mbedTLS native API
  17316. #if MBEDTLS_VERSION_MAJOR >= 3
  17317. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17318. #else
  17319. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17320. MBEDTLS_SSL_MINOR_VERSION_3);
  17321. #endif
  17322. return true;
  17323. };
  17324. SSLServer svr(setup_callback);
  17325. ASSERT_TRUE(svr.is_valid());
  17326. ASSERT_TRUE(callback_invoked);
  17327. svr.Get("/test", [&](const Request &req, Response &res) {
  17328. res.set_content("test", "text/plain");
  17329. auto cert = req.peer_cert();
  17330. ASSERT_TRUE(static_cast<bool>(cert));
  17331. auto common_name = cert.subject_cn();
  17332. EXPECT_EQ("Common Name", common_name);
  17333. });
  17334. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17335. auto se = detail::scope_exit([&] {
  17336. svr.stop();
  17337. t.join();
  17338. ASSERT_FALSE(svr.is_running());
  17339. });
  17340. svr.wait_until_ready();
  17341. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  17342. cli.enable_server_certificate_verification(false);
  17343. cli.set_connection_timeout(30);
  17344. auto res = cli.Get("/test");
  17345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17346. ASSERT_EQ(StatusCode::OK_200, res->status);
  17347. }
  17348. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  17349. // context (owning mbedtls_ssl_config) before shutting down a still-open
  17350. // keep-alive SSL session, which reads through that config in
  17351. // mbedtls_ssl_close_notify.
  17352. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  17353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17354. ASSERT_TRUE(svr.is_valid());
  17355. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17356. res.set_content("test", "text/plain");
  17357. });
  17358. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17359. auto se = detail::scope_exit([&] {
  17360. svr.stop();
  17361. t.join();
  17362. ASSERT_FALSE(svr.is_running());
  17363. });
  17364. svr.wait_until_ready();
  17365. {
  17366. SSLClient cli(HOST, PORT);
  17367. cli.enable_server_certificate_verification(false);
  17368. cli.set_keep_alive(true);
  17369. auto res = cli.Get("/test");
  17370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17371. ASSERT_EQ(StatusCode::OK_200, res->status);
  17372. // cli is destructed here with the keep-alive SSL session still open.
  17373. }
  17374. }
  17375. #endif
  17376. // WebSocket Tests
  17377. TEST(WebSocketTest, RSVBitsMustBeZero) {
  17378. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  17379. // defining the meaning of these bits has been negotiated.
  17380. auto make_frame = [](uint8_t first_byte) {
  17381. std::string frame;
  17382. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  17383. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  17384. frame += "Hello";
  17385. return frame;
  17386. };
  17387. // RSV1 set (0x40)
  17388. {
  17389. detail::BufferStream strm;
  17390. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  17391. ws::Opcode opcode;
  17392. std::string payload;
  17393. bool fin;
  17394. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17395. false, 1024));
  17396. }
  17397. // RSV2 set (0x20)
  17398. {
  17399. detail::BufferStream strm;
  17400. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  17401. ws::Opcode opcode;
  17402. std::string payload;
  17403. bool fin;
  17404. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17405. false, 1024));
  17406. }
  17407. // RSV3 set (0x10)
  17408. {
  17409. detail::BufferStream strm;
  17410. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  17411. ws::Opcode opcode;
  17412. std::string payload;
  17413. bool fin;
  17414. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17415. false, 1024));
  17416. }
  17417. // No RSV bits set - should succeed
  17418. {
  17419. detail::BufferStream strm;
  17420. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  17421. ws::Opcode opcode;
  17422. std::string payload;
  17423. bool fin;
  17424. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17425. false, 1024));
  17426. EXPECT_EQ(ws::Opcode::Text, opcode);
  17427. EXPECT_EQ("Hello", payload);
  17428. EXPECT_TRUE(fin);
  17429. }
  17430. }
  17431. TEST(WebSocketTest, ControlFrameValidation) {
  17432. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  17433. // payload length <= 125.
  17434. // Ping with FIN=0 - must be rejected
  17435. {
  17436. detail::BufferStream strm;
  17437. std::string frame;
  17438. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  17439. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17440. strm.write(frame.data(), frame.size());
  17441. ws::Opcode opcode;
  17442. std::string payload;
  17443. bool fin;
  17444. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17445. false, 1024));
  17446. }
  17447. // Close with FIN=0 - must be rejected
  17448. {
  17449. detail::BufferStream strm;
  17450. std::string frame;
  17451. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  17452. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17453. strm.write(frame.data(), frame.size());
  17454. ws::Opcode opcode;
  17455. std::string payload;
  17456. bool fin;
  17457. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17458. false, 1024));
  17459. }
  17460. // Ping with payload_len=126 (extended length) - must be rejected
  17461. {
  17462. detail::BufferStream strm;
  17463. std::string frame;
  17464. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17465. frame += static_cast<char>(126); // payload_len=126 (>125)
  17466. frame += static_cast<char>(0x00); // extended length high byte
  17467. frame += static_cast<char>(126); // extended length low byte
  17468. frame += std::string(126, 'x');
  17469. strm.write(frame.data(), frame.size());
  17470. ws::Opcode opcode;
  17471. std::string payload;
  17472. bool fin;
  17473. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17474. false, 1024));
  17475. }
  17476. // Ping with FIN=1 and payload_len=125 - should succeed
  17477. {
  17478. detail::BufferStream strm;
  17479. std::string frame;
  17480. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17481. frame += static_cast<char>(125); // payload_len=125
  17482. frame += std::string(125, 'x');
  17483. strm.write(frame.data(), frame.size());
  17484. ws::Opcode opcode;
  17485. std::string payload;
  17486. bool fin;
  17487. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17488. false, 1024));
  17489. EXPECT_EQ(ws::Opcode::Ping, opcode);
  17490. EXPECT_EQ(125u, payload.size());
  17491. EXPECT_TRUE(fin);
  17492. }
  17493. }
  17494. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  17495. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  17496. // length MUST be 0.
  17497. // MSB set - must be rejected
  17498. {
  17499. detail::BufferStream strm;
  17500. std::string frame;
  17501. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17502. frame += static_cast<char>(127); // 64-bit extended length
  17503. frame += static_cast<char>(0x80); // MSB set (invalid)
  17504. frame += std::string(7, '\0'); // remaining 7 bytes of length
  17505. strm.write(frame.data(), frame.size());
  17506. ws::Opcode opcode;
  17507. std::string payload;
  17508. bool fin;
  17509. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17510. false, 1024));
  17511. }
  17512. // MSB clear - should pass length parsing (will be rejected by max_len,
  17513. // but that's a different check; use a small length to verify)
  17514. {
  17515. detail::BufferStream strm;
  17516. std::string frame;
  17517. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17518. frame += static_cast<char>(127); // 64-bit extended length
  17519. frame += std::string(7, '\0'); // high bytes = 0
  17520. frame += static_cast<char>(0x03); // length = 3
  17521. frame += "abc";
  17522. strm.write(frame.data(), frame.size());
  17523. ws::Opcode opcode;
  17524. std::string payload;
  17525. bool fin;
  17526. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17527. false, 1024));
  17528. EXPECT_EQ(ws::Opcode::Text, opcode);
  17529. EXPECT_EQ("abc", payload);
  17530. }
  17531. }
  17532. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  17533. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  17534. // Valid UTF-8
  17535. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  17536. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  17537. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  17538. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  17539. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  17540. // Invalid UTF-8
  17541. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  17542. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  17543. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  17544. EXPECT_FALSE(
  17545. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  17546. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  17547. }
  17548. TEST(WebSocketTest, ConnectAndDisconnect) {
  17549. Server svr;
  17550. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17551. std::string msg;
  17552. while (ws.read(msg)) {}
  17553. });
  17554. auto port = svr.bind_to_any_port(HOST);
  17555. std::thread t([&]() { svr.listen_after_bind(); });
  17556. svr.wait_until_ready();
  17557. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17558. auto res = client.connect();
  17559. ASSERT_TRUE(res);
  17560. EXPECT_EQ(Error::Success, res.error());
  17561. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  17562. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  17563. EXPECT_TRUE(client.is_open());
  17564. client.close();
  17565. EXPECT_FALSE(client.is_open());
  17566. svr.stop();
  17567. t.join();
  17568. }
  17569. TEST(WebSocketTest, ValidURL) {
  17570. ws::WebSocketClient ws1("ws://localhost:8080/path");
  17571. EXPECT_TRUE(ws1.is_valid());
  17572. ws::WebSocketClient ws2("ws://example.com/path");
  17573. EXPECT_TRUE(ws2.is_valid());
  17574. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  17575. EXPECT_TRUE(ws3.is_valid());
  17576. #ifdef CPPHTTPLIB_SSL_ENABLED
  17577. ws::WebSocketClient wss1("wss://example.com/path");
  17578. EXPECT_TRUE(wss1.is_valid());
  17579. ws::WebSocketClient wss2("wss://example.com:443/path");
  17580. EXPECT_TRUE(wss2.is_valid());
  17581. #endif
  17582. }
  17583. TEST(WebSocketTest, InvalidURL) {
  17584. // No scheme
  17585. ws::WebSocketClient ws1("localhost:8080/path");
  17586. EXPECT_FALSE(ws1.is_valid());
  17587. // No path
  17588. ws::WebSocketClient ws2("ws://localhost:8080");
  17589. EXPECT_FALSE(ws2.is_valid());
  17590. // Empty string
  17591. ws::WebSocketClient ws3("");
  17592. EXPECT_FALSE(ws3.is_valid());
  17593. // Missing host
  17594. ws::WebSocketClient ws4("ws://:8080/path");
  17595. EXPECT_FALSE(ws4.is_valid());
  17596. // Port number overflow — should not crash
  17597. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  17598. EXPECT_FALSE(ws5.is_valid());
  17599. // Port out of range
  17600. ws::WebSocketClient ws6("ws://localhost:99999/path");
  17601. EXPECT_FALSE(ws6.is_valid());
  17602. }
  17603. TEST(WebSocketTest, UnsupportedScheme) {
  17604. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17605. ws::WebSocketClient ws1("http://localhost:8080/path");
  17606. EXPECT_FALSE(ws1.is_valid());
  17607. ws::WebSocketClient ws2("https://localhost:8080/path");
  17608. EXPECT_FALSE(ws2.is_valid());
  17609. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  17610. EXPECT_FALSE(ws3.is_valid());
  17611. #else
  17612. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  17613. std::invalid_argument);
  17614. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  17615. std::invalid_argument);
  17616. #endif
  17617. }
  17618. TEST(WebSocketTest, ConnectWhenInvalid) {
  17619. ws::WebSocketClient ws("not a valid url");
  17620. EXPECT_FALSE(ws.is_valid());
  17621. auto res = ws.connect();
  17622. EXPECT_FALSE(res);
  17623. EXPECT_EQ(Error::Connection, res.error());
  17624. EXPECT_EQ(-1, res.status());
  17625. }
  17626. TEST(WebSocketTest, ConnectRefusedReportsError) {
  17627. // Grab a port that is free, then close it again so nothing listens there
  17628. Server svr;
  17629. auto port = svr.bind_to_any_port(HOST);
  17630. svr.stop();
  17631. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17632. auto res = client.connect();
  17633. ASSERT_FALSE(res);
  17634. EXPECT_EQ(Error::Connection, res.error());
  17635. EXPECT_EQ(-1, res.status());
  17636. }
  17637. TEST(WebSocketTest, DefaultPort) {
  17638. ws::WebSocketClient ws1("ws://example.com/path");
  17639. EXPECT_TRUE(ws1.is_valid());
  17640. // ws:// defaults to port 80 (verified by successful parse)
  17641. #ifdef CPPHTTPLIB_SSL_ENABLED
  17642. ws::WebSocketClient ws2("wss://example.com/path");
  17643. EXPECT_TRUE(ws2.is_valid());
  17644. // wss:// defaults to port 443 (verified by successful parse)
  17645. #endif
  17646. }
  17647. TEST(WebSocketTest, IPv6LiteralAddress) {
  17648. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  17649. EXPECT_TRUE(ws1.is_valid());
  17650. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  17651. EXPECT_TRUE(ws2.is_valid());
  17652. }
  17653. TEST(WebSocketTest, ComplexPath) {
  17654. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  17655. EXPECT_TRUE(ws1.is_valid());
  17656. ws::WebSocketClient ws2("ws://localhost:8080/");
  17657. EXPECT_TRUE(ws2.is_valid());
  17658. }
  17659. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  17660. Server svr;
  17661. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17662. std::string msg;
  17663. while (ws.read(msg)) {}
  17664. });
  17665. auto port = svr.bind_to_any_port(HOST);
  17666. std::thread t([&]() { svr.listen_after_bind(); });
  17667. svr.wait_until_ready();
  17668. auto another_host = "example.com";
  17669. auto wrong_ip = "192.0.2.1";
  17670. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17671. client.set_hostname_addr_map({{another_host, wrong_ip}});
  17672. ASSERT_TRUE(client.connect());
  17673. EXPECT_TRUE(client.is_open());
  17674. client.close();
  17675. svr.stop();
  17676. t.join();
  17677. }
  17678. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  17679. Server svr;
  17680. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17681. std::string msg;
  17682. while (ws.read(msg)) {}
  17683. });
  17684. auto port = svr.bind_to_any_port(HOST);
  17685. std::thread t([&]() { svr.listen_after_bind(); });
  17686. svr.wait_until_ready();
  17687. auto wrong_ip = "192.0.2.1";
  17688. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17689. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  17690. client.set_connection_timeout(1);
  17691. client.set_read_timeout(1);
  17692. client.set_write_timeout(1);
  17693. EXPECT_FALSE(client.connect());
  17694. EXPECT_FALSE(client.is_open());
  17695. svr.stop();
  17696. t.join();
  17697. }
  17698. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  17699. // A mapped value that is not an IP literal must be resolved. HOST resolves
  17700. // from the hosts file, so this test needs no external DNS. "target.invalid"
  17701. // (RFC 6761) is only a map key and the Host header value.
  17702. auto host = "target.invalid";
  17703. Server svr;
  17704. std::string received_host;
  17705. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17706. received_host = req.get_header_value("Host");
  17707. std::string msg;
  17708. while (ws.read(msg)) {}
  17709. });
  17710. auto port = svr.bind_to_any_port(HOST);
  17711. std::thread t([&]() { svr.listen_after_bind(); });
  17712. // ASSERT_* below returns from the test body, which would leave t joinable
  17713. // and make ~thread call std::terminate.
  17714. auto se = detail::scope_exit([&] {
  17715. svr.stop();
  17716. if (t.joinable()) { t.join(); }
  17717. });
  17718. svr.wait_until_ready();
  17719. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  17720. std::to_string(port) + "/ws");
  17721. client.set_hostname_addr_map({{host, HOST}});
  17722. ASSERT_TRUE(client.connect());
  17723. EXPECT_TRUE(client.is_open());
  17724. client.close();
  17725. svr.stop();
  17726. t.join();
  17727. // The mapping only redirects the connection; the identity stays host_.
  17728. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  17729. }
  17730. class WebSocketIntegrationTest : public ::testing::Test {
  17731. protected:
  17732. void SetUp() override {
  17733. server_ = httplib::detail::make_unique<Server>();
  17734. setup_server();
  17735. start_server();
  17736. }
  17737. void TearDown() override {
  17738. server_->stop();
  17739. if (server_thread_.joinable()) { server_thread_.join(); }
  17740. }
  17741. void setup_server() {
  17742. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17743. std::string msg;
  17744. ws::ReadResult ret;
  17745. while ((ret = ws.read(msg))) {
  17746. if (ret == ws::Binary) {
  17747. ws.send(msg.data(), msg.size());
  17748. } else {
  17749. ws.send(msg);
  17750. }
  17751. }
  17752. });
  17753. server_->WebSocket("/ws-echo-string",
  17754. [](const Request &, ws::WebSocket &ws) {
  17755. std::string msg;
  17756. while (ws.read(msg)) {
  17757. ws.send("echo: " + msg);
  17758. }
  17759. });
  17760. server_->WebSocket(
  17761. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  17762. // Echo back request metadata
  17763. ws.send("path:" + req.path);
  17764. ws.send("header:" + req.get_header_value("X-Test-Header"));
  17765. std::string msg;
  17766. while (ws.read(msg)) {}
  17767. });
  17768. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  17769. std::string msg;
  17770. ws.read(msg); // wait for a message
  17771. ws.close();
  17772. });
  17773. server_->WebSocket("/ws-close-status",
  17774. [](const Request &, ws::WebSocket &ws) {
  17775. std::string msg;
  17776. ws.read(msg); // wait for a message
  17777. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  17778. });
  17779. server_->WebSocket(
  17780. "/ws-subprotocol",
  17781. [](const Request &, ws::WebSocket &ws) {
  17782. std::string msg;
  17783. while (ws.read(msg)) {
  17784. ws.send(msg);
  17785. }
  17786. },
  17787. [](const std::vector<std::string> &protocols) -> std::string {
  17788. for (const auto &p : protocols) {
  17789. if (p == "graphql-ws") { return p; }
  17790. }
  17791. return "";
  17792. });
  17793. }
  17794. void start_server() {
  17795. port_ = server_->bind_to_any_port(HOST);
  17796. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17797. server_->wait_until_ready();
  17798. }
  17799. std::unique_ptr<Server> server_;
  17800. std::thread server_thread_;
  17801. int port_ = 0;
  17802. };
  17803. TEST_F(WebSocketIntegrationTest, TextEcho) {
  17804. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17805. "/ws-echo");
  17806. ASSERT_TRUE(client.connect());
  17807. ASSERT_TRUE(client.is_open());
  17808. ASSERT_TRUE(client.send("Hello WebSocket"));
  17809. std::string msg;
  17810. EXPECT_EQ(ws::Text, client.read(msg));
  17811. EXPECT_EQ("Hello WebSocket", msg);
  17812. client.close();
  17813. }
  17814. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  17815. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17816. "/ws-echo");
  17817. ASSERT_TRUE(client.connect());
  17818. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  17819. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  17820. std::string msg;
  17821. EXPECT_EQ(ws::Binary, client.read(msg));
  17822. EXPECT_EQ(binary_data, msg);
  17823. client.close();
  17824. }
  17825. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  17826. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17827. "/ws-echo");
  17828. ASSERT_TRUE(client.connect());
  17829. for (int i = 0; i < 10; i++) {
  17830. auto text = "message " + std::to_string(i);
  17831. ASSERT_TRUE(client.send(text));
  17832. std::string msg;
  17833. ASSERT_TRUE(client.read(msg));
  17834. EXPECT_EQ(text, msg);
  17835. }
  17836. client.close();
  17837. }
  17838. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  17839. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17840. "/ws-close");
  17841. ASSERT_TRUE(client.connect());
  17842. // Send a message to trigger the server to close
  17843. ASSERT_TRUE(client.send("trigger close"));
  17844. // The server will close, so read should return false
  17845. std::string msg;
  17846. EXPECT_FALSE(client.read(msg));
  17847. EXPECT_FALSE(client.is_open());
  17848. }
  17849. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  17850. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17851. "/ws-echo");
  17852. ASSERT_TRUE(client.connect());
  17853. // 128KB message
  17854. std::string large_data(128 * 1024, 'X');
  17855. ASSERT_TRUE(client.send(large_data));
  17856. std::string msg;
  17857. ASSERT_TRUE(client.read(msg));
  17858. EXPECT_EQ(large_data, msg);
  17859. client.close();
  17860. }
  17861. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  17862. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17863. "/ws-echo");
  17864. ASSERT_TRUE(client.connect());
  17865. const int num_threads = 4;
  17866. std::vector<std::thread> threads;
  17867. std::atomic<int> send_count{0};
  17868. for (int t = 0; t < num_threads; t++) {
  17869. threads.emplace_back([&client, &send_count, t]() {
  17870. for (int i = 0; i < 5; i++) {
  17871. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  17872. if (client.send(text)) { send_count++; }
  17873. }
  17874. });
  17875. }
  17876. for (auto &th : threads) {
  17877. th.join();
  17878. }
  17879. int received = 0;
  17880. std::string msg;
  17881. while (received < send_count.load()) {
  17882. if (!client.read(msg)) { break; }
  17883. received++;
  17884. }
  17885. EXPECT_EQ(send_count.load(), received);
  17886. client.close();
  17887. }
  17888. TEST_F(WebSocketIntegrationTest, ReadString) {
  17889. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17890. "/ws-echo-string");
  17891. ASSERT_TRUE(client.connect());
  17892. ASSERT_TRUE(client.send("hello"));
  17893. std::string msg;
  17894. ASSERT_TRUE(client.read(msg));
  17895. EXPECT_EQ("echo: hello", msg);
  17896. ASSERT_TRUE(client.send("world"));
  17897. ASSERT_TRUE(client.read(msg));
  17898. EXPECT_EQ("echo: world", msg);
  17899. client.close();
  17900. }
  17901. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  17902. Headers headers = {{"X-Test-Header", "test-value"}};
  17903. ws::WebSocketClient client(
  17904. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  17905. ASSERT_TRUE(client.connect());
  17906. std::string msg;
  17907. ASSERT_TRUE(client.read(msg));
  17908. EXPECT_EQ("path:/ws-request-info", msg);
  17909. ASSERT_TRUE(client.read(msg));
  17910. EXPECT_EQ("header:test-value", msg);
  17911. client.close();
  17912. }
  17913. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  17914. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17915. "/ws-echo");
  17916. client.set_read_timeout(1, 0); // 1 second
  17917. ASSERT_TRUE(client.connect());
  17918. // Don't send anything — server echo handler waits for a message,
  17919. // so read() should time out and return false.
  17920. std::string msg;
  17921. EXPECT_FALSE(client.read(msg));
  17922. }
  17923. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  17924. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17925. "/ws-echo");
  17926. client.set_read_timeout(5, 0);
  17927. ASSERT_TRUE(client.connect());
  17928. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17929. // The server should reject it and close the connection.
  17930. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  17931. client.send(oversized);
  17932. // The server's read() should have failed due to payload limit,
  17933. // so our read() should return false (connection closed).
  17934. std::string msg;
  17935. EXPECT_FALSE(client.read(msg));
  17936. }
  17937. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  17938. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17939. "/ws-echo");
  17940. client.set_read_timeout(10, 0);
  17941. ASSERT_TRUE(client.connect());
  17942. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17943. // This should succeed.
  17944. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  17945. ASSERT_TRUE(client.send(at_limit));
  17946. std::string msg;
  17947. ASSERT_TRUE(client.read(msg));
  17948. EXPECT_EQ(at_limit.size(), msg.size());
  17949. client.close();
  17950. }
  17951. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  17952. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17953. "/nonexistent");
  17954. auto res = client.connect();
  17955. EXPECT_FALSE(res);
  17956. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  17957. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  17958. EXPECT_FALSE(client.is_open());
  17959. }
  17960. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  17961. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17962. "/ws-echo");
  17963. ASSERT_TRUE(client.connect());
  17964. ASSERT_TRUE(client.send(""));
  17965. std::string msg;
  17966. EXPECT_EQ(ws::Text, client.read(msg));
  17967. EXPECT_EQ("", msg);
  17968. client.close();
  17969. }
  17970. TEST_F(WebSocketIntegrationTest, Reconnect) {
  17971. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17972. "/ws-echo");
  17973. // First connection
  17974. ASSERT_TRUE(client.connect());
  17975. ASSERT_TRUE(client.send("first"));
  17976. std::string msg;
  17977. ASSERT_TRUE(client.read(msg));
  17978. EXPECT_EQ("first", msg);
  17979. client.close();
  17980. EXPECT_FALSE(client.is_open());
  17981. // Reconnect using the same client object
  17982. ASSERT_TRUE(client.connect());
  17983. ASSERT_TRUE(client.is_open());
  17984. ASSERT_TRUE(client.send("second"));
  17985. ASSERT_TRUE(client.read(msg));
  17986. EXPECT_EQ("second", msg);
  17987. client.close();
  17988. }
  17989. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  17990. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17991. "/ws-close-status");
  17992. ASSERT_TRUE(client.connect());
  17993. // Trigger the server to close with GoingAway status
  17994. ASSERT_TRUE(client.send("trigger"));
  17995. // read() should return false after receiving the close frame
  17996. std::string msg;
  17997. EXPECT_FALSE(client.read(msg));
  17998. EXPECT_FALSE(client.is_open());
  17999. }
  18000. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  18001. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18002. "/ws-echo");
  18003. ASSERT_TRUE(client.connect());
  18004. client.close(ws::CloseStatus::GoingAway, "client leaving");
  18005. EXPECT_FALSE(client.is_open());
  18006. }
  18007. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  18008. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  18009. ws::WebSocketClient client(
  18010. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18011. ASSERT_TRUE(client.connect());
  18012. // Server should have selected graphql-ws
  18013. EXPECT_EQ("graphql-ws", client.subprotocol());
  18014. client.close();
  18015. }
  18016. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  18017. Headers headers;
  18018. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  18019. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  18020. ws::WebSocketClient client(
  18021. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18022. ASSERT_TRUE(client.connect());
  18023. // The offer on the second field line counts too, so graphql-ws is selected
  18024. EXPECT_EQ("graphql-ws", client.subprotocol());
  18025. client.close();
  18026. }
  18027. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  18028. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  18029. ws::WebSocketClient client(
  18030. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18031. ASSERT_TRUE(client.connect());
  18032. // Server should not have selected any subprotocol
  18033. EXPECT_TRUE(client.subprotocol().empty());
  18034. client.close();
  18035. }
  18036. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  18037. // Connect without requesting any subprotocol
  18038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18039. "/ws-subprotocol");
  18040. ASSERT_TRUE(client.connect());
  18041. EXPECT_TRUE(client.subprotocol().empty());
  18042. client.close();
  18043. }
  18044. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  18045. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18046. "/ws-echo");
  18047. client.set_tcp_nodelay(true);
  18048. client.set_connection_timeout(3, 0);
  18049. bool socket_options_called = false;
  18050. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  18051. ASSERT_TRUE(client.connect());
  18052. ASSERT_TRUE(client.is_open());
  18053. EXPECT_TRUE(socket_options_called);
  18054. ASSERT_TRUE(client.send("hello"));
  18055. std::string msg;
  18056. auto result = client.read(msg);
  18057. EXPECT_EQ(result, ws::ReadResult::Text);
  18058. EXPECT_EQ(msg, "hello");
  18059. client.close();
  18060. }
  18061. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  18062. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18063. "/ws-echo");
  18064. client.set_connection_timeout(std::chrono::seconds(3));
  18065. client.set_write_timeout(std::chrono::seconds(3));
  18066. // A sub-second remainder exercises the seconds/microseconds split.
  18067. client.set_read_timeout(std::chrono::milliseconds(1500));
  18068. ASSERT_TRUE(client.connect());
  18069. auto start = std::chrono::steady_clock::now();
  18070. std::string msg;
  18071. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  18072. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18073. std::chrono::steady_clock::now() - start)
  18074. .count();
  18075. // Above 1s so that dropping the microseconds half of the split fails here,
  18076. // and well under the 300s default so that ignoring the setter fails too.
  18077. EXPECT_GE(elapsed, 1400);
  18078. EXPECT_LT(elapsed, 30000);
  18079. }
  18080. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  18081. Server svr;
  18082. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  18083. if (!req.has_header("Authorization")) {
  18084. res.status = StatusCode::Unauthorized_401;
  18085. res.set_content("Unauthorized", "text/plain");
  18086. return Server::HandlerResponse::Handled;
  18087. }
  18088. return Server::HandlerResponse::Unhandled;
  18089. });
  18090. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18091. std::string msg;
  18092. while (ws.read(msg)) {
  18093. ws.send(msg);
  18094. }
  18095. });
  18096. auto port = svr.bind_to_any_port("localhost");
  18097. std::thread t([&]() { svr.listen_after_bind(); });
  18098. svr.wait_until_ready();
  18099. // Without Authorization header - should be rejected before upgrade
  18100. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  18101. EXPECT_FALSE(client1.connect());
  18102. // With Authorization header - should succeed
  18103. Headers headers = {{"Authorization", "Bearer token123"}};
  18104. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  18105. headers);
  18106. ASSERT_TRUE(client2.connect());
  18107. ASSERT_TRUE(client2.send("hello"));
  18108. std::string msg;
  18109. ASSERT_TRUE(client2.read(msg));
  18110. EXPECT_EQ("hello", msg);
  18111. client2.close();
  18112. svr.stop();
  18113. t.join();
  18114. }
  18115. TEST(WebSocketTest, QueryStringInHandshake) {
  18116. Server svr;
  18117. std::mutex mtx;
  18118. std::string received_target;
  18119. std::string received_token;
  18120. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18121. {
  18122. std::lock_guard<std::mutex> lock(mtx);
  18123. received_target = req.target;
  18124. if (req.has_param("token")) {
  18125. received_token = req.get_param_value("token");
  18126. }
  18127. }
  18128. std::string msg;
  18129. while (ws.read(msg)) {
  18130. ws.send(msg);
  18131. }
  18132. });
  18133. auto port = svr.bind_to_any_port("localhost");
  18134. std::thread t([&]() { svr.listen_after_bind(); });
  18135. svr.wait_until_ready();
  18136. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  18137. "/ws?token=ABC&session=123");
  18138. ASSERT_TRUE(client.connect());
  18139. // Round-trip ensures the handler has run and captured the request.
  18140. ASSERT_TRUE(client.send("hello"));
  18141. std::string msg;
  18142. ASSERT_TRUE(client.read(msg));
  18143. EXPECT_EQ("hello", msg);
  18144. client.close();
  18145. {
  18146. std::lock_guard<std::mutex> lock(mtx);
  18147. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  18148. EXPECT_EQ("ABC", received_token);
  18149. }
  18150. svr.stop();
  18151. t.join();
  18152. }
  18153. // Run a handshake against a throwaway server and hand the request the server
  18154. // received back to the caller, so tests can assert on the headers the client
  18155. // actually put on the wire.
  18156. static void capture_websocket_handshake_request(
  18157. const Headers &client_headers,
  18158. std::function<void(const Request &, int port)> verify) {
  18159. Server svr;
  18160. std::mutex mtx;
  18161. Request received;
  18162. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18163. {
  18164. std::lock_guard<std::mutex> lock(mtx);
  18165. received = req;
  18166. }
  18167. std::string msg;
  18168. while (ws.read(msg)) {
  18169. ws.send(msg);
  18170. }
  18171. });
  18172. auto port = svr.bind_to_any_port("localhost");
  18173. std::thread t([&]() { svr.listen_after_bind(); });
  18174. auto se = detail::scope_exit([&] {
  18175. svr.stop();
  18176. t.join();
  18177. });
  18178. svr.wait_until_ready();
  18179. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  18180. client_headers);
  18181. ASSERT_TRUE(client.connect());
  18182. ASSERT_TRUE(client.send("hello"));
  18183. std::string msg;
  18184. ASSERT_TRUE(client.read(msg));
  18185. client.close();
  18186. {
  18187. std::lock_guard<std::mutex> lock(mtx);
  18188. verify(received, port);
  18189. }
  18190. }
  18191. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  18192. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  18193. // Non-default port must be present in the Host header. Default ports
  18194. // (80/443) are omitted; that logic is covered by
  18195. // MakeHostAndPortStringTest.
  18196. EXPECT_EQ("localhost:" + std::to_string(port),
  18197. req.get_header_value("Host"));
  18198. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  18199. req.get_header_value("User-Agent"));
  18200. EXPECT_FALSE(req.has_header("Accept"));
  18201. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  18202. EXPECT_FALSE(req.has_header("Content-Length"));
  18203. });
  18204. }
  18205. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  18206. capture_websocket_handshake_request(
  18207. {{"Host", "example.com"},
  18208. {"User-Agent", "custom-agent"},
  18209. {"X-Custom", "value"}},
  18210. [](const Request &req, int) {
  18211. EXPECT_EQ("example.com", req.get_header_value("Host"));
  18212. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  18213. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  18214. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  18215. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  18216. });
  18217. }
  18218. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  18219. capture_websocket_handshake_request(
  18220. {{"Upgrade", "bogus"},
  18221. {"Connection", "close"},
  18222. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  18223. {"Sec-WebSocket-Version", "8"}},
  18224. [](const Request &req, int) {
  18225. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  18226. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  18227. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  18228. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  18229. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  18230. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  18231. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  18232. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  18233. req.get_header_value("Sec-WebSocket-Key"));
  18234. });
  18235. }
  18236. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  18237. // A header the client refuses to send must abort the handshake before any
  18238. // part of it reaches the wire; a lone request line would otherwise sit in
  18239. // the peer's buffer as a truncated request.
  18240. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18241. ASSERT_NE(INVALID_SOCKET, srv);
  18242. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  18243. sockaddr_in addr{};
  18244. addr.sin_family = AF_INET;
  18245. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  18246. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18247. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18248. ASSERT_EQ(0, ::listen(srv, 1));
  18249. sockaddr_in bound{};
  18250. socklen_t bound_len = sizeof(bound);
  18251. ASSERT_EQ(
  18252. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  18253. auto port = ntohs(bound.sin_port);
  18254. ssize_t received = -1;
  18255. std::thread t([&] {
  18256. // Bound every blocking call so a regression fails the test with a bad
  18257. // value instead of hanging the suite.
  18258. fd_set rfds;
  18259. FD_ZERO(&rfds);
  18260. FD_SET(srv, &rfds);
  18261. timeval tv{5, 0};
  18262. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  18263. 0) {
  18264. return;
  18265. }
  18266. sockaddr_in cli_addr{};
  18267. socklen_t cli_len = sizeof(cli_addr);
  18268. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18269. if (cli == INVALID_SOCKET) { return; }
  18270. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  18271. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18272. char buf[4096];
  18273. received = ::recv(cli, buf, sizeof(buf), 0);
  18274. });
  18275. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  18276. // connect() has already shut the socket down by the time it returns false,
  18277. // so the peer sees EOF without waiting for the client to be destroyed.
  18278. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  18279. {{"X-Bad", "a\r\nInjected: 1"}});
  18280. EXPECT_FALSE(client.connect());
  18281. t.join();
  18282. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  18283. EXPECT_EQ(0, received);
  18284. }
  18285. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  18286. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  18287. // contains "upgrade" as a substring is a different token and must not
  18288. // start a WebSocket handshake.
  18289. auto make_request = [](const std::vector<std::string> &connection_values) {
  18290. Request req;
  18291. req.method = "GET";
  18292. req.headers.emplace("Upgrade", "websocket");
  18293. for (const auto &value : connection_values) {
  18294. req.headers.emplace("Connection", value);
  18295. }
  18296. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18297. req.headers.emplace("Sec-WebSocket-Version", "13");
  18298. return req;
  18299. };
  18300. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  18301. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  18302. EXPECT_TRUE(
  18303. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  18304. EXPECT_TRUE(
  18305. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  18306. EXPECT_TRUE(
  18307. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  18308. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  18309. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  18310. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  18311. EXPECT_FALSE(
  18312. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  18313. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  18314. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18315. }
  18316. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  18317. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  18318. // asks recipients to match each protocol-name case-insensitively, and RFC
  18319. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  18320. // client naming websocket alongside another protocol, or on a second field
  18321. // line, is offering websocket; a value that merely contains "websocket" as a
  18322. // substring is a different protocol name and is not.
  18323. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  18324. Request req;
  18325. req.method = "GET";
  18326. for (const auto &value : upgrade_values) {
  18327. req.headers.emplace("Upgrade", value);
  18328. }
  18329. req.headers.emplace("Connection", "Upgrade");
  18330. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18331. req.headers.emplace("Sec-WebSocket-Version", "13");
  18332. return req;
  18333. };
  18334. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  18335. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  18336. EXPECT_TRUE(
  18337. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  18338. EXPECT_TRUE(
  18339. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  18340. EXPECT_TRUE(
  18341. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  18342. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  18343. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  18344. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  18345. EXPECT_FALSE(
  18346. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  18347. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  18348. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18349. }
  18350. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  18351. Server svr;
  18352. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  18353. auto port = svr.bind_to_any_port("localhost");
  18354. std::thread t([&]() { svr.listen_after_bind(); });
  18355. auto se = detail::scope_exit([&] {
  18356. svr.stop();
  18357. t.join();
  18358. });
  18359. svr.wait_until_ready();
  18360. Headers headers = {{"Upgrade", "websocket"},
  18361. {"Connection", "notupgrade"},
  18362. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  18363. {"Sec-WebSocket-Version", "13"}};
  18364. Client cli("localhost", port);
  18365. auto res = cli.Get("/ws", headers);
  18366. // The route exists only as a WebSocket route, so a request that fails the
  18367. // handshake check falls through to ordinary routing.
  18368. ASSERT_TRUE(res);
  18369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  18370. }
  18371. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  18372. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  18373. // Connection value is the only thing left for the client to reject.
  18374. Server svr;
  18375. svr.Get("/ws", [](const Request &req, Response &res) {
  18376. res.status = StatusCode::SwitchingProtocol_101;
  18377. res.set_header("Upgrade", "websocket");
  18378. res.set_header("Connection", "notupgrade");
  18379. res.set_header("Sec-WebSocket-Accept",
  18380. detail::websocket_accept_key(
  18381. req.get_header_value("Sec-WebSocket-Key")));
  18382. });
  18383. auto port = svr.bind_to_any_port("localhost");
  18384. std::thread t([&]() { svr.listen_after_bind(); });
  18385. auto se = detail::scope_exit([&] {
  18386. svr.stop();
  18387. t.join();
  18388. });
  18389. svr.wait_until_ready();
  18390. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18391. auto res = client.connect();
  18392. EXPECT_FALSE(res);
  18393. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18394. EXPECT_FALSE(client.is_open());
  18395. }
  18396. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  18397. // The socket path doubles as the URL host, so it must not contain '/'.
  18398. const char *shard = getenv("GTEST_SHARD_INDEX");
  18399. const std::string sock_path =
  18400. shard ? std::string("httplib-ws-") + shard + ".sock"
  18401. : std::string("httplib-ws.sock");
  18402. std::remove(sock_path.c_str());
  18403. Server svr;
  18404. std::mutex mtx;
  18405. std::string received_host;
  18406. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18407. {
  18408. std::lock_guard<std::mutex> lock(mtx);
  18409. received_host = req.get_header_value("Host");
  18410. }
  18411. std::string msg;
  18412. while (ws.read(msg)) {
  18413. ws.send(msg);
  18414. }
  18415. });
  18416. svr.set_address_family(AF_UNIX);
  18417. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  18418. auto se = detail::scope_exit([&] {
  18419. svr.stop();
  18420. t.join();
  18421. std::remove(sock_path.c_str());
  18422. });
  18423. svr.wait_until_ready();
  18424. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  18425. client.set_address_family(AF_UNIX);
  18426. ASSERT_TRUE(client.connect());
  18427. ASSERT_TRUE(client.send("hello"));
  18428. std::string msg;
  18429. ASSERT_TRUE(client.read(msg));
  18430. client.close();
  18431. {
  18432. std::lock_guard<std::mutex> lock(mtx);
  18433. // There is no host:port for a Unix socket, so the same "localhost"
  18434. // placeholder the HTTP client uses is expected.
  18435. EXPECT_EQ("localhost", received_host);
  18436. }
  18437. }
  18438. // Two threads must never parse WebSocket frames from the same stream.
  18439. // close() used to read the peer's Close reply with its own frame read, so it
  18440. // raced a reader thread that was in the middle of a payload: the payload loop
  18441. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  18442. // so bytes taken by close() were replaced with bytes from further along the
  18443. // stream. The message kept its length and silently changed content.
  18444. //
  18445. // The raw peer below sends a frame header plus part of the payload, waits for
  18446. // the handler to call close(), and only then sends the rest. Whichever thread
  18447. // would win the race for those bytes, the message must arrive intact, because
  18448. // close() must not touch the stream while read() owns it.
  18449. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  18450. #ifndef _WIN32
  18451. signal(SIGPIPE, SIG_IGN);
  18452. #endif
  18453. const size_t payload_len = 120; // fits the 7-bit length field
  18454. const size_t prefix_len = 8;
  18455. const int attempts = 8;
  18456. std::string expected(payload_len, '\0');
  18457. for (size_t i = 0; i < payload_len; i++) {
  18458. expected[i] = static_cast<char>('a' + i % 26);
  18459. }
  18460. std::atomic<bool> peer_stalled{false};
  18461. std::atomic<bool> handler_done{false};
  18462. std::mutex received_mutex;
  18463. std::vector<std::string> received;
  18464. // Bound every wait, so a regression fails the test instead of hanging the
  18465. // suite.
  18466. auto wait_for = [](const std::atomic<bool> &flag) {
  18467. for (int i = 0; i < 500 && !flag; i++) {
  18468. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18469. }
  18470. };
  18471. Server svr;
  18472. svr.set_websocket_ping_interval(0);
  18473. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  18474. std::thread reader([&]() {
  18475. std::string msg;
  18476. while (ws.read(msg)) {
  18477. std::lock_guard<std::mutex> guard(received_mutex);
  18478. received.push_back(msg);
  18479. }
  18480. });
  18481. // Wait until the peer stalls mid-payload, so the reader thread is parked
  18482. // inside read_websocket_frame() when close() runs.
  18483. wait_for(peer_stalled);
  18484. ws.close();
  18485. reader.join();
  18486. handler_done = true;
  18487. });
  18488. auto port = svr.bind_to_any_port("127.0.0.1");
  18489. std::thread t([&]() { svr.listen_after_bind(); });
  18490. auto se = detail::scope_exit([&] {
  18491. svr.stop();
  18492. t.join();
  18493. });
  18494. svr.wait_until_ready();
  18495. auto send_bytes = [](socket_t s, const std::string &data) {
  18496. #ifdef _WIN32
  18497. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  18498. #else
  18499. auto n = ::send(s, data.data(), data.size(), 0);
  18500. #endif
  18501. return n == static_cast<decltype(n)>(data.size());
  18502. };
  18503. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  18504. // Every length used here fits the 7-bit length field.
  18505. auto masked_header = [](uint8_t first_byte, size_t len) {
  18506. std::string h;
  18507. h += static_cast<char>(first_byte);
  18508. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  18509. h.append(4, '\0'); // mask key
  18510. return h;
  18511. };
  18512. for (int attempt = 0; attempt < attempts; attempt++) {
  18513. peer_stalled = false;
  18514. handler_done = false;
  18515. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  18516. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  18517. auto se_sock = detail::scope_exit([&] {
  18518. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  18519. });
  18520. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18521. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18522. sockaddr_in addr{};
  18523. addr.sin_family = AF_INET;
  18524. addr.sin_port = htons(static_cast<uint16_t>(port));
  18525. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18526. ASSERT_EQ(
  18527. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  18528. << "attempt " << attempt;
  18529. ASSERT_TRUE(send_bytes(sock,
  18530. "GET /ws HTTP/1.1\r\n"
  18531. "Host: 127.0.0.1\r\n"
  18532. "Upgrade: websocket\r\n"
  18533. "Connection: Upgrade\r\n"
  18534. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  18535. "Sec-WebSocket-Version: 13\r\n"
  18536. "\r\n"))
  18537. << "attempt " << attempt;
  18538. std::string response;
  18539. while (response.find("\r\n\r\n") == std::string::npos) {
  18540. char buf[512];
  18541. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  18542. if (n <= 0) { break; }
  18543. response.append(buf, static_cast<size_t>(n));
  18544. }
  18545. ASSERT_NE(std::string::npos, response.find(" 101 "))
  18546. << "attempt " << attempt;
  18547. // Send the header of a Binary message but only the first prefix_len bytes
  18548. // of its payload, leaving the reader thread stalled inside the payload.
  18549. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  18550. expected.substr(0, prefix_len)))
  18551. << "attempt " << attempt;
  18552. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18553. peer_stalled = true;
  18554. // Let close() send its Close frame and park in its own read before the
  18555. // rest of the payload arrives, so both threads are waiting for it.
  18556. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18557. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  18558. close_frame += static_cast<char>(0x03); // status 1000
  18559. close_frame += static_cast<char>(0xE8);
  18560. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  18561. << "attempt " << attempt;
  18562. // Closing the peer releases the reader thread even on the buggy path,
  18563. // where it waits for bytes another thread already consumed.
  18564. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18565. detail::close_socket(sock);
  18566. sock = INVALID_SOCKET;
  18567. wait_for(handler_done);
  18568. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  18569. }
  18570. std::lock_guard<std::mutex> guard(received_mutex);
  18571. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  18572. << "a message in flight when close() ran was dropped";
  18573. for (size_t i = 0; i < received.size(); i++) {
  18574. EXPECT_EQ(expected, received[i]) << "message " << i;
  18575. }
  18576. }
  18577. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18578. class WebSocketSSLIntegrationTest : public ::testing::Test {
  18579. protected:
  18580. void SetUp() override {
  18581. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  18582. SERVER_PRIVATE_KEY_FILE);
  18583. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18584. std::string msg;
  18585. ws::ReadResult ret;
  18586. while ((ret = ws.read(msg))) {
  18587. if (ret == ws::Binary) {
  18588. ws.send(msg.data(), msg.size());
  18589. } else {
  18590. ws.send(msg);
  18591. }
  18592. }
  18593. });
  18594. port_ = server_->bind_to_any_port(HOST);
  18595. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18596. server_->wait_until_ready();
  18597. }
  18598. void TearDown() override {
  18599. server_->stop();
  18600. if (server_thread_.joinable()) { server_thread_.join(); }
  18601. }
  18602. std::unique_ptr<SSLServer> server_;
  18603. std::thread server_thread_;
  18604. int port_ = 0;
  18605. };
  18606. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  18607. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18608. "/ws-echo");
  18609. client.enable_server_certificate_verification(false);
  18610. ASSERT_TRUE(client.connect());
  18611. ASSERT_TRUE(client.is_open());
  18612. ASSERT_TRUE(client.send("Hello WSS"));
  18613. std::string msg;
  18614. EXPECT_EQ(ws::Text, client.read(msg));
  18615. EXPECT_EQ("Hello WSS", msg);
  18616. client.close();
  18617. }
  18618. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  18619. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  18620. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  18621. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  18622. // client (without calling close() first) is the only path that runs
  18623. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  18624. // bug exactly.
  18625. //
  18626. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  18627. // when linked against an instrumented libssl; run under Valgrind to catch it
  18628. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  18629. // suite (the freed session otherwise stalls on the close handshake) — this test
  18630. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  18631. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  18632. {
  18633. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18634. "/ws-echo");
  18635. client.enable_server_certificate_verification(false);
  18636. client.set_read_timeout(2, 0);
  18637. client.set_write_timeout(2, 0);
  18638. ASSERT_TRUE(client.connect());
  18639. ASSERT_TRUE(client.is_open());
  18640. ASSERT_TRUE(client.send("still open"));
  18641. // Intentionally do NOT call client.close(): leaving scope runs
  18642. // shutdown_and_close() with the WebSocket still open, which must send the
  18643. // close frame while the TLS session is still alive.
  18644. }
  18645. }
  18646. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  18647. // shutdown_and_close() at the start of connect(), reproducing the same
  18648. // use-after-free within the test body rather than at scope exit. The second
  18649. // connect must succeed and echo, proving the close handshake ran over a live
  18650. // session. See the note above about memory-tool requirements.
  18651. TEST_F(WebSocketSSLIntegrationTest,
  18652. ReconnectWhileOpenSendsCloseOverLiveSession) {
  18653. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18654. "/ws-echo");
  18655. client.enable_server_certificate_verification(false);
  18656. client.set_read_timeout(2, 0);
  18657. client.set_write_timeout(2, 0);
  18658. ASSERT_TRUE(client.connect());
  18659. ASSERT_TRUE(client.is_open());
  18660. ASSERT_TRUE(client.send("still open"));
  18661. // Reconnect without closing first: connect() calls shutdown_and_close() on
  18662. // the still-open connection, which must not touch a freed TLS session.
  18663. ASSERT_TRUE(client.connect());
  18664. ASSERT_TRUE(client.is_open());
  18665. ASSERT_TRUE(client.send("after reconnect"));
  18666. std::string msg;
  18667. EXPECT_EQ(ws::Text, client.read(msg));
  18668. EXPECT_EQ("after reconnect", msg);
  18669. client.close();
  18670. }
  18671. #endif
  18672. #ifdef CPPHTTPLIB_SSL_ENABLED
  18673. class WebSocketSSLCATest : public ::testing::Test {
  18674. protected:
  18675. void SetUp() override {
  18676. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  18677. SERVER_PRIVATE_KEY_FILE);
  18678. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18679. std::string msg;
  18680. while (ws.read(msg)) {
  18681. ws.send(msg);
  18682. }
  18683. });
  18684. port_ = server_->bind_to_any_port("127.0.0.1");
  18685. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18686. server_->wait_until_ready();
  18687. }
  18688. void TearDown() override {
  18689. server_->stop();
  18690. if (server_thread_.joinable()) { server_thread_.join(); }
  18691. }
  18692. std::string url() const {
  18693. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  18694. }
  18695. std::unique_ptr<SSLServer> server_;
  18696. std::thread server_thread_;
  18697. int port_ = 0;
  18698. };
  18699. // A custom CA loaded as PEM verifies the server with full certificate
  18700. // verification enabled
  18701. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  18702. ws::WebSocketClient client(url());
  18703. std::string cert;
  18704. read_file(SERVER_CERT2_FILE, cert);
  18705. client.load_ca_cert_store(cert.c_str(), cert.size());
  18706. ASSERT_TRUE(client.connect());
  18707. ASSERT_TRUE(client.send("hello"));
  18708. std::string msg;
  18709. EXPECT_EQ(ws::Text, client.read(msg));
  18710. EXPECT_EQ("hello", msg);
  18711. client.close();
  18712. }
  18713. // A custom CA that does not cover the server must fail verification (the
  18714. // custom CA is exclusive; system certs are not loaded alongside it)
  18715. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  18716. ws::WebSocketClient client(url());
  18717. std::string cert;
  18718. read_file(CLIENT_CA_CERT_FILE, cert);
  18719. client.load_ca_cert_store(cert.c_str(), cert.size());
  18720. auto res = client.connect();
  18721. ASSERT_FALSE(res);
  18722. EXPECT_EQ(Error::SSLServerVerification, res.error());
  18723. EXPECT_EQ(-1, res.status());
  18724. EXPECT_NE(0u, res.ssl_backend_error());
  18725. }
  18726. // The same CA as a file path rather than PEM in memory
  18727. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  18728. ws::WebSocketClient client(url());
  18729. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18730. ASSERT_TRUE(client.connect());
  18731. ASSERT_TRUE(client.send("hello"));
  18732. std::string msg;
  18733. EXPECT_EQ(ws::Text, client.read(msg));
  18734. EXPECT_EQ("hello", msg);
  18735. client.close();
  18736. }
  18737. // ...and a CA file that does not cover the server still fails, so it is the
  18738. // path above that decides the outcome
  18739. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  18740. ws::WebSocketClient client(url());
  18741. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18742. ASSERT_FALSE(client.connect());
  18743. }
  18744. // Regression test: reconnecting with a native custom CA store used to reuse
  18745. // a store handle the previous TLS context had already freed (use-after-free
  18746. // under the OpenSSL backend). The context now lives as long as the client.
  18747. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  18748. ws::WebSocketClient client(url());
  18749. std::string cert;
  18750. read_file(SERVER_CERT2_FILE, cert);
  18751. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  18752. ASSERT_TRUE(client.connect());
  18753. client.close();
  18754. ASSERT_TRUE(client.connect());
  18755. ASSERT_TRUE(client.send("again"));
  18756. std::string msg;
  18757. EXPECT_EQ(ws::Text, client.read(msg));
  18758. EXPECT_EQ("again", msg);
  18759. client.close();
  18760. }
  18761. // Regression test: a certificate with a trusted chain but no identity match
  18762. // for the server IP must be rejected. The Mbed TLS backend used to skip
  18763. // verification entirely for IP hosts, so this connection succeeded there.
  18764. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  18765. // chain verification while the identity check must still fail.
  18766. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  18767. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18768. ASSERT_TRUE(svr.is_valid());
  18769. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18770. std::string msg;
  18771. while (ws.read(msg)) {
  18772. ws.send(msg);
  18773. }
  18774. });
  18775. auto port = svr.bind_to_any_port("127.0.0.1");
  18776. auto t = std::thread([&]() { svr.listen_after_bind(); });
  18777. auto se = detail::scope_exit([&] {
  18778. svr.stop();
  18779. t.join();
  18780. });
  18781. svr.wait_until_ready();
  18782. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  18783. "/echo");
  18784. std::string cert;
  18785. read_file(SERVER_CERT_FILE, cert);
  18786. client.load_ca_cert_store(cert.c_str(), cert.size());
  18787. ASSERT_FALSE(client.connect());
  18788. }
  18789. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  18790. // SNI, so nothing binds the host name to the TLS session. These bind the
  18791. // server to "localhost" instead, the only shape that exercises the SNI and
  18792. // hostname-verification path with certificate verification left enabled.
  18793. class WebSocketSSLDnsHostTest : public ::testing::Test {
  18794. protected:
  18795. void Start(const char *cert_file) {
  18796. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  18797. SERVER_PRIVATE_KEY_FILE);
  18798. ASSERT_TRUE(server_->is_valid());
  18799. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18800. std::string msg;
  18801. while (ws.read(msg)) {
  18802. ws.send(msg);
  18803. }
  18804. });
  18805. port_ = server_->bind_to_any_port("localhost");
  18806. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18807. server_->wait_until_ready();
  18808. }
  18809. void TearDown() override {
  18810. if (server_) { server_->stop(); }
  18811. if (server_thread_.joinable()) { server_thread_.join(); }
  18812. }
  18813. std::string url() const {
  18814. return "wss://localhost:" + std::to_string(port_) + "/echo";
  18815. }
  18816. std::unique_ptr<SSLServer> server_;
  18817. std::thread server_thread_;
  18818. int port_ = 0;
  18819. };
  18820. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  18821. // out and the connection is usable
  18822. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  18823. Start(SERVER_CERT2_FILE);
  18824. ws::WebSocketClient client(url());
  18825. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18826. ASSERT_TRUE(client.connect());
  18827. ASSERT_TRUE(client.send("hello"));
  18828. std::string msg;
  18829. EXPECT_EQ(ws::Text, client.read(msg));
  18830. EXPECT_EQ("hello", msg);
  18831. client.close();
  18832. }
  18833. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  18834. // while the identity check must still reject "localhost"
  18835. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  18836. Start(SERVER_CERT_FILE);
  18837. ws::WebSocketClient client(url());
  18838. client.set_ca_cert_path(SERVER_CERT_FILE);
  18839. auto res = client.connect();
  18840. ASSERT_FALSE(res);
  18841. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  18842. EXPECT_EQ(-1, res.status());
  18843. }
  18844. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  18845. // disabled: the chain is still checked, only the identity check is skipped
  18846. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  18847. Start(SERVER_CERT_FILE);
  18848. ws::WebSocketClient client(url());
  18849. client.set_ca_cert_path(SERVER_CERT_FILE);
  18850. client.enable_server_hostname_verification(false);
  18851. ASSERT_TRUE(client.connect());
  18852. ASSERT_TRUE(client.send("hello"));
  18853. std::string msg;
  18854. EXPECT_EQ(ws::Text, client.read(msg));
  18855. EXPECT_EQ("hello", msg);
  18856. client.close();
  18857. }
  18858. // A CA that did not sign the server certificate fails the chain, even though
  18859. // the name would match
  18860. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  18861. Start(SERVER_CERT2_FILE);
  18862. ws::WebSocketClient client(url());
  18863. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18864. ASSERT_FALSE(client.connect());
  18865. }
  18866. // With verification disabled, neither the chain nor the name is checked
  18867. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  18868. Start(SERVER_CERT_FILE);
  18869. ws::WebSocketClient client(url());
  18870. client.enable_server_certificate_verification(false);
  18871. ASSERT_TRUE(client.connect());
  18872. ASSERT_TRUE(client.send("hello"));
  18873. std::string msg;
  18874. EXPECT_EQ(ws::Text, client.read(msg));
  18875. EXPECT_EQ("hello", msg);
  18876. client.close();
  18877. }
  18878. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  18879. protected:
  18880. void SetUp() override {
  18881. server_ = httplib::detail::make_unique<SSLServer>(
  18882. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18883. ASSERT_TRUE(server_->is_valid());
  18884. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18885. std::string msg;
  18886. while (ws.read(msg)) {
  18887. ws.send(msg);
  18888. }
  18889. });
  18890. port_ = server_->bind_to_any_port("localhost");
  18891. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18892. server_->wait_until_ready();
  18893. }
  18894. void TearDown() override {
  18895. server_->stop();
  18896. if (server_thread_.joinable()) { server_thread_.join(); }
  18897. }
  18898. std::string url() const {
  18899. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  18900. }
  18901. void ConnectWithClientCert(const std::string &client_cert_file,
  18902. const std::string &client_private_key_file,
  18903. const char *private_key_password) {
  18904. std::string cert_pem, key_pem;
  18905. read_file(client_cert_file, cert_pem);
  18906. read_file(client_private_key_file, key_pem);
  18907. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  18908. key_pem.c_str(), key_pem.size(),
  18909. private_key_password};
  18910. ws::WebSocketClient client(url(), pem);
  18911. ASSERT_TRUE(client.is_valid());
  18912. client.enable_server_certificate_verification(false);
  18913. ASSERT_TRUE(client.connect());
  18914. ASSERT_TRUE(client.send("hello"));
  18915. std::string msg;
  18916. EXPECT_EQ(ws::Text, client.read(msg));
  18917. EXPECT_EQ("hello", msg);
  18918. client.close();
  18919. }
  18920. std::unique_ptr<SSLServer> server_;
  18921. std::thread server_thread_;
  18922. int port_ = 0;
  18923. };
  18924. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  18925. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  18926. }
  18927. // Control for the tests above: the fixture's server really does require a
  18928. // client certificate, so it is the PEM the constructor installed that decides
  18929. // the outcome.
  18930. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  18931. ws::WebSocketClient client(url());
  18932. ASSERT_TRUE(client.is_valid());
  18933. client.enable_server_certificate_verification(false);
  18934. EXPECT_FALSE(client.connect());
  18935. }
  18936. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  18937. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  18938. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  18939. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  18940. }
  18941. #endif
  18942. #if !defined(_WIN32)
  18943. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  18944. auto secret_dir = std::string("./symlink_test_secret");
  18945. auto served_dir = std::string("./symlink_test_served");
  18946. auto secret_file = secret_dir + "/secret.txt";
  18947. auto symlink_path = served_dir + "/escape";
  18948. // Setup: create directories and files
  18949. mkdir(secret_dir.c_str(), 0755);
  18950. mkdir(served_dir.c_str(), 0755);
  18951. {
  18952. std::ofstream ofs(secret_file);
  18953. ofs << "SECRET_DATA";
  18954. }
  18955. // Create symlink using absolute path so it resolves correctly
  18956. #ifdef PATH_MAX
  18957. char abs_secret[PATH_MAX];
  18958. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  18959. #else
  18960. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  18961. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  18962. ASSERT_NE(nullptr, abs_secret);
  18963. #endif
  18964. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  18965. auto se = detail::scope_exit([&] {
  18966. unlink(symlink_path.c_str());
  18967. unlink(secret_file.c_str());
  18968. rmdir(served_dir.c_str());
  18969. rmdir(secret_dir.c_str());
  18970. });
  18971. Server svr;
  18972. svr.set_mount_point("/", served_dir);
  18973. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18974. auto se2 = detail::scope_exit([&] {
  18975. svr.stop();
  18976. listen_thread.join();
  18977. });
  18978. svr.wait_until_ready();
  18979. Client cli("localhost", PORT);
  18980. // Symlink pointing outside base dir should be blocked
  18981. auto res = cli.Get("/escape/secret.txt");
  18982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18983. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18984. }
  18985. #endif
  18986. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  18987. // A GET request with Content-Length to a static file handler must have its
  18988. // body drained before the keep-alive connection is reused. Otherwise the
  18989. // unread body bytes are interpreted as the next HTTP request.
  18990. //
  18991. // The body is sent AFTER receiving the first response (as in the original
  18992. // PoC) so that the stream_line_reader cannot buffer it together with the
  18993. // headers of the first request.
  18994. Server svr;
  18995. svr.set_mount_point("/", "./www");
  18996. std::atomic<int> smuggled_count(0);
  18997. svr.Get("/smuggled", [&](const Request &, Response &res) {
  18998. smuggled_count++;
  18999. res.set_content("oops", "text/plain");
  19000. });
  19001. auto port = svr.bind_to_any_port("localhost");
  19002. thread t = thread([&] { svr.listen_after_bind(); });
  19003. auto se = detail::scope_exit([&] {
  19004. svr.stop();
  19005. t.join();
  19006. });
  19007. svr.wait_until_ready();
  19008. auto error = Error::Success;
  19009. auto sock = detail::create_client_socket(
  19010. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  19011. /*connection_timeout_sec=*/2, 0,
  19012. /*read_timeout_sec=*/2, 0,
  19013. /*write_timeout_sec=*/2, 0, std::string(), error);
  19014. ASSERT_NE(INVALID_SOCKET, sock);
  19015. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19016. // The "smuggled" request will be sent as the body of the outer GET
  19017. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  19018. "Host: localhost\r\n"
  19019. "Connection: close\r\n"
  19020. "\r\n";
  19021. // Step 1: Send only the outer request headers (no body yet)
  19022. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  19023. "Host: localhost\r\n"
  19024. "Content-Length: " +
  19025. std::to_string(smuggled.size()) +
  19026. "\r\n"
  19027. "\r\n";
  19028. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  19029. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  19030. // Step 2: Read the first response (server serves file without reading body)
  19031. std::string first_response;
  19032. char buf[4096];
  19033. for (;;) {
  19034. auto n = recv(sock, buf, sizeof(buf), 0);
  19035. if (n <= 0) break;
  19036. first_response.append(buf, static_cast<size_t>(n));
  19037. // Stop once we have a complete response (headers + body)
  19038. auto hdr_end = first_response.find("\r\n\r\n");
  19039. if (hdr_end != std::string::npos) {
  19040. // Check for Content-Length to know when the body is complete
  19041. auto cl_pos = first_response.find("Content-Length:");
  19042. if (cl_pos != std::string::npos) {
  19043. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  19044. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  19045. auto cl = std::stoul(
  19046. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  19047. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  19048. } else {
  19049. break; // No Content-Length, assume headers-only response
  19050. }
  19051. }
  19052. }
  19053. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  19054. // Step 3: Now send the body, which looks like a new HTTP request.
  19055. // On a vulnerable server the keep-alive loop reads this as a second request.
  19056. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  19057. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  19058. // Step 4: Try to read a second response (should NOT exist after fix)
  19059. std::string second_response;
  19060. for (;;) {
  19061. auto n = recv(sock, buf, sizeof(buf), 0);
  19062. if (n <= 0) break;
  19063. second_response.append(buf, static_cast<size_t>(n));
  19064. }
  19065. // The smuggled request must NOT have been processed
  19066. EXPECT_EQ(0, smuggled_count.load());
  19067. }
  19068. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19069. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  19070. // must be rejected with 400 Bad Request.
  19071. Server svr;
  19072. svr.Post("/test", [&](const Request &, Response &res) {
  19073. res.set_content("ok", "text/plain");
  19074. });
  19075. thread t = thread([&] { svr.listen(HOST, PORT); });
  19076. auto se = detail::scope_exit([&] {
  19077. svr.stop();
  19078. t.join();
  19079. ASSERT_FALSE(svr.is_running());
  19080. });
  19081. svr.wait_until_ready();
  19082. // Exact "chunked"
  19083. {
  19084. auto req = "POST /test HTTP/1.1\r\n"
  19085. "Host: localhost\r\n"
  19086. "Content-Length: 5\r\n"
  19087. "Transfer-Encoding: chunked\r\n"
  19088. "Connection: close\r\n"
  19089. "\r\n"
  19090. "hello";
  19091. std::string response;
  19092. ASSERT_TRUE(send_request(1, req, &response));
  19093. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19094. response.substr(0, response.find("\r\n")));
  19095. }
  19096. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  19097. {
  19098. auto req = "POST /test HTTP/1.1\r\n"
  19099. "Host: localhost\r\n"
  19100. "Content-Length: 5\r\n"
  19101. "Transfer-Encoding: gzip, chunked\r\n"
  19102. "Connection: close\r\n"
  19103. "\r\n"
  19104. "hello";
  19105. std::string response;
  19106. ASSERT_TRUE(send_request(1, req, &response));
  19107. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19108. response.substr(0, response.find("\r\n")));
  19109. }
  19110. }
  19111. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  19112. Server svr;
  19113. svr.Post("/test", [&](const Request &, Response &res) {
  19114. res.set_content("ok", "text/plain");
  19115. });
  19116. thread t = thread([&] { svr.listen(HOST, PORT); });
  19117. auto se = detail::scope_exit([&] {
  19118. svr.stop();
  19119. t.join();
  19120. ASSERT_FALSE(svr.is_running());
  19121. });
  19122. svr.wait_until_ready();
  19123. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  19124. // length cannot be determined, so the server must answer 400 and close
  19125. // rather than treat the request as bodyless and leave the body in the
  19126. // socket for the next request to pick up.
  19127. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  19128. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  19129. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  19130. std::string response;
  19131. ASSERT_TRUE(send_request(1, req, &response));
  19132. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19133. response.substr(0, response.find("\r\n")))
  19134. << transfer_encoding;
  19135. }
  19136. // RFC 9110 5.3: the codings may also be split across several
  19137. // Transfer-Encoding lines, which combine in the order they were received.
  19138. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  19139. // just like the single-line "chunked, gzip" above.
  19140. {
  19141. auto req = "POST /test HTTP/1.1\r\n"
  19142. "Host: localhost\r\n"
  19143. "Transfer-Encoding: chunked\r\n"
  19144. "Transfer-Encoding: gzip\r\n"
  19145. "\r\n"
  19146. "0\r\n\r\n";
  19147. std::string response;
  19148. ASSERT_TRUE(send_request(1, req, &response));
  19149. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19150. response.substr(0, response.find("\r\n")));
  19151. }
  19152. // A sequence ending in chunked stays valid.
  19153. auto req = "POST /test HTTP/1.1\r\n"
  19154. "Host: localhost\r\n"
  19155. "Transfer-Encoding: gzip, chunked\r\n"
  19156. "Connection: close\r\n"
  19157. "\r\n"
  19158. "0\r\n\r\n";
  19159. std::string response;
  19160. ASSERT_TRUE(send_request(1, req, &response));
  19161. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19162. // ...including when it is spread over several lines.
  19163. auto split_req = "POST /test HTTP/1.1\r\n"
  19164. "Host: localhost\r\n"
  19165. "Transfer-Encoding: gzip\r\n"
  19166. "Transfer-Encoding: chunked\r\n"
  19167. "Connection: close\r\n"
  19168. "\r\n"
  19169. "0\r\n\r\n";
  19170. std::string split_response;
  19171. ASSERT_TRUE(send_request(1, split_req, &split_response));
  19172. EXPECT_EQ("HTTP/1.1 200 OK",
  19173. split_response.substr(0, split_response.find("\r\n")));
  19174. }
  19175. // Regression for issue #2450: a DELETE without Content-Length on a
  19176. // keep-alive connection must not let the post-response drain consume the
  19177. // next request's bytes.
  19178. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  19179. Server svr;
  19180. std::atomic<int> delete_count(0);
  19181. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  19182. delete_count++;
  19183. res.status = StatusCode::NoContent_204;
  19184. });
  19185. auto port = svr.bind_to_any_port(HOST);
  19186. thread t = thread([&] { svr.listen_after_bind(); });
  19187. auto se = detail::scope_exit([&] {
  19188. svr.stop();
  19189. t.join();
  19190. });
  19191. svr.wait_until_ready();
  19192. auto error = Error::Success;
  19193. auto sock = detail::create_client_socket(
  19194. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19195. /*connection_timeout_sec=*/2, 0,
  19196. /*read_timeout_sec=*/2, 0,
  19197. /*write_timeout_sec=*/2, 0, std::string(), error);
  19198. ASSERT_NE(INVALID_SOCKET, sock);
  19199. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19200. auto send_request_and_read_response = [&](const std::string &req,
  19201. std::string &out) -> bool {
  19202. auto sent = send(sock, req.data(), req.size(), 0);
  19203. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  19204. char buf[4096];
  19205. for (;;) {
  19206. auto n = recv(sock, buf, sizeof(buf), 0);
  19207. if (n <= 0) { return !out.empty(); }
  19208. out.append(buf, static_cast<size_t>(n));
  19209. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  19210. }
  19211. };
  19212. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  19213. "Host: localhost\r\n"
  19214. "\r\n";
  19215. std::string resp1;
  19216. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  19217. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  19218. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  19219. "Host: localhost\r\n"
  19220. "Connection: close\r\n"
  19221. "\r\n";
  19222. std::string resp2;
  19223. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  19224. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  19225. EXPECT_EQ(2, delete_count.load());
  19226. }
  19227. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  19228. Server svr;
  19229. svr.Post("/ingest", [&](const Request &, Response &res,
  19230. const ContentReader &content_reader) {
  19231. auto consumed = content_reader([](const char *, size_t) { return false; });
  19232. EXPECT_FALSE(consumed);
  19233. res.status = StatusCode::Conflict_409;
  19234. res.set_header("Connection", "close");
  19235. });
  19236. auto port = svr.bind_to_any_port(HOST);
  19237. thread t = thread([&] { svr.listen_after_bind(); });
  19238. auto se = detail::scope_exit([&] {
  19239. svr.stop();
  19240. t.join();
  19241. });
  19242. svr.wait_until_ready();
  19243. auto error = Error::Success;
  19244. auto sock = detail::create_client_socket(
  19245. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19246. /*connection_timeout_sec=*/2, 0,
  19247. /*read_timeout_sec=*/1, 0,
  19248. /*write_timeout_sec=*/2, 0, std::string(), error);
  19249. ASSERT_NE(INVALID_SOCKET, sock);
  19250. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19251. std::string request = "POST /ingest HTTP/1.1\r\n"
  19252. "Host: localhost\r\n"
  19253. "Transfer-Encoding: chunked\r\n"
  19254. "\r\n"
  19255. "4\r\n"
  19256. "data\r\n";
  19257. auto sent = send(sock, request.data(), request.size(), 0);
  19258. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  19259. std::string response;
  19260. ssize_t received = 0;
  19261. do {
  19262. char buf[4096];
  19263. received = recv(sock, buf, sizeof(buf), 0);
  19264. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  19265. } while (received > 0);
  19266. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  19267. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  19268. EXPECT_EQ(0, received);
  19269. }
  19270. namespace no_proxy_test {
  19271. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  19272. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  19273. // calling listen().
  19274. class ScopedServer {
  19275. public:
  19276. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  19277. ~ScopedServer() {
  19278. svr_.stop();
  19279. if (th_.joinable()) { th_.join(); }
  19280. }
  19281. Server &svr() { return svr_; }
  19282. int port() const { return port_; }
  19283. void listen() {
  19284. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19285. svr_.wait_until_ready();
  19286. }
  19287. private:
  19288. Server svr_;
  19289. std::thread th_;
  19290. int port_ = 0;
  19291. };
  19292. class ProxyAndTargetServers {
  19293. public:
  19294. ProxyAndTargetServers() {
  19295. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  19296. proxy_hits_++;
  19297. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19298. res.set_content("via-proxy", "text/plain");
  19299. });
  19300. target_.Get(".*", [this](const Request &req, Response &res) {
  19301. target_hits_++;
  19302. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19303. res.set_content("direct", "text/plain");
  19304. });
  19305. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  19306. target_port_ = target_.bind_to_any_port("127.0.0.1");
  19307. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  19308. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  19309. proxy_mock_.wait_until_ready();
  19310. target_.wait_until_ready();
  19311. }
  19312. ~ProxyAndTargetServers() {
  19313. proxy_mock_.stop();
  19314. target_.stop();
  19315. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  19316. if (target_thread_.joinable()) { target_thread_.join(); }
  19317. }
  19318. Server &proxy_mock() { return proxy_mock_; }
  19319. Server &target() { return target_; }
  19320. int proxy_port() const { return proxy_port_; }
  19321. int target_port() const { return target_port_; }
  19322. int proxy_hits() const { return proxy_hits_.load(); }
  19323. int target_hits() const { return target_hits_.load(); }
  19324. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  19325. void reset_counters() {
  19326. proxy_hits_ = 0;
  19327. target_hits_ = 0;
  19328. last_had_proxy_authz_ = false;
  19329. }
  19330. private:
  19331. Server proxy_mock_;
  19332. Server target_;
  19333. std::thread proxy_thread_;
  19334. std::thread target_thread_;
  19335. int proxy_port_ = 0;
  19336. int target_port_ = 0;
  19337. std::atomic<int> proxy_hits_{0};
  19338. std::atomic<int> target_hits_{0};
  19339. std::atomic<bool> last_had_proxy_authz_{false};
  19340. };
  19341. inline std::unique_ptr<Client> make_client(const std::string &host,
  19342. ProxyAndTargetServers &s) {
  19343. auto cli = detail::make_unique<Client>(host, s.target_port());
  19344. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  19345. cli->set_proxy("127.0.0.1", s.proxy_port());
  19346. return cli;
  19347. }
  19348. } // namespace no_proxy_test
  19349. using no_proxy_test::make_client;
  19350. using no_proxy_test::ProxyAndTargetServers;
  19351. TEST(NoProxyTest, ExactHostnameBypasses) {
  19352. ProxyAndTargetServers s;
  19353. auto cli = make_client("example.com", s);
  19354. cli->set_no_proxy({"example.com"});
  19355. auto res = cli->Get("/");
  19356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19357. EXPECT_EQ(0, s.proxy_hits());
  19358. EXPECT_EQ(1, s.target_hits());
  19359. }
  19360. TEST(NoProxyTest, SubdomainBypasses) {
  19361. ProxyAndTargetServers s;
  19362. auto cli = make_client("foo.example.com", s);
  19363. cli->set_no_proxy({"example.com"});
  19364. auto res = cli->Get("/");
  19365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19366. EXPECT_EQ(0, s.proxy_hits());
  19367. EXPECT_EQ(1, s.target_hits());
  19368. }
  19369. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  19370. // Regression guard: "evilexample.com" must not be considered a subdomain
  19371. // of "example.com". Without the dot-boundary rule, a naive endsWith
  19372. // check would let traffic bypass the proxy and leak credentials direct
  19373. // to the attacker host.
  19374. ProxyAndTargetServers s;
  19375. auto cli = make_client("evilexample.com", s);
  19376. cli->set_no_proxy({"example.com"});
  19377. auto res = cli->Get("/");
  19378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19379. EXPECT_GE(s.proxy_hits(), 1);
  19380. EXPECT_EQ(0, s.target_hits());
  19381. }
  19382. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  19383. ProxyAndTargetServers s;
  19384. auto cli = make_client("example.com.evil.com", s);
  19385. cli->set_no_proxy({"example.com"});
  19386. auto res = cli->Get("/");
  19387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19388. EXPECT_GE(s.proxy_hits(), 1);
  19389. EXPECT_EQ(0, s.target_hits());
  19390. }
  19391. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  19392. ProxyAndTargetServers s;
  19393. auto cli = make_client("example.com", s);
  19394. cli->set_no_proxy({".example.com"});
  19395. auto res = cli->Get("/");
  19396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19397. EXPECT_EQ(0, s.proxy_hits());
  19398. EXPECT_EQ(1, s.target_hits());
  19399. }
  19400. TEST(NoProxyTest, CaseInsensitiveHostname) {
  19401. ProxyAndTargetServers s;
  19402. auto cli = make_client("Example.COM", s);
  19403. cli->set_no_proxy({"EXAMPLE.com"});
  19404. auto res = cli->Get("/");
  19405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19406. EXPECT_EQ(0, s.proxy_hits());
  19407. EXPECT_EQ(1, s.target_hits());
  19408. }
  19409. TEST(NoProxyTest, TrailingDotIsNormalized) {
  19410. ProxyAndTargetServers s;
  19411. auto cli = make_client("example.com.", s);
  19412. cli->set_no_proxy({"example.com"});
  19413. auto res = cli->Get("/");
  19414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19415. EXPECT_EQ(0, s.proxy_hits());
  19416. EXPECT_EQ(1, s.target_hits());
  19417. }
  19418. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  19419. // Trailing dots must be normalized on BOTH sides — host and entry.
  19420. // An implementation that only strips the host-side trailing dot would
  19421. // fail to match host "example.com" against entry "example.com." because
  19422. // a literal substring search would compare 11 chars against 12.
  19423. ProxyAndTargetServers s;
  19424. auto cli = make_client("example.com", s);
  19425. cli->set_no_proxy({"example.com."});
  19426. auto res = cli->Get("/");
  19427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19428. EXPECT_EQ(0, s.proxy_hits());
  19429. EXPECT_EQ(1, s.target_hits());
  19430. }
  19431. TEST(NoProxyTest, WildcardBypassesEverything) {
  19432. ProxyAndTargetServers s;
  19433. auto cli = make_client("anything.invalid.test", s);
  19434. cli->set_no_proxy({"*"});
  19435. auto res = cli->Get("/");
  19436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19437. EXPECT_EQ(0, s.proxy_hits());
  19438. EXPECT_EQ(1, s.target_hits());
  19439. }
  19440. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  19441. ProxyAndTargetServers s;
  19442. Client cli("127.0.0.1", s.target_port());
  19443. cli.set_proxy("127.0.0.1", s.proxy_port());
  19444. cli.set_no_proxy({"127.0.0.1"});
  19445. auto res = cli.Get("/");
  19446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19447. EXPECT_EQ(0, s.proxy_hits());
  19448. EXPECT_EQ(1, s.target_hits());
  19449. }
  19450. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  19451. ProxyAndTargetServers s;
  19452. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  19453. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  19454. cli.set_proxy("127.0.0.1", s.proxy_port());
  19455. cli.set_no_proxy({"::1"});
  19456. auto res = cli.Get("/");
  19457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19458. EXPECT_EQ(0, s.proxy_hits());
  19459. EXPECT_EQ(1, s.target_hits());
  19460. }
  19461. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  19462. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  19463. // must still be recognized as IPv6 for CIDR matching. Implementations
  19464. // that detect IPv6 only when the host begins with '[' would parse the
  19465. // host as a hostname and miss the match.
  19466. ProxyAndTargetServers s;
  19467. Client cli("fe80::1", s.target_port());
  19468. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19469. cli.set_proxy("127.0.0.1", s.proxy_port());
  19470. cli.set_no_proxy({"fe80::/10"});
  19471. auto res = cli.Get("/");
  19472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19473. EXPECT_EQ(0, s.proxy_hits());
  19474. EXPECT_EQ(1, s.target_hits());
  19475. }
  19476. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  19477. ProxyAndTargetServers s;
  19478. Client cli("::1", s.target_port());
  19479. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  19480. cli.set_proxy("127.0.0.1", s.proxy_port());
  19481. cli.set_no_proxy({"[::1]"});
  19482. auto res = cli.Get("/");
  19483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19484. EXPECT_EQ(0, s.proxy_hits());
  19485. EXPECT_EQ(1, s.target_hits());
  19486. }
  19487. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  19488. ProxyAndTargetServers s;
  19489. Client cli("fe80::1", s.target_port());
  19490. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19491. cli.set_proxy("127.0.0.1", s.proxy_port());
  19492. cli.set_no_proxy({"[fe80::]/10"});
  19493. auto res = cli.Get("/");
  19494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19495. EXPECT_EQ(0, s.proxy_hits());
  19496. EXPECT_EQ(1, s.target_hits());
  19497. }
  19498. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  19499. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  19500. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  19501. // tricks via address-family conversion.
  19502. ProxyAndTargetServers s;
  19503. Client cli("::ffff:127.0.0.1", s.target_port());
  19504. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  19505. cli.set_proxy("127.0.0.1", s.proxy_port());
  19506. cli.set_no_proxy({"127.0.0.1"});
  19507. auto res = cli.Get("/");
  19508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19509. EXPECT_GE(s.proxy_hits(), 1);
  19510. EXPECT_EQ(0, s.target_hits());
  19511. }
  19512. TEST(NoProxyTest, IPv4CidrMatch) {
  19513. ProxyAndTargetServers s;
  19514. Client cli("127.0.0.1", s.target_port());
  19515. cli.set_proxy("127.0.0.1", s.proxy_port());
  19516. cli.set_no_proxy({"127.0.0.0/8"});
  19517. auto res = cli.Get("/");
  19518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19519. EXPECT_EQ(0, s.proxy_hits());
  19520. EXPECT_EQ(1, s.target_hits());
  19521. }
  19522. TEST(NoProxyTest, IPv4CidrNonMatch) {
  19523. ProxyAndTargetServers s;
  19524. Client cli("127.0.0.1", s.target_port());
  19525. cli.set_proxy("127.0.0.1", s.proxy_port());
  19526. cli.set_no_proxy({"10.0.0.0/8"});
  19527. auto res = cli.Get("/");
  19528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19529. EXPECT_GE(s.proxy_hits(), 1);
  19530. EXPECT_EQ(0, s.target_hits());
  19531. }
  19532. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  19533. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  19534. // IPv4 target matches.
  19535. ProxyAndTargetServers s;
  19536. Client cli("127.0.0.1", s.target_port());
  19537. cli.set_proxy("127.0.0.1", s.proxy_port());
  19538. cli.set_no_proxy({"0.0.0.0/0"});
  19539. auto res = cli.Get("/");
  19540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19541. EXPECT_EQ(0, s.proxy_hits());
  19542. EXPECT_EQ(1, s.target_hits());
  19543. }
  19544. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  19545. ProxyAndTargetServers s;
  19546. Client cli("127.0.0.1", s.target_port());
  19547. cli.set_proxy("127.0.0.1", s.proxy_port());
  19548. cli.set_no_proxy({"127.0.0.1"});
  19549. auto res = cli.Get("/");
  19550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19551. EXPECT_EQ(0, s.proxy_hits());
  19552. EXPECT_EQ(1, s.target_hits());
  19553. }
  19554. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  19555. ProxyAndTargetServers s;
  19556. Client cli("127.0.0.1", s.target_port());
  19557. cli.set_proxy("127.0.0.1", s.proxy_port());
  19558. cli.set_no_proxy({"127.0.0.0/33"});
  19559. auto res = cli.Get("/");
  19560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19561. EXPECT_GE(s.proxy_hits(), 1);
  19562. EXPECT_EQ(0, s.target_hits());
  19563. }
  19564. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  19565. // Empty prefix after the slash must be rejected, not silently treated as /32.
  19566. ProxyAndTargetServers s;
  19567. Client cli("127.0.0.1", s.target_port());
  19568. cli.set_proxy("127.0.0.1", s.proxy_port());
  19569. cli.set_no_proxy({"127.0.0.1/"});
  19570. auto res = cli.Get("/");
  19571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19572. EXPECT_GE(s.proxy_hits(), 1);
  19573. EXPECT_EQ(0, s.target_hits());
  19574. }
  19575. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  19576. ProxyAndTargetServers s;
  19577. auto cli = make_client("internal.corp", s);
  19578. cli->set_proxy_basic_auth("u", "p");
  19579. cli->set_no_proxy({"internal.corp"});
  19580. auto res = cli->Get("/");
  19581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19582. EXPECT_EQ(1, s.target_hits());
  19583. EXPECT_EQ(0, s.proxy_hits());
  19584. EXPECT_FALSE(s.last_had_proxy_authz())
  19585. << "Proxy-Authorization must not be sent direct to the target";
  19586. }
  19587. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  19588. ProxyAndTargetServers s;
  19589. auto cli = make_client("public.example", s);
  19590. cli->set_proxy_basic_auth("u", "p");
  19591. cli->set_no_proxy({"internal.corp"}); // does not match
  19592. auto res = cli->Get("/");
  19593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19594. EXPECT_GE(s.proxy_hits(), 1);
  19595. EXPECT_TRUE(s.last_had_proxy_authz());
  19596. }
  19597. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  19598. ProxyAndTargetServers s;
  19599. auto cli = make_client("anything.test", s);
  19600. auto res = cli->Get("/");
  19601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19602. EXPECT_GE(s.proxy_hits(), 1);
  19603. EXPECT_EQ(0, s.target_hits());
  19604. }
  19605. TEST(NoProxyTest, PortSpecificEntryRejected) {
  19606. ProxyAndTargetServers s;
  19607. auto cli = make_client("example.com", s);
  19608. cli->set_no_proxy({"example.com:8080"});
  19609. auto res = cli->Get("/");
  19610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19611. EXPECT_GE(s.proxy_hits(), 1);
  19612. EXPECT_EQ(0, s.target_hits());
  19613. }
  19614. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  19615. ProxyAndTargetServers s;
  19616. auto cli = make_client("anything.test", s);
  19617. cli->set_no_proxy({"", " ", "\t"});
  19618. auto res = cli->Get("/");
  19619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19620. EXPECT_GE(s.proxy_hits(), 1);
  19621. EXPECT_EQ(0, s.target_hits());
  19622. }
  19623. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  19624. // An entry with leading/trailing whitespace must still match — env-style
  19625. // values are commonly pasted with stray spaces and an implementation
  19626. // that feeds the raw token directly to inet_pton would fail to match
  19627. // valid CIDRs because of the spaces.
  19628. ProxyAndTargetServers s;
  19629. Client cli("127.0.0.1", s.target_port());
  19630. cli.set_proxy("127.0.0.1", s.proxy_port());
  19631. cli.set_no_proxy({" 127.0.0.0/8 "});
  19632. auto res = cli.Get("/");
  19633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19634. EXPECT_EQ(0, s.proxy_hits());
  19635. EXPECT_EQ(1, s.target_hits());
  19636. }
  19637. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  19638. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  19639. // go direct and must NOT carry Proxy-Authorization.
  19640. std::atomic<int> proxy_hits{0};
  19641. std::atomic<int> target_hits{0};
  19642. std::atomic<bool> target_saw_authz{false};
  19643. no_proxy_test::ScopedServer proxy_mock, target;
  19644. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19645. proxy_hits++;
  19646. res.status = 302;
  19647. res.set_header("Location", "http://127.0.0.1:" +
  19648. std::to_string(target.port()) + "/landed");
  19649. });
  19650. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19651. target_hits++;
  19652. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  19653. res.set_content("direct", "text/plain");
  19654. });
  19655. proxy_mock.listen();
  19656. target.listen();
  19657. Client cli("public.example", target.port());
  19658. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19659. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19660. cli.set_proxy_basic_auth("u", "p");
  19661. cli.set_no_proxy({"127.0.0.1"});
  19662. cli.set_follow_location(true);
  19663. auto res = cli.Get("/redir");
  19664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19665. EXPECT_GE(proxy_hits.load(), 1);
  19666. EXPECT_GE(target_hits.load(), 1);
  19667. EXPECT_FALSE(target_saw_authz.load());
  19668. }
  19669. #ifdef CPPHTTPLIB_SSL_ENABLED
  19670. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  19671. // Direct origin replying 407 must not trigger the digest retry; otherwise
  19672. // proxy creds would be sent to the (possibly hostile) origin.
  19673. std::atomic<int> target_hits{0};
  19674. std::atomic<bool> target_saw_proxy_authz{false};
  19675. no_proxy_test::ScopedServer target;
  19676. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19677. target_hits++;
  19678. if (req.has_header("Proxy-Authorization")) {
  19679. target_saw_proxy_authz = true;
  19680. }
  19681. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19682. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  19683. "nonce=\"abc\", algorithm=MD5");
  19684. });
  19685. target.listen();
  19686. // The proxy address is set to the target's port: the bypass MUST kick in;
  19687. // if it doesn't, the test still routes "via proxy" to the same server and
  19688. // the Proxy-Authorization assertion below catches the leak.
  19689. Client cli("evil.example", target.port());
  19690. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  19691. cli.set_proxy("127.0.0.1", target.port());
  19692. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19693. cli.set_no_proxy({"evil.example"});
  19694. auto res = cli.Get("/x");
  19695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19696. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19697. EXPECT_EQ(1, target_hits.load());
  19698. EXPECT_FALSE(target_saw_proxy_authz.load());
  19699. }
  19700. #endif
  19701. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  19702. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  19703. std::atomic<int> proxy_hits{0};
  19704. std::atomic<int> bypass_hits{0};
  19705. std::atomic<bool> proxy_saw_c_url{false};
  19706. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  19707. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  19708. proxy_hits++;
  19709. if (req.path.find("/start") != std::string::npos) {
  19710. res.status = 302;
  19711. res.set_header("Location", "http://127.0.0.1:" +
  19712. std::to_string(bypass_server.port()) +
  19713. "/middle");
  19714. return;
  19715. }
  19716. if (req.path.find("/end") != std::string::npos) {
  19717. proxy_saw_c_url = true;
  19718. res.set_content("c-via-proxy", "text/plain");
  19719. return;
  19720. }
  19721. res.set_content("unexpected", "text/plain");
  19722. });
  19723. // public.example's "advertised" port is arbitrary (the request never lands
  19724. // there — it goes through the proxy), but use a dynamic value to stay
  19725. // friendly with sharded parallel runs.
  19726. int public_port = bypass_server.port();
  19727. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  19728. bypass_hits++;
  19729. res.status = 302;
  19730. res.set_header("Location", "http://public.example:" +
  19731. std::to_string(public_port) + "/end");
  19732. });
  19733. proxy_mock.listen();
  19734. bypass_server.listen();
  19735. Client cli("public.example", public_port);
  19736. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19737. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19738. cli.set_no_proxy({"127.0.0.1"});
  19739. cli.set_follow_location(true);
  19740. auto res = cli.Get("/start");
  19741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19742. EXPECT_EQ(StatusCode::OK_200, res->status);
  19743. EXPECT_EQ("c-via-proxy", res->body);
  19744. EXPECT_GE(proxy_hits.load(), 2);
  19745. EXPECT_GE(bypass_hits.load(), 1);
  19746. EXPECT_TRUE(proxy_saw_c_url.load());
  19747. }
  19748. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  19749. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  19750. // request reconnects to the correct endpoint.
  19751. std::atomic<int> proxy_hits{0};
  19752. std::atomic<int> target_hits{0};
  19753. no_proxy_test::ScopedServer proxy_mock, target;
  19754. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19755. proxy_hits++;
  19756. res.set_content("via-proxy", "text/plain");
  19757. });
  19758. target.svr().Get(".*", [&](const Request &, Response &res) {
  19759. target_hits++;
  19760. res.set_content("direct", "text/plain");
  19761. });
  19762. proxy_mock.listen();
  19763. target.listen();
  19764. Client cli("public.example", target.port());
  19765. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19766. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19767. cli.set_keep_alive(true);
  19768. auto res1 = cli.Get("/a");
  19769. ASSERT_TRUE(res1);
  19770. EXPECT_EQ("via-proxy", res1->body);
  19771. EXPECT_EQ(1, proxy_hits.load());
  19772. EXPECT_EQ(0, target_hits.load());
  19773. cli.set_no_proxy({"public.example"});
  19774. auto res2 = cli.Get("/b");
  19775. ASSERT_TRUE(res2);
  19776. EXPECT_EQ("direct", res2->body);
  19777. EXPECT_EQ(1, proxy_hits.load());
  19778. EXPECT_EQ(1, target_hits.load());
  19779. }
  19780. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  19781. namespace proxy_tunnel_test {
  19782. // SSLServer counterpart to no_proxy_test::ScopedServer.
  19783. class ScopedSSLServer {
  19784. public:
  19785. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  19786. port_ = svr_.bind_to_any_port("127.0.0.1");
  19787. }
  19788. ~ScopedSSLServer() {
  19789. svr_.stop();
  19790. if (th_.joinable()) { th_.join(); }
  19791. }
  19792. SSLServer &svr() { return svr_; }
  19793. int port() const { return port_; }
  19794. void listen() {
  19795. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19796. svr_.wait_until_ready();
  19797. }
  19798. private:
  19799. SSLServer svr_;
  19800. std::thread th_;
  19801. int port_ = 0;
  19802. };
  19803. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  19804. class ScopedConnectProxy {
  19805. public:
  19806. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  19807. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  19808. if (listen_fd_ < 0) { return; }
  19809. int yes = 1;
  19810. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  19811. sockaddr_in a{};
  19812. a.sin_family = AF_INET;
  19813. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19814. a.sin_port = 0;
  19815. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  19816. return;
  19817. }
  19818. socklen_t alen = sizeof(a);
  19819. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  19820. 0) {
  19821. return;
  19822. }
  19823. port_ = ntohs(a.sin_port);
  19824. if (::listen(listen_fd_, 1) != 0) { return; }
  19825. th_ = std::thread([this] { run(); });
  19826. }
  19827. ~ScopedConnectProxy() {
  19828. stop_ = true;
  19829. if (listen_fd_ >= 0) {
  19830. ::shutdown(listen_fd_, SHUT_RDWR);
  19831. ::close(listen_fd_);
  19832. }
  19833. if (th_.joinable()) { th_.join(); }
  19834. }
  19835. int port() const { return port_; }
  19836. int connect_hits() const { return connect_hits_.load(); }
  19837. private:
  19838. void run() {
  19839. while (!stop_.load()) {
  19840. fd_set rfds;
  19841. FD_ZERO(&rfds);
  19842. FD_SET(listen_fd_, &rfds);
  19843. timeval tv{0, 100 * 1000};
  19844. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  19845. if (sel <= 0) { continue; }
  19846. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  19847. if (client_fd < 0) { continue; }
  19848. std::string req;
  19849. char buf[2048];
  19850. while (req.find("\r\n\r\n") == std::string::npos) {
  19851. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  19852. if (n <= 0) { break; }
  19853. req.append(buf, static_cast<size_t>(n));
  19854. }
  19855. if (req.compare(0, 7, "CONNECT") != 0) {
  19856. ::close(client_fd);
  19857. continue;
  19858. }
  19859. connect_hits_++;
  19860. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  19861. ::send(client_fd, ok, std::strlen(ok), 0);
  19862. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  19863. sockaddr_in o{};
  19864. o.sin_family = AF_INET;
  19865. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19866. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  19867. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  19868. 0) {
  19869. ::close(client_fd);
  19870. ::close(origin_fd);
  19871. continue;
  19872. }
  19873. auto forward = [](int from, int to) {
  19874. char b[8192];
  19875. for (;;) {
  19876. ssize_t n = ::recv(from, b, sizeof(b), 0);
  19877. if (n <= 0) { break; }
  19878. ssize_t off = 0;
  19879. while (off < n) {
  19880. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  19881. if (s <= 0) {
  19882. off = n;
  19883. break;
  19884. }
  19885. off += s;
  19886. }
  19887. }
  19888. ::shutdown(to, SHUT_WR);
  19889. };
  19890. std::thread t1([&] { forward(client_fd, origin_fd); });
  19891. std::thread t2([&] { forward(origin_fd, client_fd); });
  19892. t1.join();
  19893. t2.join();
  19894. ::close(client_fd);
  19895. ::close(origin_fd);
  19896. }
  19897. }
  19898. int forward_port_ = -1;
  19899. int listen_fd_ = -1;
  19900. int port_ = 0;
  19901. std::thread th_;
  19902. std::atomic<bool> stop_{false};
  19903. std::atomic<int> connect_hits_{0};
  19904. };
  19905. } // namespace proxy_tunnel_test
  19906. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  19907. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  19908. // retry; otherwise proxy creds would be sent to the origin.
  19909. std::atomic<int> origin_hits{0};
  19910. std::atomic<bool> origin_saw_proxy_authz{false};
  19911. proxy_tunnel_test::ScopedSSLServer origin;
  19912. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  19913. origin_hits++;
  19914. if (req.has_header("Proxy-Authorization")) {
  19915. origin_saw_proxy_authz = true;
  19916. }
  19917. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19918. res.set_header("Proxy-Authenticate",
  19919. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  19920. "algorithm=MD5");
  19921. });
  19922. origin.listen();
  19923. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  19924. ASSERT_NE(0, proxy.port());
  19925. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  19926. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  19927. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  19928. // and answer with its own status, making this test flaky.
  19929. SSLClient cli("127.0.0.1", origin.port());
  19930. cli.enable_server_certificate_verification(false);
  19931. cli.set_proxy("127.0.0.1", proxy.port());
  19932. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19933. auto res = cli.Get("/x");
  19934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19935. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19936. EXPECT_EQ(1, origin_hits.load());
  19937. EXPECT_FALSE(origin_saw_proxy_authz.load());
  19938. EXPECT_EQ(1, proxy.connect_hits());
  19939. }
  19940. #endif