test.cc 810 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // Empty quality value
  892. EXPECT_FALSE(
  893. detail::parse_accept_header("text/html;q=,application/json", result));
  894. // Invalid media type format (no slash and not wildcard)
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("invalidtype,application/json", result));
  897. // Valid cases should still work
  898. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  899. EXPECT_EQ(result.size(), 1U);
  900. EXPECT_EQ(result[0], "*/*");
  901. EXPECT_TRUE(detail::parse_accept_header("*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*");
  904. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "text/*");
  907. }
  908. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  909. // elements, so a leading, trailing or doubled comma is a legal Accept value
  910. // and must not be answered with 400 Bad Request.
  911. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  912. struct {
  913. const char *value;
  914. std::vector<std::string> expected;
  915. } cases[] = {
  916. {",application/json", {"application/json"}},
  917. {"text/html,", {"text/html"}},
  918. {"text/html,,*/*", {"text/html", "*/*"}},
  919. // An empty element may be spelled with whitespace in it
  920. {"text/html, , application/json", {"text/html", "application/json"}},
  921. // Nothing but empty elements is an empty list, which means the same
  922. // thing as no Accept header at all
  923. {",,,", {}},
  924. // Quality values still apply across ignored empty elements
  925. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  926. };
  927. for (const auto &c : cases) {
  928. std::vector<std::string> result;
  929. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  930. << "value: " << c.value;
  931. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  932. }
  933. // An invalid entry is still rejected when empty elements surround it
  934. std::vector<std::string> result;
  935. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  936. }
  937. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  938. Server svr;
  939. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  940. EXPECT_EQ(req.accept_content_types.size(), 3U);
  941. EXPECT_EQ(req.accept_content_types[0], "application/json");
  942. EXPECT_EQ(req.accept_content_types[1], "text/html");
  943. EXPECT_EQ(req.accept_content_types[2], "*/*");
  944. res.set_content("ok", "text/plain");
  945. });
  946. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  947. EXPECT_TRUE(false);
  948. res.set_content("bad request", "text/plain");
  949. });
  950. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  951. auto se = detail::scope_exit([&] {
  952. svr.stop();
  953. listen_thread.join();
  954. ASSERT_FALSE(svr.is_running());
  955. });
  956. svr.wait_until_ready();
  957. Client cli("localhost", PORT);
  958. {
  959. auto res = cli.Get(
  960. "/accept_ok",
  961. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  963. EXPECT_EQ(StatusCode::OK_200, res->status);
  964. }
  965. {
  966. auto res = cli.Get("/accept_bad_request",
  967. Headers{{"Accept", "text/html;q=abc,application/json"}});
  968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  969. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  970. }
  971. }
  972. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  973. Server svr;
  974. svr.Get("/", [](const Request & /*req*/, Response &res) {
  975. res.set_content("ok", "text/plain");
  976. });
  977. std::atomic<int> start_count{0};
  978. std::atomic<bool> running_when_called{false};
  979. svr.set_start_handler([&]() {
  980. running_when_called = svr.is_running();
  981. start_count++;
  982. });
  983. auto port = svr.bind_to_any_port(HOST);
  984. std::thread t([&]() { svr.listen_after_bind(); });
  985. auto se = detail::scope_exit([&] {
  986. svr.stop();
  987. t.join();
  988. ASSERT_FALSE(svr.is_running());
  989. });
  990. svr.wait_until_ready();
  991. // A successful request proves the accept loop is running, which the start
  992. // handler precedes; so by now the handler must have run exactly once.
  993. Client cli(HOST, port);
  994. cli.set_connection_timeout(std::chrono::seconds(5));
  995. auto res = cli.Get("/");
  996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  997. EXPECT_EQ(StatusCode::OK_200, res->status);
  998. EXPECT_EQ(1, start_count.load());
  999. EXPECT_TRUE(running_when_called.load());
  1000. }
  1001. TEST(DivideTest, DivideStringTests) {
  1002. auto divide = [](const std::string &str, char d) {
  1003. std::string lhs;
  1004. std::string rhs;
  1005. detail::divide(str, d,
  1006. [&](const char *lhs_data, std::size_t lhs_size,
  1007. const char *rhs_data, std::size_t rhs_size) {
  1008. lhs.assign(lhs_data, lhs_size);
  1009. rhs.assign(rhs_data, rhs_size);
  1010. });
  1011. return std::make_pair(std::move(lhs), std::move(rhs));
  1012. };
  1013. {
  1014. const auto res = divide("", '=');
  1015. EXPECT_EQ(res.first, "");
  1016. EXPECT_EQ(res.second, "");
  1017. }
  1018. {
  1019. const auto res = divide("=", '=');
  1020. EXPECT_EQ(res.first, "");
  1021. EXPECT_EQ(res.second, "");
  1022. }
  1023. {
  1024. const auto res = divide(" ", '=');
  1025. EXPECT_EQ(res.first, " ");
  1026. EXPECT_EQ(res.second, "");
  1027. }
  1028. {
  1029. const auto res = divide("a", '=');
  1030. EXPECT_EQ(res.first, "a");
  1031. EXPECT_EQ(res.second, "");
  1032. }
  1033. {
  1034. const auto res = divide("a=", '=');
  1035. EXPECT_EQ(res.first, "a");
  1036. EXPECT_EQ(res.second, "");
  1037. }
  1038. {
  1039. const auto res = divide("=b", '=');
  1040. EXPECT_EQ(res.first, "");
  1041. EXPECT_EQ(res.second, "b");
  1042. }
  1043. {
  1044. const auto res = divide("a=b", '=');
  1045. EXPECT_EQ(res.first, "a");
  1046. EXPECT_EQ(res.second, "b");
  1047. }
  1048. {
  1049. const auto res = divide("a=b=", '=');
  1050. EXPECT_EQ(res.first, "a");
  1051. EXPECT_EQ(res.second, "b=");
  1052. }
  1053. {
  1054. const auto res = divide("a=b=c", '=');
  1055. EXPECT_EQ(res.first, "a");
  1056. EXPECT_EQ(res.second, "b=c");
  1057. }
  1058. }
  1059. TEST(SplitTest, ParseQueryString) {
  1060. string s = "key1=val1&key2=val2&key3=val3";
  1061. Params dic;
  1062. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1063. [&](const char *b, const char *e) {
  1064. string key, val;
  1065. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1066. if (key.empty()) {
  1067. key.assign(b2, e2);
  1068. } else {
  1069. val.assign(b2, e2);
  1070. }
  1071. });
  1072. dic.emplace(key, val);
  1073. });
  1074. EXPECT_EQ("val1", dic.find("key1")->second);
  1075. EXPECT_EQ("val2", dic.find("key2")->second);
  1076. EXPECT_EQ("val3", dic.find("key3")->second);
  1077. }
  1078. TEST(SplitTest, ParseInvalidQueryTests) {
  1079. {
  1080. string s = " ";
  1081. Params dict;
  1082. detail::parse_query_text(s, dict);
  1083. EXPECT_TRUE(dict.empty());
  1084. }
  1085. {
  1086. string s = " = =";
  1087. Params dict;
  1088. detail::parse_query_text(s, dict);
  1089. EXPECT_TRUE(dict.empty());
  1090. }
  1091. }
  1092. TEST(ParseQueryTest, ParseQueryString) {
  1093. {
  1094. std::string s = "key1=val1&key2=val2&key3=val3";
  1095. Params dic;
  1096. detail::parse_query_text(s, dic);
  1097. EXPECT_EQ("val1", dic.find("key1")->second);
  1098. EXPECT_EQ("val2", dic.find("key2")->second);
  1099. EXPECT_EQ("val3", dic.find("key3")->second);
  1100. }
  1101. {
  1102. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1103. Params dic;
  1104. detail::parse_query_text(s, dic);
  1105. EXPECT_EQ("", dic.find("key1")->second);
  1106. EXPECT_EQ("val1", dic.find("key2")->second);
  1107. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1108. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1109. }
  1110. }
  1111. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1112. Params dic;
  1113. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1114. dic.emplace("key1", "val1");
  1115. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1116. dic.emplace("key2", "val2");
  1117. dic.emplace("key3", "val3");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1119. }
  1120. // Joins every entry of a Headers or Params into "key=value " so a whole
  1121. // traversal can be compared in one assertion. Both are instantiations of the
  1122. // same insertion-ordered container, so one helper serves both.
  1123. template <typename Map> static std::string entries_to_string(const Map &m) {
  1124. std::string s;
  1125. for (const auto &entry : m) {
  1126. s += entry.first + "=" + entry.second + " ";
  1127. }
  1128. return s;
  1129. }
  1130. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1131. // Params used to be a std::multimap, which sorted by name and handed the
  1132. // caller's query back alphabetised. A client signing its query string could
  1133. // not reproduce the order it asked for.
  1134. Params dic;
  1135. dic.emplace("zulu", "1");
  1136. dic.emplace("alpha", "2");
  1137. dic.emplace("mike", "3");
  1138. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1139. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1140. }
  1141. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1142. Params dic;
  1143. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1144. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1145. }
  1146. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1147. Request req;
  1148. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1149. req.params);
  1150. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1151. EXPECT_EQ("first", req.get_param_value("tag"));
  1152. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1153. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1154. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1155. EXPECT_EQ("", req.get_param_value("tag", 3));
  1156. }
  1157. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1158. // Params shares its container with Headers, which matches field names
  1159. // case-insensitively. Parameter names must not pick that up.
  1160. Params dic;
  1161. dic.emplace("Key", "upper");
  1162. dic.emplace("key", "lower");
  1163. EXPECT_EQ(2U, dic.size());
  1164. EXPECT_EQ(1U, dic.count("Key"));
  1165. EXPECT_EQ(1U, dic.count("key"));
  1166. EXPECT_EQ("upper", dic.find("Key")->second);
  1167. EXPECT_EQ("lower", dic.find("key")->second);
  1168. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1169. }
  1170. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1171. Server svr;
  1172. std::string order;
  1173. svr.Get("/order", [&](const Request &req, Response &res) {
  1174. order = entries_to_string(req.params);
  1175. res.set_content("ok", "text/plain");
  1176. });
  1177. auto port = svr.bind_to_any_port(HOST);
  1178. thread t = thread([&] { svr.listen_after_bind(); });
  1179. auto se = detail::scope_exit([&] {
  1180. svr.stop();
  1181. t.join();
  1182. ASSERT_FALSE(svr.is_running());
  1183. });
  1184. svr.wait_until_ready();
  1185. Client cli(HOST, port);
  1186. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1187. ASSERT_TRUE(res);
  1188. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1189. }
  1190. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1191. Server svr;
  1192. std::string field_order, file_order;
  1193. svr.Post("/order", [&](const Request &req, Response &res) {
  1194. for (const auto &field : req.form.fields) {
  1195. field_order += field.first + "=" + field.second.content + " ";
  1196. }
  1197. for (const auto &file : req.form.files) {
  1198. file_order += file.first + "=" + file.second.filename + " ";
  1199. }
  1200. res.set_content("ok", "text/plain");
  1201. });
  1202. auto port = svr.bind_to_any_port(HOST);
  1203. thread t = thread([&] { svr.listen_after_bind(); });
  1204. auto se = detail::scope_exit([&] {
  1205. svr.stop();
  1206. t.join();
  1207. ASSERT_FALSE(svr.is_running());
  1208. });
  1209. svr.wait_until_ready();
  1210. UploadFormDataItems items = {
  1211. {"zulu", "1", "", ""},
  1212. {"alpha", "2", "", ""},
  1213. {"mike", "3", "", ""},
  1214. {"zebra", "z", "z.txt", "text/plain"},
  1215. {"apple", "a", "a.txt", "text/plain"},
  1216. };
  1217. Client cli(HOST, port);
  1218. auto res = cli.Post("/order", items);
  1219. ASSERT_TRUE(res);
  1220. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1221. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1222. }
  1223. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1224. Server svr;
  1225. std::vector<std::string> values;
  1226. std::string first, second, out_of_range, order;
  1227. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1228. values = req.form.get_fields("tag");
  1229. first = req.form.get_field("tag", 0);
  1230. second = req.form.get_field("tag", 1);
  1231. out_of_range = req.form.get_field("tag", 2);
  1232. for (const auto &field : req.form.fields) {
  1233. order += field.first + "=" + field.second.content + " ";
  1234. }
  1235. res.set_content("ok", "text/plain");
  1236. });
  1237. auto port = svr.bind_to_any_port(HOST);
  1238. thread t = thread([&] { svr.listen_after_bind(); });
  1239. auto se = detail::scope_exit([&] {
  1240. svr.stop();
  1241. t.join();
  1242. ASSERT_FALSE(svr.is_running());
  1243. });
  1244. svr.wait_until_ready();
  1245. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1246. // not adjacent in the container.
  1247. UploadFormDataItems items = {
  1248. {"tag", "first", "", ""},
  1249. {"other", "x", "", ""},
  1250. {"tag", "second", "", ""},
  1251. };
  1252. Client cli(HOST, port);
  1253. auto res = cli.Post("/repeated", items);
  1254. ASSERT_TRUE(res);
  1255. ASSERT_EQ(2U, values.size());
  1256. EXPECT_EQ("first", values[0]);
  1257. EXPECT_EQ("second", values[1]);
  1258. EXPECT_EQ("first", first);
  1259. EXPECT_EQ("second", second);
  1260. // std::multimap already kept entries sharing a name in insertion order, so
  1261. // everything above passes without this change too. The whole traversal is
  1262. // what tells the two apart: sorting by name would hoist "other" to the front
  1263. // and the two "tag" parts would end up adjacent.
  1264. EXPECT_EQ("tag=first other=x tag=second ", order);
  1265. // Advancing past the last entry of a name used to run off the container;
  1266. // the container's saturating increment makes it return the default instead.
  1267. EXPECT_EQ("", out_of_range);
  1268. }
  1269. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1270. // Server::read_content() keeps a FormFields::iterator alive across the
  1271. // content callbacks that fill the part it points at. The container is
  1272. // vector-backed, so a later emplace can reallocate and invalidate an older
  1273. // iterator; 64 parts grow the vector through seven reallocations, which
  1274. // checks that every part's content still lands in its own entry.
  1275. const size_t part_count = 64;
  1276. // One formula for both the parts sent and the values expected back, so the
  1277. // two cannot drift apart.
  1278. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1279. auto content_of = [](size_t i) {
  1280. return std::string(64, static_cast<char>('a' + (i % 26)));
  1281. };
  1282. Server svr;
  1283. std::vector<std::pair<std::string, std::string>> received;
  1284. svr.Post("/many", [&](const Request &req, Response &res) {
  1285. for (const auto &field : req.form.fields) {
  1286. received.emplace_back(field.first, field.second.content);
  1287. }
  1288. res.set_content("ok", "text/plain");
  1289. });
  1290. auto port = svr.bind_to_any_port(HOST);
  1291. thread t = thread([&] { svr.listen_after_bind(); });
  1292. auto se = detail::scope_exit([&] {
  1293. svr.stop();
  1294. t.join();
  1295. ASSERT_FALSE(svr.is_running());
  1296. });
  1297. svr.wait_until_ready();
  1298. UploadFormDataItems items;
  1299. for (size_t i = 0; i < part_count; i++) {
  1300. items.push_back({name_of(i), content_of(i), "", ""});
  1301. }
  1302. Client cli(HOST, port);
  1303. auto res = cli.Post("/many", items);
  1304. ASSERT_TRUE(res);
  1305. ASSERT_EQ(part_count, received.size());
  1306. for (size_t i = 0; i < part_count; i++) {
  1307. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1308. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1309. }
  1310. }
  1311. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1312. string content_type = "multipart/form-data; boundary=something";
  1313. string boundary;
  1314. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1315. EXPECT_TRUE(ret);
  1316. EXPECT_EQ(boundary, "something");
  1317. }
  1318. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1319. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1320. string boundary;
  1321. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1322. EXPECT_TRUE(ret);
  1323. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1324. }
  1325. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1326. string content_type =
  1327. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1328. string boundary;
  1329. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1330. EXPECT_TRUE(ret);
  1331. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1332. }
  1333. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1334. string content_type =
  1335. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1336. string boundary;
  1337. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1338. EXPECT_TRUE(ret);
  1339. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1340. }
  1341. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1342. const string boundary(70, 'a');
  1343. string content_type = "multipart/form-data; boundary=" + boundary;
  1344. string parsed;
  1345. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1346. EXPECT_TRUE(ret);
  1347. EXPECT_EQ(parsed, boundary);
  1348. }
  1349. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1350. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1351. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1352. string parsed;
  1353. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1354. EXPECT_FALSE(ret);
  1355. }
  1356. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1357. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1358. // is 72 characters on the wire and still valid.
  1359. const string boundary(70, 'a');
  1360. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1361. string parsed;
  1362. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1363. EXPECT_EQ(parsed, boundary);
  1364. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1365. parsed.clear();
  1366. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1367. }
  1368. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1369. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1370. // The parameter parser must not treat that '=' as the key/value separator.
  1371. string content_type =
  1372. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1373. "charset=UTF-8";
  1374. string parsed;
  1375. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1376. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1377. }
  1378. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1379. // A ';' inside the quoted-string is part of the value, not a parameter
  1380. // separator, so it must not truncate the boundary.
  1381. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1382. string parsed;
  1383. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1384. EXPECT_EQ(parsed, "a;b");
  1385. }
  1386. TEST(ParseDispositionParamsTest, QuotedValues) {
  1387. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1388. // ';' and '=' are ordinary characters inside one.
  1389. struct {
  1390. const char *value;
  1391. std::vector<std::pair<const char *, const char *>> expected;
  1392. } cases[] = {
  1393. {"name=\"file1\"; filename=\"a.txt\"",
  1394. {{"name", "file1"}, {"filename", "a.txt"}}},
  1395. // Whitespace around '=' and ';' is still trimmed
  1396. {"name=\"file2\" ;filename = \"a.html\"",
  1397. {{"name", "file2"}, {"filename", "a.html"}}},
  1398. // '=' inside the value used to leave only the text after the last one
  1399. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1400. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1401. {"name=\"x=y\"", {{"name", "x=y"}}},
  1402. // ';' inside the value used to truncate the pair and leave a bogus one
  1403. {"name=\"file3\"; filename=\"a;b.txt\"",
  1404. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1405. // An unquoted value keeps working, and so does filename*
  1406. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1407. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1408. // A parameter with no key is dropped rather than turned into one whose
  1409. // key is the value
  1410. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1411. };
  1412. for (const auto &c : cases) {
  1413. Params params;
  1414. detail::parse_disposition_params(c.value, params);
  1415. for (const auto &kv : c.expected) {
  1416. auto it = params.find(kv.first);
  1417. ASSERT_NE(it, params.end())
  1418. << "value: " << c.value << ", key: " << kv.first;
  1419. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1420. }
  1421. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1422. }
  1423. }
  1424. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1425. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1426. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1427. Server svr;
  1428. std::string field_value, file_name, file_filename;
  1429. bool has_field = false, has_file = false;
  1430. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1431. has_field = req.form.has_field("x=y");
  1432. field_value = req.form.get_field("x=y");
  1433. has_file = req.form.has_file("file1");
  1434. const auto &file = req.form.get_file("file1");
  1435. file_name = file.name;
  1436. file_filename = file.filename;
  1437. res.set_content("ok", "text/plain");
  1438. });
  1439. auto port = svr.bind_to_any_port(HOST);
  1440. thread t = thread([&] { svr.listen_after_bind(); });
  1441. auto se = detail::scope_exit([&] {
  1442. svr.stop();
  1443. t.join();
  1444. ASSERT_FALSE(svr.is_running());
  1445. });
  1446. svr.wait_until_ready();
  1447. UploadFormDataItems items = {
  1448. {"x=y", "field-value", "", ""},
  1449. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1450. };
  1451. Client cli(HOST, port);
  1452. auto res = cli.Post("/quoted", items);
  1453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1454. ASSERT_EQ(StatusCode::OK_200, res->status);
  1455. EXPECT_TRUE(has_field);
  1456. EXPECT_EQ("field-value", field_value);
  1457. EXPECT_TRUE(has_file);
  1458. EXPECT_EQ("file1", file_name);
  1459. EXPECT_EQ("a;b=report.pdf", file_filename);
  1460. }
  1461. TEST(GetHeaderValueTest, DefaultValue) {
  1462. Headers headers = {{"Dummy", "Dummy"}};
  1463. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1464. EXPECT_STREQ("text/plain", val);
  1465. }
  1466. TEST(GetHeaderValueTest, DefaultValueInt) {
  1467. Headers headers = {{"Dummy", "Dummy"}};
  1468. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1469. EXPECT_EQ(100ull, val);
  1470. }
  1471. TEST(GetHeaderValueTest, RegularValue) {
  1472. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1473. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1474. EXPECT_STREQ("text/html", val);
  1475. }
  1476. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1477. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1478. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1479. EXPECT_STREQ("text/html", val);
  1480. }
  1481. TEST(GetHeaderValueTest, SetContent) {
  1482. Response res;
  1483. res.set_content("html", "text/html");
  1484. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1485. res.set_content("text", "text/plain");
  1486. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1487. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1488. }
  1489. TEST(GetHeaderValueTest, RegularValueInt) {
  1490. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1491. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1492. EXPECT_EQ(100ull, val);
  1493. }
  1494. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1495. Headers headers = {{"Content-Length", "x"}};
  1496. auto is_invalid_value = false;
  1497. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1498. is_invalid_value);
  1499. EXPECT_EQ(0ull, val);
  1500. EXPECT_TRUE(is_invalid_value);
  1501. }
  1502. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1503. // An all-digit value that overflows size_t must be reported as invalid, not
  1504. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1505. // a large length to a small one on 32-bit builds, leaving the framing length
  1506. // wrong while is_invalid_value stayed false.
  1507. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1508. auto is_invalid_value = false;
  1509. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1510. is_invalid_value);
  1511. EXPECT_TRUE(is_invalid_value);
  1512. // A well-formed length is unaffected.
  1513. Headers ok = {{"Content-Length", "1234"}};
  1514. is_invalid_value = false;
  1515. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1516. is_invalid_value);
  1517. EXPECT_EQ(1234ull, val);
  1518. EXPECT_FALSE(is_invalid_value);
  1519. }
  1520. TEST(GetHeaderValueTest, Range) {
  1521. {
  1522. Headers headers = {make_range_header({{1, -1}})};
  1523. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1524. EXPECT_STREQ("bytes=1-", val);
  1525. }
  1526. {
  1527. Headers headers = {make_range_header({{-1, 1}})};
  1528. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1529. EXPECT_STREQ("bytes=-1", val);
  1530. }
  1531. {
  1532. Headers headers = {make_range_header({{1, 10}})};
  1533. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1534. EXPECT_STREQ("bytes=1-10", val);
  1535. }
  1536. {
  1537. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1538. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1539. EXPECT_STREQ("bytes=1-10, 100-", val);
  1540. }
  1541. {
  1542. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1543. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1544. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1545. }
  1546. {
  1547. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1548. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1549. EXPECT_STREQ("bytes=0-0, -1", val);
  1550. }
  1551. }
  1552. TEST(BearerTokenAuthTest, SchemeValidation) {
  1553. // A value shorter than "Bearer " must not throw from the fixed-length
  1554. // substr, and a non-Bearer scheme must not be reported as a token.
  1555. struct {
  1556. const char *value;
  1557. const char *expected;
  1558. } cases[] = {
  1559. {"x", ""},
  1560. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1561. {"Bearer abc123", "abc123"},
  1562. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1563. };
  1564. for (const auto &c : cases) {
  1565. Request req;
  1566. req.set_header("Authorization", c.value);
  1567. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1568. }
  1569. }
  1570. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1571. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1572. // to depend on the standard library (libstdc++ handed back duplicates in
  1573. // reverse insertion order, libc++ in insertion order).
  1574. Request req;
  1575. req.set_header("Accept-Encoding", "gzip");
  1576. req.set_header("Accept-Encoding", "deflate");
  1577. req.set_header("Accept-Encoding", "br");
  1578. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1579. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1580. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1581. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1582. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1583. }
  1584. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1585. Request req;
  1586. req.set_header("X-Test", "only");
  1587. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1588. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1589. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1590. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1591. }
  1592. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1593. Headers headers;
  1594. headers.emplace("Host", "example.com");
  1595. headers.emplace("Accept-Encoding", "gzip");
  1596. headers.emplace("User-Agent", "test");
  1597. headers.emplace("Accept-Encoding", "deflate");
  1598. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1599. "Accept-Encoding=deflate ",
  1600. entries_to_string(headers));
  1601. }
  1602. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1603. Headers headers = {{"Content-Type", "text/html"},
  1604. {"CONTENT-TYPE", "text/xml"}};
  1605. EXPECT_EQ(2U, headers.count("content-type"));
  1606. auto it = headers.find("content-type");
  1607. ASSERT_TRUE(it != headers.end());
  1608. EXPECT_EQ("text/html", it->second);
  1609. }
  1610. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1611. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1612. // drop only those fields and leave everything positioned between them.
  1613. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1614. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1615. auto rng = headers.equal_range("a");
  1616. headers.erase(rng.first, rng.second);
  1617. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1618. }
  1619. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1620. Headers headers = {
  1621. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1622. EXPECT_EQ(3U, headers.erase("A"));
  1623. EXPECT_EQ(0U, headers.count("A"));
  1624. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1625. }
  1626. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1627. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1628. headers.emplace_front("Host", "example.com");
  1629. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1630. entries_to_string(headers));
  1631. }
  1632. TEST(ParseHeaderValueTest, Range) {
  1633. {
  1634. Ranges ranges;
  1635. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1636. EXPECT_TRUE(ret);
  1637. EXPECT_EQ(1u, ranges.size());
  1638. EXPECT_EQ(1u, ranges[0].first);
  1639. EXPECT_EQ(-1, ranges[0].second);
  1640. }
  1641. {
  1642. Ranges ranges;
  1643. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1644. EXPECT_TRUE(ret);
  1645. EXPECT_EQ(1u, ranges.size());
  1646. EXPECT_EQ(-1, ranges[0].first);
  1647. EXPECT_EQ(1u, ranges[0].second);
  1648. }
  1649. {
  1650. Ranges ranges;
  1651. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1652. EXPECT_TRUE(ret);
  1653. EXPECT_EQ(1u, ranges.size());
  1654. EXPECT_EQ(1u, ranges[0].first);
  1655. EXPECT_EQ(10u, ranges[0].second);
  1656. }
  1657. {
  1658. Ranges ranges;
  1659. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1660. EXPECT_FALSE(ret);
  1661. }
  1662. {
  1663. Ranges ranges;
  1664. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1665. EXPECT_TRUE(ret);
  1666. EXPECT_EQ(2u, ranges.size());
  1667. EXPECT_EQ(1u, ranges[0].first);
  1668. EXPECT_EQ(10u, ranges[0].second);
  1669. EXPECT_EQ(100u, ranges[1].first);
  1670. EXPECT_EQ(-1, ranges[1].second);
  1671. }
  1672. {
  1673. Ranges ranges;
  1674. auto ret =
  1675. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1676. EXPECT_TRUE(ret);
  1677. EXPECT_EQ(3u, ranges.size());
  1678. EXPECT_EQ(1u, ranges[0].first);
  1679. EXPECT_EQ(10u, ranges[0].second);
  1680. EXPECT_EQ(100u, ranges[1].first);
  1681. EXPECT_EQ(200u, ranges[1].second);
  1682. EXPECT_EQ(300u, ranges[2].first);
  1683. EXPECT_EQ(400u, ranges[2].second);
  1684. }
  1685. {
  1686. Ranges ranges;
  1687. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1688. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1689. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1690. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1700. EXPECT_TRUE(ranges.empty());
  1701. }
  1702. }
  1703. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1704. Request req;
  1705. req.set_header("Accept-Encoding", "gzip");
  1706. Response res;
  1707. res.set_header("Content-Type", "text/plain");
  1708. auto ret = detail::encoding_type(req, res);
  1709. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1710. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1711. #else
  1712. EXPECT_TRUE(ret == detail::EncodingType::None);
  1713. #endif
  1714. }
  1715. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1716. Request req;
  1717. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1718. Response res;
  1719. res.set_header("Content-Type", "text/plain");
  1720. auto ret = detail::encoding_type(req, res);
  1721. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1722. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1723. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1724. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1725. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1726. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1727. #else
  1728. EXPECT_TRUE(ret == detail::EncodingType::None);
  1729. #endif
  1730. }
  1731. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1732. Request req;
  1733. req.set_header("Accept-Encoding",
  1734. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1735. Response res;
  1736. res.set_header("Content-Type", "text/plain");
  1737. auto ret = detail::encoding_type(req, res);
  1738. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1739. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1740. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1741. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1742. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1743. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1744. #else
  1745. EXPECT_TRUE(ret == detail::EncodingType::None);
  1746. #endif
  1747. }
  1748. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1749. // All supported encodings rejected with q=0 should return None
  1750. Request req;
  1751. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1752. Response res;
  1753. res.set_header("Content-Type", "text/plain");
  1754. auto ret = detail::encoding_type(req, res);
  1755. EXPECT_TRUE(ret == detail::EncodingType::None);
  1756. }
  1757. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1758. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1759. Request req;
  1760. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1761. Response res;
  1762. res.set_header("Content-Type", "text/plain");
  1763. auto ret = detail::encoding_type(req, res);
  1764. EXPECT_TRUE(ret == detail::EncodingType::None);
  1765. }
  1766. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1767. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1768. Request req;
  1769. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1770. Response res;
  1771. res.set_header("Content-Type", "text/plain");
  1772. auto ret = detail::encoding_type(req, res);
  1773. EXPECT_TRUE(ret == detail::EncodingType::None);
  1774. }
  1775. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1776. // RFC 7231: Accept-Encoding values are case-insensitive
  1777. Request req;
  1778. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1779. Response res;
  1780. res.set_header("Content-Type", "text/plain");
  1781. auto ret = detail::encoding_type(req, res);
  1782. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1783. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1784. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1785. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1786. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1787. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1788. #else
  1789. EXPECT_TRUE(ret == detail::EncodingType::None);
  1790. #endif
  1791. }
  1792. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1793. // q value should determine priority, not hardcoded order
  1794. Request req;
  1795. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1796. Response res;
  1797. res.set_header("Content-Type", "text/plain");
  1798. auto ret = detail::encoding_type(req, res);
  1799. // gzip has highest q=1.0, so it should be selected even though
  1800. // br and zstd are also supported
  1801. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1802. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1803. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1804. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1805. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1806. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1807. #else
  1808. EXPECT_TRUE(ret == detail::EncodingType::None);
  1809. #endif
  1810. }
  1811. TEST(BufferStreamTest, read) {
  1812. detail::BufferStream strm1;
  1813. Stream &strm = strm1;
  1814. EXPECT_EQ(5, strm.write("hello"));
  1815. char buf[512];
  1816. EXPECT_EQ(2, strm.read(buf, 2));
  1817. EXPECT_EQ('h', buf[0]);
  1818. EXPECT_EQ('e', buf[1]);
  1819. EXPECT_EQ(2, strm.read(buf, 2));
  1820. EXPECT_EQ('l', buf[0]);
  1821. EXPECT_EQ('l', buf[1]);
  1822. EXPECT_EQ(1, strm.read(buf, 1));
  1823. EXPECT_EQ('o', buf[0]);
  1824. EXPECT_EQ(0, strm.read(buf, 1));
  1825. }
  1826. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1827. auto host = "www.httpwatch.com";
  1828. auto ip = hosted_at(host);
  1829. EXPECT_EQ("23.96.13.243", ip);
  1830. std::vector<std::string> addrs;
  1831. hosted_at(host, addrs);
  1832. EXPECT_EQ(1u, addrs.size());
  1833. }
  1834. #if 0 // It depends on each test environment...
  1835. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1836. auto host = "www.youtube.com";
  1837. std::vector<std::string> addrs;
  1838. hosted_at(host, addrs);
  1839. EXPECT_EQ(20u, addrs.size());
  1840. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1841. EXPECT_TRUE(it != addrs.end());
  1842. }
  1843. #endif
  1844. class ChunkedEncodingTest : public ::testing::Test {
  1845. protected:
  1846. ChunkedEncodingTest()
  1847. : cli_(HOST, PORT)
  1848. #ifdef CPPHTTPLIB_SSL_ENABLED
  1849. ,
  1850. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1851. #endif
  1852. {
  1853. cli_.set_connection_timeout(2);
  1854. #ifdef CPPHTTPLIB_SSL_ENABLED
  1855. cli_.enable_server_certificate_verification(false);
  1856. #endif
  1857. }
  1858. virtual void SetUp() {
  1859. read_file("./image.jpg", image_data_);
  1860. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1861. res.set_content("Hello World!", "text/plain");
  1862. });
  1863. svr_.Get(
  1864. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1865. res.set_chunked_content_provider(
  1866. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1867. size_t remaining = image_data_.size() - offset;
  1868. if (remaining == 0) {
  1869. sink.done();
  1870. } else {
  1871. constexpr size_t CHUNK_SIZE = 1024;
  1872. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1873. sink.write(&image_data_[offset], send_size);
  1874. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1875. }
  1876. return true;
  1877. });
  1878. });
  1879. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1880. svr_.wait_until_ready();
  1881. }
  1882. virtual void TearDown() {
  1883. svr_.stop();
  1884. if (!request_threads_.empty()) {
  1885. std::this_thread::sleep_for(std::chrono::seconds(1));
  1886. for (auto &t : request_threads_) {
  1887. t.join();
  1888. }
  1889. }
  1890. t_.join();
  1891. }
  1892. #ifdef CPPHTTPLIB_SSL_ENABLED
  1893. SSLClient cli_;
  1894. SSLServer svr_;
  1895. #else
  1896. Client cli_;
  1897. Server svr_;
  1898. #endif
  1899. thread t_;
  1900. std::vector<thread> request_threads_;
  1901. std::string image_data_;
  1902. };
  1903. TEST_F(ChunkedEncodingTest, NormalGet) {
  1904. auto res = cli_.Get("/chunked");
  1905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1906. std::string out;
  1907. read_file("./image.jpg", out);
  1908. EXPECT_EQ(StatusCode::OK_200, res->status);
  1909. EXPECT_EQ(out, res->body);
  1910. }
  1911. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1912. std::string body;
  1913. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1914. body.append(data, data_length);
  1915. return true;
  1916. });
  1917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1918. std::string out;
  1919. read_file("./image.jpg", out);
  1920. EXPECT_EQ(StatusCode::OK_200, res->status);
  1921. EXPECT_EQ(out, body);
  1922. }
  1923. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1924. std::string body;
  1925. auto res = cli_.Get(
  1926. "/chunked",
  1927. [&](const Response &response) {
  1928. EXPECT_EQ(StatusCode::OK_200, response.status);
  1929. return true;
  1930. },
  1931. [&](const char *data, size_t data_length) {
  1932. body.append(data, data_length);
  1933. return true;
  1934. });
  1935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1936. std::string out;
  1937. read_file("./image.jpg", out);
  1938. EXPECT_EQ(StatusCode::OK_200, res->status);
  1939. EXPECT_EQ(out, body);
  1940. }
  1941. TEST(RangeTest, FromHTTPBin_Online) {
  1942. auto host = "httpbingo.org";
  1943. auto path = std::string{"/range/32"};
  1944. #ifdef CPPHTTPLIB_SSL_ENABLED
  1945. auto port = 443;
  1946. SSLClient cli(host, port);
  1947. #else
  1948. auto port = 80;
  1949. Client cli(host, port);
  1950. #endif
  1951. cli.set_connection_timeout(5);
  1952. {
  1953. auto res = cli.Get(path);
  1954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1955. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1956. EXPECT_EQ(StatusCode::OK_200, res->status);
  1957. }
  1958. {
  1959. Headers headers = {make_range_header({{1, -1}})};
  1960. auto res = cli.Get(path, headers);
  1961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1962. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1963. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1964. }
  1965. {
  1966. Headers headers = {make_range_header({{1, 10}})};
  1967. auto res = cli.Get(path, headers);
  1968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1969. EXPECT_EQ("bcdefghijk", res->body);
  1970. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1971. }
  1972. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1973. // entire resource, while the original httpbin returned 200. Both are
  1974. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1975. {
  1976. Headers headers = {make_range_header({{0, 31}})};
  1977. auto res = cli.Get(path, headers);
  1978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1979. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1980. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1981. res->status == StatusCode::PartialContent_206);
  1982. }
  1983. {
  1984. Headers headers = {make_range_header({{0, -1}})};
  1985. auto res = cli.Get(path, headers);
  1986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1987. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1988. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1989. res->status == StatusCode::PartialContent_206);
  1990. }
  1991. // go-httpbin returns 206 with clamped range for over-range requests,
  1992. // while the original httpbin returned 416. Both behaviors are observed
  1993. // in real servers, so we only verify the request succeeds.
  1994. {
  1995. Headers headers = {make_range_header({{0, 32}})};
  1996. auto res = cli.Get(path, headers);
  1997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1998. }
  1999. }
  2000. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2001. auto host = "unresolvableaddress.local";
  2002. auto path = std::string{"/"};
  2003. #ifdef CPPHTTPLIB_SSL_ENABLED
  2004. auto port = 443;
  2005. SSLClient cli(host, port);
  2006. #else
  2007. auto port = 80;
  2008. Client cli(host, port);
  2009. #endif
  2010. cli.set_connection_timeout(1);
  2011. {
  2012. auto res = cli.Get(path);
  2013. ASSERT_FALSE(res);
  2014. }
  2015. std::this_thread::sleep_for(std::chrono::seconds(8));
  2016. }
  2017. #if defined(__linux__) && defined(__GLIBC__) && \
  2018. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2019. // Forward declaration: in split builds split.py strips `inline` and moves the
  2020. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2021. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2022. // against the symbol in both header-only and split builds.
  2023. namespace httplib {
  2024. namespace detail {
  2025. int getaddrinfo_with_timeout(const char *node, const char *service,
  2026. const struct addrinfo *hints,
  2027. struct addrinfo **res, time_t timeout_sec);
  2028. } // namespace detail
  2029. } // namespace httplib
  2030. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2031. //
  2032. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2033. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2034. // gai_suspend() call hits the connection timeout the function calls
  2035. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2036. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2037. // still alive and still references the now-destroyed stack frame.
  2038. //
  2039. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2040. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2041. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2042. // and runs them in a container.
  2043. namespace {
  2044. bool should_run_issue_2431_tests() {
  2045. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2046. return v && *v && std::string(v) != "0";
  2047. }
  2048. std::string unique_unresolvable_host(int n) {
  2049. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2050. // glibc still asks the configured nameserver — which is exactly the path
  2051. // we want to exercise. A unique label per call avoids the resolver cache.
  2052. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2053. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2054. std::to_string(n) + ".invalid";
  2055. }
  2056. } // namespace
  2057. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2058. if (!should_run_issue_2431_tests()) {
  2059. GTEST_SKIP()
  2060. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2061. }
  2062. for (int i = 0; i < 8; ++i) {
  2063. struct addrinfo hints;
  2064. memset(&hints, 0, sizeof(hints));
  2065. hints.ai_family = AF_UNSPEC;
  2066. hints.ai_socktype = SOCK_STREAM;
  2067. auto host = unique_unresolvable_host(i);
  2068. struct addrinfo *result = nullptr;
  2069. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2070. &result, /*timeout_sec=*/1);
  2071. if (rc == 0 && result) { freeaddrinfo(result); }
  2072. }
  2073. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2074. // stack region they still believe holds their gaicb.
  2075. std::this_thread::sleep_for(std::chrono::seconds(3));
  2076. }
  2077. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2078. if (!should_run_issue_2431_tests()) {
  2079. GTEST_SKIP()
  2080. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2081. }
  2082. std::atomic<bool> stop{false};
  2083. std::vector<std::thread> threads;
  2084. for (int t = 0; t < 8; ++t) {
  2085. threads.emplace_back([t, &stop] {
  2086. int i = 0;
  2087. while (!stop.load(std::memory_order_relaxed)) {
  2088. struct addrinfo hints;
  2089. memset(&hints, 0, sizeof(hints));
  2090. hints.ai_family = AF_UNSPEC;
  2091. hints.ai_socktype = SOCK_STREAM;
  2092. auto host = unique_unresolvable_host(t * 100000 + i++);
  2093. struct addrinfo *result = nullptr;
  2094. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2095. &result, /*timeout_sec=*/1);
  2096. if (rc == 0 && result) { freeaddrinfo(result); }
  2097. }
  2098. });
  2099. }
  2100. std::this_thread::sleep_for(std::chrono::seconds(8));
  2101. stop.store(true, std::memory_order_relaxed);
  2102. for (auto &th : threads) {
  2103. th.join();
  2104. }
  2105. std::this_thread::sleep_for(std::chrono::seconds(3));
  2106. }
  2107. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2108. if (!should_run_issue_2431_tests()) {
  2109. GTEST_SKIP()
  2110. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2111. }
  2112. std::atomic<bool> stop{false};
  2113. std::vector<std::thread> threads;
  2114. for (int t = 0; t < 8; ++t) {
  2115. threads.emplace_back([t, &stop] {
  2116. int i = 0;
  2117. while (!stop.load(std::memory_order_relaxed)) {
  2118. auto host = unique_unresolvable_host(t * 100000 + i++);
  2119. Client cli(host, 80);
  2120. cli.set_connection_timeout(1, 0);
  2121. cli.set_read_timeout(1, 0);
  2122. cli.set_write_timeout(1, 0);
  2123. (void)cli.Get("/");
  2124. }
  2125. });
  2126. }
  2127. std::this_thread::sleep_for(std::chrono::seconds(8));
  2128. stop.store(true, std::memory_order_relaxed);
  2129. for (auto &th : threads) {
  2130. th.join();
  2131. }
  2132. std::this_thread::sleep_for(std::chrono::seconds(3));
  2133. }
  2134. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2135. TEST(ConnectionErrorTest, InvalidHost) {
  2136. auto host = "-abcde.com";
  2137. #ifdef CPPHTTPLIB_SSL_ENABLED
  2138. auto port = 443;
  2139. SSLClient cli(host, port);
  2140. #else
  2141. auto port = 80;
  2142. Client cli(host, port);
  2143. #endif
  2144. cli.set_connection_timeout(std::chrono::seconds(2));
  2145. auto res = cli.Get("/");
  2146. ASSERT_TRUE(!res);
  2147. EXPECT_EQ(Error::Connection, res.error());
  2148. }
  2149. TEST(ConnectionErrorTest, InvalidHost2) {
  2150. auto host = "httpcan.org/";
  2151. #ifdef CPPHTTPLIB_SSL_ENABLED
  2152. SSLClient cli(host);
  2153. #else
  2154. Client cli(host);
  2155. #endif
  2156. cli.set_connection_timeout(std::chrono::seconds(2));
  2157. auto res = cli.Get("/");
  2158. ASSERT_TRUE(!res);
  2159. EXPECT_EQ(Error::Connection, res.error());
  2160. }
  2161. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2162. auto host = "httpcan.org/";
  2163. #ifdef CPPHTTPLIB_SSL_ENABLED
  2164. SSLClient cli(host);
  2165. #else
  2166. Client cli(host);
  2167. #endif
  2168. cli.set_connection_timeout(std::chrono::seconds(2));
  2169. auto res = cli.Get("/");
  2170. ASSERT_TRUE(!res);
  2171. stringstream s;
  2172. s << "error code: " << res.error();
  2173. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2174. }
  2175. TEST(ConnectionErrorTest, InvalidPort) {
  2176. auto host = "localhost";
  2177. auto port = 44380;
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. SSLClient cli(host, port);
  2180. #else
  2181. Client cli(host, port);
  2182. #endif
  2183. cli.set_connection_timeout(std::chrono::seconds(2));
  2184. auto res = cli.Get("/");
  2185. ASSERT_TRUE(!res);
  2186. EXPECT_TRUE(Error::Connection == res.error() ||
  2187. Error::ConnectionTimeout == res.error());
  2188. }
  2189. TEST(ConnectionErrorTest, Timeout_Online) {
  2190. auto host = "google.com";
  2191. #ifdef CPPHTTPLIB_SSL_ENABLED
  2192. auto port = 44380;
  2193. SSLClient cli(host, port);
  2194. #else
  2195. auto port = 8080;
  2196. Client cli(host, port);
  2197. #endif
  2198. cli.set_connection_timeout(std::chrono::seconds(2));
  2199. // only probe one address type so that the error reason
  2200. // correlates to the timed-out IPv4, not the unsupported
  2201. // IPv6 connection attempt
  2202. cli.set_address_family(AF_INET);
  2203. auto res = cli.Get("/");
  2204. ASSERT_TRUE(!res);
  2205. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2206. }
  2207. TEST(CancelTest, NoCancel_Online) {
  2208. auto host = "httpbingo.org";
  2209. auto path = std::string{"/range/32"};
  2210. #ifdef CPPHTTPLIB_SSL_ENABLED
  2211. auto port = 443;
  2212. SSLClient cli(host, port);
  2213. #else
  2214. auto port = 80;
  2215. Client cli(host, port);
  2216. #endif
  2217. cli.set_connection_timeout(std::chrono::seconds(5));
  2218. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2220. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2221. EXPECT_EQ(StatusCode::OK_200, res->status);
  2222. }
  2223. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2224. // Use /bytes with a large payload so that the DownloadProgress callback
  2225. // (which only fires for Content-Length responses) is invoked before the
  2226. // entire body is received, giving cancellation a chance to fire.
  2227. auto host = "httpbingo.org";
  2228. auto path = std::string{"/bytes/524288"};
  2229. #ifdef CPPHTTPLIB_SSL_ENABLED
  2230. auto port = 443;
  2231. SSLClient cli(host, port);
  2232. #else
  2233. auto port = 80;
  2234. Client cli(host, port);
  2235. #endif
  2236. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2237. cli.set_connection_timeout(std::chrono::seconds(5));
  2238. ASSERT_TRUE(!res);
  2239. EXPECT_EQ(Error::Canceled, res.error());
  2240. }
  2241. TEST(CancelTest, WithCancelLargePayload_Online) {
  2242. auto host = "httpbingo.org";
  2243. auto path = std::string{"/bytes/524288"};
  2244. #ifdef CPPHTTPLIB_SSL_ENABLED
  2245. auto port = 443;
  2246. SSLClient cli(host, port);
  2247. #else
  2248. auto port = 80;
  2249. Client cli(host, port);
  2250. #endif
  2251. cli.set_connection_timeout(std::chrono::seconds(5));
  2252. uint32_t count = 0;
  2253. auto res =
  2254. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2255. ASSERT_TRUE(!res);
  2256. EXPECT_EQ(Error::Canceled, res.error());
  2257. }
  2258. TEST(CancelTest, NoCancelPost) {
  2259. Server svr;
  2260. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2261. res.set_content("Hello World!", "text/plain");
  2262. });
  2263. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2264. auto se = detail::scope_exit([&] {
  2265. svr.stop();
  2266. thread.join();
  2267. ASSERT_FALSE(svr.is_running());
  2268. });
  2269. svr.wait_until_ready();
  2270. Client cli(HOST, PORT);
  2271. cli.set_connection_timeout(std::chrono::seconds(5));
  2272. auto res =
  2273. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2274. "application/json", [](uint64_t, uint64_t) { return true; });
  2275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2276. EXPECT_EQ("Hello World!", res->body);
  2277. EXPECT_EQ(StatusCode::OK_200, res->status);
  2278. }
  2279. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2280. Server svr;
  2281. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2282. res.set_content("Hello World!", "text/plain");
  2283. });
  2284. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2285. auto se = detail::scope_exit([&] {
  2286. svr.stop();
  2287. thread.join();
  2288. ASSERT_FALSE(svr.is_running());
  2289. });
  2290. svr.wait_until_ready();
  2291. Client cli(HOST, PORT);
  2292. cli.set_connection_timeout(std::chrono::seconds(5));
  2293. auto res =
  2294. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2295. "application/json", [](uint64_t, uint64_t) { return false; });
  2296. ASSERT_TRUE(!res);
  2297. EXPECT_EQ(Error::Canceled, res.error());
  2298. }
  2299. TEST(CancelTest, WithCancelLargePayloadPost) {
  2300. Server svr;
  2301. svr.set_payload_max_length(200 * 1024 * 1024);
  2302. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2303. res.set_content(LARGE_DATA, "text/plain");
  2304. });
  2305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2306. auto se = detail::scope_exit([&] {
  2307. svr.stop();
  2308. thread.join();
  2309. ASSERT_FALSE(svr.is_running());
  2310. });
  2311. svr.wait_until_ready();
  2312. Client cli(HOST, PORT);
  2313. cli.set_payload_max_length(200 * 1024 * 1024);
  2314. cli.set_connection_timeout(std::chrono::seconds(5));
  2315. auto res =
  2316. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2317. "application/json", [](uint64_t, uint64_t) { return false; });
  2318. ASSERT_TRUE(!res);
  2319. EXPECT_EQ(Error::Canceled, res.error());
  2320. }
  2321. TEST(CancelTest, NoCancelPut) {
  2322. Server svr;
  2323. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2324. res.set_content("Hello World!", "text/plain");
  2325. });
  2326. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2327. auto se = detail::scope_exit([&] {
  2328. svr.stop();
  2329. thread.join();
  2330. ASSERT_FALSE(svr.is_running());
  2331. });
  2332. svr.wait_until_ready();
  2333. Client cli(HOST, PORT);
  2334. cli.set_connection_timeout(std::chrono::seconds(5));
  2335. auto res =
  2336. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2337. "application/json", [](uint64_t, uint64_t) { return true; });
  2338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2339. EXPECT_EQ("Hello World!", res->body);
  2340. EXPECT_EQ(StatusCode::OK_200, res->status);
  2341. }
  2342. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2343. Server svr;
  2344. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2345. res.set_content("Hello World!", "text/plain");
  2346. });
  2347. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2348. auto se = detail::scope_exit([&] {
  2349. svr.stop();
  2350. thread.join();
  2351. ASSERT_FALSE(svr.is_running());
  2352. });
  2353. svr.wait_until_ready();
  2354. Client cli(HOST, PORT);
  2355. cli.set_connection_timeout(std::chrono::seconds(5));
  2356. auto res =
  2357. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2358. "application/json", [](uint64_t, uint64_t) { return false; });
  2359. ASSERT_TRUE(!res);
  2360. EXPECT_EQ(Error::Canceled, res.error());
  2361. }
  2362. TEST(CancelTest, WithCancelLargePayloadPut) {
  2363. Server svr;
  2364. svr.set_payload_max_length(200 * 1024 * 1024);
  2365. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2366. res.set_content(LARGE_DATA, "text/plain");
  2367. });
  2368. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2369. auto se = detail::scope_exit([&] {
  2370. svr.stop();
  2371. thread.join();
  2372. ASSERT_FALSE(svr.is_running());
  2373. });
  2374. svr.wait_until_ready();
  2375. Client cli(HOST, PORT);
  2376. cli.set_payload_max_length(200 * 1024 * 1024);
  2377. cli.set_connection_timeout(std::chrono::seconds(5));
  2378. auto res =
  2379. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2380. "application/json", [](uint64_t, uint64_t) { return false; });
  2381. ASSERT_TRUE(!res);
  2382. EXPECT_EQ(Error::Canceled, res.error());
  2383. }
  2384. TEST(CancelTest, NoCancelPatch) {
  2385. Server svr;
  2386. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2387. res.set_content("Hello World!", "text/plain");
  2388. });
  2389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2390. auto se = detail::scope_exit([&] {
  2391. svr.stop();
  2392. thread.join();
  2393. ASSERT_FALSE(svr.is_running());
  2394. });
  2395. svr.wait_until_ready();
  2396. Client cli(HOST, PORT);
  2397. cli.set_connection_timeout(std::chrono::seconds(5));
  2398. auto res =
  2399. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2400. "application/json", [](uint64_t, uint64_t) { return true; });
  2401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2402. EXPECT_EQ("Hello World!", res->body);
  2403. EXPECT_EQ(StatusCode::OK_200, res->status);
  2404. }
  2405. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2406. Server svr;
  2407. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2408. res.set_content("Hello World!", "text/plain");
  2409. });
  2410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2411. auto se = detail::scope_exit([&] {
  2412. svr.stop();
  2413. thread.join();
  2414. ASSERT_FALSE(svr.is_running());
  2415. });
  2416. svr.wait_until_ready();
  2417. Client cli(HOST, PORT);
  2418. cli.set_connection_timeout(std::chrono::seconds(5));
  2419. auto res =
  2420. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2421. "application/json", [](uint64_t, uint64_t) { return false; });
  2422. ASSERT_TRUE(!res);
  2423. EXPECT_EQ(Error::Canceled, res.error());
  2424. }
  2425. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2426. Server svr;
  2427. svr.set_payload_max_length(200 * 1024 * 1024);
  2428. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2429. res.set_content(LARGE_DATA, "text/plain");
  2430. });
  2431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2432. auto se = detail::scope_exit([&] {
  2433. svr.stop();
  2434. thread.join();
  2435. ASSERT_FALSE(svr.is_running());
  2436. });
  2437. svr.wait_until_ready();
  2438. Client cli(HOST, PORT);
  2439. cli.set_payload_max_length(200 * 1024 * 1024);
  2440. cli.set_connection_timeout(std::chrono::seconds(5));
  2441. auto res =
  2442. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2443. "application/json", [](uint64_t, uint64_t) { return false; });
  2444. ASSERT_TRUE(!res);
  2445. EXPECT_EQ(Error::Canceled, res.error());
  2446. }
  2447. TEST(CancelTest, NoCancelDelete) {
  2448. Server svr;
  2449. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2450. res.set_content("Hello World!", "text/plain");
  2451. });
  2452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2453. auto se = detail::scope_exit([&] {
  2454. svr.stop();
  2455. thread.join();
  2456. ASSERT_FALSE(svr.is_running());
  2457. });
  2458. svr.wait_until_ready();
  2459. Client cli(HOST, PORT);
  2460. cli.set_connection_timeout(std::chrono::seconds(5));
  2461. auto res =
  2462. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2463. "application/json", [](uint64_t, uint64_t) { return true; });
  2464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2465. EXPECT_EQ("Hello World!", res->body);
  2466. EXPECT_EQ(StatusCode::OK_200, res->status);
  2467. }
  2468. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2469. Server svr;
  2470. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2471. res.set_content("Hello World!", "text/plain");
  2472. });
  2473. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2474. auto se = detail::scope_exit([&] {
  2475. svr.stop();
  2476. thread.join();
  2477. ASSERT_FALSE(svr.is_running());
  2478. });
  2479. svr.wait_until_ready();
  2480. Client cli(HOST, PORT);
  2481. cli.set_connection_timeout(std::chrono::seconds(5));
  2482. auto res =
  2483. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2484. "application/json", [](uint64_t, uint64_t) { return false; });
  2485. ASSERT_TRUE(!res);
  2486. EXPECT_EQ(Error::Canceled, res.error());
  2487. }
  2488. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2489. Server svr;
  2490. svr.set_payload_max_length(200 * 1024 * 1024);
  2491. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2492. res.set_content(LARGE_DATA, "text/plain");
  2493. });
  2494. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2495. auto se = detail::scope_exit([&] {
  2496. svr.stop();
  2497. thread.join();
  2498. ASSERT_FALSE(svr.is_running());
  2499. });
  2500. svr.wait_until_ready();
  2501. Client cli(HOST, PORT);
  2502. cli.set_payload_max_length(200 * 1024 * 1024);
  2503. cli.set_connection_timeout(std::chrono::seconds(5));
  2504. auto res =
  2505. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2506. "application/json", [](uint64_t, uint64_t) { return false; });
  2507. ASSERT_TRUE(!res);
  2508. EXPECT_EQ(Error::Canceled, res.error());
  2509. }
  2510. static std::string remove_whitespace(const std::string &input) {
  2511. std::string output;
  2512. output.reserve(input.size());
  2513. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2514. [](unsigned char c) { return !std::isspace(c); });
  2515. return output;
  2516. }
  2517. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2518. auto host = "httpbingo.org";
  2519. auto path = std::string{"/basic-auth/hello/world"};
  2520. #ifdef CPPHTTPLIB_SSL_ENABLED
  2521. auto port = 443;
  2522. SSLClient cli(host, port);
  2523. #else
  2524. auto port = 80;
  2525. Client cli(host, port);
  2526. #endif
  2527. {
  2528. auto res = cli.Get(path);
  2529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2530. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2531. }
  2532. {
  2533. auto res = cli.Get(
  2534. path, Headers{make_basic_authentication_header("hello", "world")});
  2535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2536. auto body = remove_whitespace(res->body);
  2537. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2538. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2539. EXPECT_EQ(StatusCode::OK_200, res->status);
  2540. }
  2541. {
  2542. cli.set_basic_auth("hello", "world");
  2543. auto res = cli.Get(path);
  2544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2545. auto body = remove_whitespace(res->body);
  2546. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2547. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2548. EXPECT_EQ(StatusCode::OK_200, res->status);
  2549. }
  2550. {
  2551. cli.set_basic_auth("hello", "bad");
  2552. auto res = cli.Get(path);
  2553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2554. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2555. }
  2556. {
  2557. cli.set_basic_auth("bad", "world");
  2558. auto res = cli.Get(path);
  2559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2560. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2561. }
  2562. }
  2563. #ifdef CPPHTTPLIB_SSL_ENABLED
  2564. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2565. auto host = "httpbingo.org";
  2566. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2567. auto paths = std::vector<std::string>{
  2568. "/digest-auth/auth/hello/world/MD5",
  2569. "/digest-auth/auth/hello/world/SHA-256",
  2570. };
  2571. auto port = 443;
  2572. SSLClient cli(host, port);
  2573. {
  2574. auto res = cli.Get(unauth_path);
  2575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2576. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2577. }
  2578. {
  2579. cli.set_digest_auth("hello", "world");
  2580. for (const auto &path : paths) {
  2581. auto res = cli.Get(path.c_str());
  2582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2583. auto body = remove_whitespace(res->body);
  2584. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2585. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2586. EXPECT_EQ(StatusCode::OK_200, res->status);
  2587. }
  2588. cli.set_digest_auth("hello", "bad");
  2589. for (const auto &path : paths) {
  2590. auto res = cli.Get(path.c_str());
  2591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2593. }
  2594. }
  2595. }
  2596. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2597. // comma-separated list of challenges, and each challenge may itself carry a
  2598. // comma-separated auth-param list, so a server can legally offer Basic
  2599. // before Digest, either as two field lines or packed into one. Runs one 401
  2600. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2601. // value() joins them in receipt order) and checks that the retry carries a
  2602. // well-formed Digest Authorization header naming expected_realm.
  2603. static void
  2604. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2605. const std::string &expected_realm) {
  2606. std::atomic<int> hits{0};
  2607. Server svr;
  2608. svr.Get("/x", [&](const Request &req, Response &res) {
  2609. if (++hits == 1) {
  2610. res.status = StatusCode::Unauthorized_401;
  2611. for (const auto &challenge : challenges) {
  2612. res.set_header("WWW-Authenticate", challenge);
  2613. }
  2614. } else {
  2615. auto authorization = req.get_header_value("Authorization");
  2616. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2617. EXPECT_NE(std::string::npos,
  2618. authorization.find("realm=\"" + expected_realm + "\""));
  2619. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2620. res.set_content("ok", "text/plain");
  2621. }
  2622. });
  2623. auto port = svr.bind_to_any_port(HOST);
  2624. std::thread t([&]() { svr.listen_after_bind(); });
  2625. auto se = detail::scope_exit([&] {
  2626. svr.stop();
  2627. t.join();
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli(HOST, port);
  2631. cli.set_digest_auth("hello", "world");
  2632. auto res = cli.Get("/x");
  2633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2634. EXPECT_EQ(2, hits.load());
  2635. }
  2636. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2637. static const char *kDigestChallenge =
  2638. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2639. "algorithm=MD5";
  2640. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2641. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2642. "testrealm");
  2643. }
  2644. // Same challenge list with the schemes in the opposite order, to make sure
  2645. // the fix above didn't just special-case "Basic first".
  2646. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2647. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2648. "testrealm");
  2649. }
  2650. // A comma inside a quoted auth-param value must not be mistaken for the
  2651. // separator between two challenges (or two auth-params).
  2652. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2653. run_digest_challenge_list_test(
  2654. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2655. "algorithm=MD5"},
  2656. "test,realm");
  2657. }
  2658. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2659. // make_digest_authentication_header() dereferences both unconditionally, so
  2660. // a server sending a challenge missing either one must not be treated as
  2661. // usable -- doing so used to crash the client with std::out_of_range.
  2662. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2663. Server svr;
  2664. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2665. res.status = StatusCode::Unauthorized_401;
  2666. res.set_header("WWW-Authenticate", challenge);
  2667. });
  2668. auto port = svr.bind_to_any_port(HOST);
  2669. std::thread t([&]() { svr.listen_after_bind(); });
  2670. auto se = detail::scope_exit([&] {
  2671. svr.stop();
  2672. t.join();
  2673. });
  2674. svr.wait_until_ready();
  2675. Client cli(HOST, port);
  2676. cli.set_digest_auth("hello", "world");
  2677. auto res = cli.Get("/x");
  2678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2679. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2680. }
  2681. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2682. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2683. }
  2684. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2685. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2686. }
  2687. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2688. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2689. }
  2690. #endif
  2691. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2692. auto host = "google.com";
  2693. auto another_host = "example.com";
  2694. auto wrong_ip = "0.0.0.0";
  2695. #ifdef CPPHTTPLIB_SSL_ENABLED
  2696. SSLClient cli(host);
  2697. #else
  2698. Client cli(host);
  2699. #endif
  2700. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2701. auto res = cli.Get("/");
  2702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2703. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2704. }
  2705. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2706. auto host = "google.com";
  2707. auto wrong_ip = "0.0.0.0";
  2708. #ifdef CPPHTTPLIB_SSL_ENABLED
  2709. SSLClient cli(host);
  2710. #else
  2711. Client cli(host);
  2712. #endif
  2713. cli.set_hostname_addr_map({{host, wrong_ip}});
  2714. auto res = cli.Get("/");
  2715. ASSERT_TRUE(!res);
  2716. EXPECT_EQ(Error::Connection, res.error());
  2717. }
  2718. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2719. // A mapped value that is not an IP literal must be resolved. "localhost"
  2720. // resolves from the hosts file, so this test needs no external DNS.
  2721. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2722. auto host = "target.invalid";
  2723. Server svr;
  2724. std::string received_host;
  2725. svr.Get("/hi", [&](const Request &req, Response &res) {
  2726. received_host = req.get_header_value("Host");
  2727. res.set_content("Hello World!", "text/plain");
  2728. });
  2729. auto port = svr.bind_to_any_port(HOST);
  2730. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2731. auto se = detail::scope_exit([&] {
  2732. svr.stop();
  2733. thread.join();
  2734. ASSERT_FALSE(svr.is_running());
  2735. });
  2736. svr.wait_until_ready();
  2737. Client cli(host, port);
  2738. cli.set_hostname_addr_map({{host, HOST}});
  2739. auto res = cli.Get("/hi");
  2740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2741. EXPECT_EQ(StatusCode::OK_200, res->status);
  2742. // The mapping only redirects the connection; the identity stays host_.
  2743. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2744. }
  2745. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2746. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2747. auto host = "target.invalid";
  2748. Server svr;
  2749. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2750. res.set_content("Hello World!", "text/plain");
  2751. });
  2752. auto port = svr.bind_to_any_port("127.0.0.1");
  2753. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2754. auto se = detail::scope_exit([&] {
  2755. svr.stop();
  2756. thread.join();
  2757. ASSERT_FALSE(svr.is_running());
  2758. });
  2759. svr.wait_until_ready();
  2760. Client cli(host, port);
  2761. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2762. auto res = cli.Get("/hi");
  2763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2764. EXPECT_EQ(StatusCode::OK_200, res->status);
  2765. }
  2766. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2767. // An empty mapped value must leave host_ as the connection target. Without
  2768. // that guard the empty value would become the host argument, getaddrinfo
  2769. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2770. // loopback - silently connecting somewhere the caller never asked for.
  2771. // The server listens on loopback, so such a fallback would succeed and is
  2772. // therefore observable as a failure of this test.
  2773. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2774. Server svr;
  2775. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2776. res.set_content("Hello World!", "text/plain");
  2777. });
  2778. auto port = svr.bind_to_any_port(HOST);
  2779. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2780. auto se = detail::scope_exit([&] {
  2781. svr.stop();
  2782. thread.join();
  2783. ASSERT_FALSE(svr.is_running());
  2784. });
  2785. svr.wait_until_ready();
  2786. Client cli(blackhole, port);
  2787. cli.set_hostname_addr_map({{blackhole, ""}});
  2788. cli.set_connection_timeout(1);
  2789. auto res = cli.Get("/hi");
  2790. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2791. }
  2792. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2793. auto host = "httpbingo.org";
  2794. auto path = std::string{"/absolute-redirect/3"};
  2795. #ifdef CPPHTTPLIB_SSL_ENABLED
  2796. SSLClient cli(host);
  2797. #else
  2798. Client cli(host);
  2799. #endif
  2800. cli.set_follow_location(true);
  2801. auto res = cli.Get(path);
  2802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2803. EXPECT_EQ(StatusCode::OK_200, res->status);
  2804. }
  2805. TEST(RedirectTest, Redirect_Online) {
  2806. auto host = "httpbingo.org";
  2807. auto path = std::string{"/redirect/3"};
  2808. #ifdef CPPHTTPLIB_SSL_ENABLED
  2809. SSLClient cli(host);
  2810. #else
  2811. Client cli(host);
  2812. #endif
  2813. cli.set_follow_location(true);
  2814. auto res = cli.Get(path);
  2815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2816. EXPECT_EQ(StatusCode::OK_200, res->status);
  2817. }
  2818. TEST(RelativeRedirectTest, Redirect_Online) {
  2819. auto host = "httpbingo.org";
  2820. auto path = std::string{"/relative-redirect/3"};
  2821. #ifdef CPPHTTPLIB_SSL_ENABLED
  2822. SSLClient cli(host);
  2823. #else
  2824. Client cli(host);
  2825. #endif
  2826. cli.set_follow_location(true);
  2827. auto res = cli.Get(path);
  2828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2829. EXPECT_EQ(StatusCode::OK_200, res->status);
  2830. }
  2831. TEST(TooManyRedirectTest, Redirect_Online) {
  2832. auto host = "httpbingo.org";
  2833. auto path = std::string{"/redirect/21"};
  2834. #ifdef CPPHTTPLIB_SSL_ENABLED
  2835. SSLClient cli(host);
  2836. #else
  2837. Client cli(host);
  2838. #endif
  2839. cli.set_follow_location(true);
  2840. auto res = cli.Get(path);
  2841. ASSERT_TRUE(!res);
  2842. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2843. }
  2844. #ifdef CPPHTTPLIB_SSL_ENABLED
  2845. TEST(YahooRedirectTest, Redirect_Online) {
  2846. Client cli("yahoo.com");
  2847. auto res = cli.Get("/");
  2848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2849. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2850. cli.set_follow_location(true);
  2851. res = cli.Get("/");
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2855. }
  2856. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2857. #define REDIR_HOST "httpbingo.org"
  2858. #define REDIR_PATH "/redirect-to"
  2859. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2860. SSLClient cli(REDIR_HOST);
  2861. cli.set_follow_location(true);
  2862. auto res =
  2863. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. EXPECT_EQ(StatusCode::OK_200, res->status);
  2866. }
  2867. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2868. SSLClient cli(REDIR_HOST);
  2869. cli.set_follow_location(true);
  2870. Params params;
  2871. params.emplace("url", "http://example.com");
  2872. params.emplace("status_code", "302");
  2873. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. EXPECT_EQ(StatusCode::OK_200, res->status);
  2876. }
  2877. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2878. SSLClient cli(REDIR_HOST);
  2879. cli.set_follow_location(true);
  2880. Params params;
  2881. params.emplace("url", "http://example.com");
  2882. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2884. EXPECT_EQ(StatusCode::OK_200, res->status);
  2885. }
  2886. TEST(UrlWithSpace, Redirect_Online) {
  2887. SSLClient cli("edge.forgecdn.net");
  2888. cli.set_follow_location(true);
  2889. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2891. EXPECT_EQ(StatusCode::OK_200, res->status);
  2892. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2893. }
  2894. #endif
  2895. #if !defined(_WIN32) && !defined(_WIN64)
  2896. TEST(ReceiveSignals, Signal) {
  2897. auto setupSignalHandlers = []() {
  2898. struct sigaction act;
  2899. sigemptyset(&act.sa_mask);
  2900. act.sa_flags = SA_SIGINFO;
  2901. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2902. switch (sig) {
  2903. case SIGINT:
  2904. default: break;
  2905. }
  2906. };
  2907. ::sigaction(SIGINT, &act, nullptr);
  2908. };
  2909. Server svr;
  2910. int port = 0;
  2911. auto thread = std::thread([&]() {
  2912. setupSignalHandlers();
  2913. port = svr.bind_to_any_port(HOST);
  2914. svr.listen_after_bind();
  2915. });
  2916. auto se = detail::scope_exit([&] {
  2917. svr.stop();
  2918. thread.join();
  2919. ASSERT_FALSE(svr.is_running());
  2920. });
  2921. svr.wait_until_ready();
  2922. ASSERT_TRUE(svr.is_running());
  2923. pthread_kill(thread.native_handle(), SIGINT);
  2924. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2925. ASSERT_TRUE(svr.is_running());
  2926. }
  2927. #endif
  2928. TEST(RedirectToDifferentPort, Redirect) {
  2929. Server svr1;
  2930. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2931. res.set_content("Hello World!", "text/plain");
  2932. });
  2933. int svr1_port = 0;
  2934. auto thread1 = std::thread([&]() {
  2935. svr1_port = svr1.bind_to_any_port(HOST);
  2936. svr1.listen_after_bind();
  2937. });
  2938. Server svr2;
  2939. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2940. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2941. });
  2942. int svr2_port = 0;
  2943. auto thread2 = std::thread([&]() {
  2944. svr2_port = svr2.bind_to_any_port(HOST);
  2945. svr2.listen_after_bind();
  2946. });
  2947. auto se = detail::scope_exit([&] {
  2948. svr2.stop();
  2949. thread2.join();
  2950. svr1.stop();
  2951. thread1.join();
  2952. ASSERT_FALSE(svr2.is_running());
  2953. ASSERT_FALSE(svr1.is_running());
  2954. });
  2955. svr1.wait_until_ready();
  2956. svr2.wait_until_ready();
  2957. Client cli("localhost", svr2_port);
  2958. cli.set_follow_location(true);
  2959. auto res = cli.Get("/2");
  2960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2961. EXPECT_EQ(StatusCode::OK_200, res->status);
  2962. EXPECT_EQ("Hello World!", res->body);
  2963. }
  2964. static void
  2965. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2966. Server svr1;
  2967. std::string captured_authorization;
  2968. svr1.Get("/target", [&](const Request &req, Response &res) {
  2969. captured_authorization = req.get_header_value("Authorization");
  2970. res.set_content("OK", "text/plain");
  2971. });
  2972. int svr1_port = 0;
  2973. auto thread1 = std::thread([&]() {
  2974. svr1_port = svr1.bind_to_any_port(HOST);
  2975. svr1.listen_after_bind();
  2976. });
  2977. Server svr2;
  2978. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2979. res.set_redirect(
  2980. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2981. });
  2982. int svr2_port = 0;
  2983. auto thread2 = std::thread([&]() {
  2984. svr2_port = svr2.bind_to_any_port(HOST);
  2985. svr2.listen_after_bind();
  2986. });
  2987. auto se = detail::scope_exit([&] {
  2988. svr2.stop();
  2989. thread2.join();
  2990. svr1.stop();
  2991. thread1.join();
  2992. ASSERT_FALSE(svr2.is_running());
  2993. ASSERT_FALSE(svr1.is_running());
  2994. });
  2995. svr1.wait_until_ready();
  2996. svr2.wait_until_ready();
  2997. Client cli("localhost", svr2_port);
  2998. cli.set_follow_location(true);
  2999. set_auth(cli);
  3000. auto res = cli.Get("/redir");
  3001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3002. EXPECT_EQ(StatusCode::OK_200, res->status);
  3003. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3004. EXPECT_TRUE(captured_authorization.empty());
  3005. }
  3006. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3007. TestDoNotForwardCredentialsOnRedirect(
  3008. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3009. }
  3010. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3011. TestDoNotForwardCredentialsOnRedirect(
  3012. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3013. }
  3014. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3015. Server svr1;
  3016. std::string captured_cookie;
  3017. bool target_hit = false;
  3018. svr1.Get("/target", [&](const Request &req, Response &res) {
  3019. captured_cookie = req.get_header_value("Cookie");
  3020. target_hit = true;
  3021. res.set_content("OK", "text/plain");
  3022. });
  3023. int svr1_port = 0;
  3024. auto thread1 = std::thread([&]() {
  3025. svr1_port = svr1.bind_to_any_port(HOST);
  3026. svr1.listen_after_bind();
  3027. });
  3028. Server svr2;
  3029. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3030. res.set_redirect(
  3031. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3032. });
  3033. int svr2_port = 0;
  3034. auto thread2 = std::thread([&]() {
  3035. svr2_port = svr2.bind_to_any_port(HOST);
  3036. svr2.listen_after_bind();
  3037. });
  3038. auto se = detail::scope_exit([&] {
  3039. svr2.stop();
  3040. thread2.join();
  3041. svr1.stop();
  3042. thread1.join();
  3043. ASSERT_FALSE(svr2.is_running());
  3044. ASSERT_FALSE(svr1.is_running());
  3045. });
  3046. svr1.wait_until_ready();
  3047. svr2.wait_until_ready();
  3048. Client cli("localhost", svr2_port);
  3049. cli.set_follow_location(true);
  3050. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3051. auto res = cli.Get("/redir", headers);
  3052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3053. EXPECT_EQ(StatusCode::OK_200, res->status);
  3054. EXPECT_TRUE(target_hit);
  3055. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3056. EXPECT_TRUE(captured_cookie.empty());
  3057. }
  3058. TEST(RedirectToSamePort, ForwardCookie) {
  3059. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3060. // header so that ordinary session flows keep working.
  3061. Server svr;
  3062. std::string captured_cookie;
  3063. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3064. res.set_redirect("/target", 302);
  3065. });
  3066. svr.Get("/target", [&](const Request &req, Response &res) {
  3067. captured_cookie = req.get_header_value("Cookie");
  3068. res.set_content("OK", "text/plain");
  3069. });
  3070. auto port = svr.bind_to_any_port(HOST);
  3071. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3072. auto se = detail::scope_exit([&] {
  3073. svr.stop();
  3074. thread.join();
  3075. ASSERT_FALSE(svr.is_running());
  3076. });
  3077. svr.wait_until_ready();
  3078. Client cli(HOST, port);
  3079. cli.set_follow_location(true);
  3080. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3081. auto res = cli.Get("/redir", headers);
  3082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3083. EXPECT_EQ(StatusCode::OK_200, res->status);
  3084. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3085. }
  3086. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3087. Server svr;
  3088. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3089. // Port number that overflows int — should not crash
  3090. res.set_redirect("http://localhost:99999999999999999999/target");
  3091. });
  3092. auto port = svr.bind_to_any_port(HOST);
  3093. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3094. auto se = detail::scope_exit([&] {
  3095. svr.stop();
  3096. thread.join();
  3097. ASSERT_FALSE(svr.is_running());
  3098. });
  3099. svr.wait_until_ready();
  3100. Client cli(HOST, port);
  3101. cli.set_follow_location(true);
  3102. auto res = cli.Get("/redir");
  3103. // Should fail gracefully, not crash (no valid response due to bad port)
  3104. EXPECT_FALSE(res);
  3105. }
  3106. TEST(RedirectFromPageWithContent, Redirect) {
  3107. Server svr;
  3108. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3109. res.set_content("___", "text/plain");
  3110. res.set_redirect("/2");
  3111. });
  3112. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3113. res.set_content("Hello World!", "text/plain");
  3114. });
  3115. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3116. auto se = detail::scope_exit([&] {
  3117. svr.stop();
  3118. th.join();
  3119. ASSERT_FALSE(svr.is_running());
  3120. });
  3121. svr.wait_until_ready();
  3122. {
  3123. Client cli("localhost", PORT);
  3124. cli.set_follow_location(true);
  3125. std::string body;
  3126. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3127. body.append(data, data_length);
  3128. return true;
  3129. });
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. EXPECT_EQ("Hello World!", body);
  3133. }
  3134. {
  3135. Client cli("localhost", PORT);
  3136. std::string body;
  3137. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3138. body.append(data, data_length);
  3139. return true;
  3140. });
  3141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3142. EXPECT_EQ(StatusCode::Found_302, res->status);
  3143. EXPECT_EQ("___", body);
  3144. }
  3145. }
  3146. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3147. Server svr;
  3148. auto port_str = std::to_string(PORT);
  3149. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3150. auto expected_host = "[::1]:" + port_str;
  3151. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3152. res.set_content("___", "text/plain");
  3153. // res.set_redirect("/2");
  3154. res.set_redirect(redirect_url);
  3155. });
  3156. svr.Get("/2", [&](const Request &req, Response &res) {
  3157. auto host_header = req.headers.find("Host");
  3158. ASSERT_TRUE(host_header != req.headers.end());
  3159. EXPECT_EQ(expected_host, host_header->second);
  3160. res.set_content("Hello World!", "text/plain");
  3161. });
  3162. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3163. auto se = detail::scope_exit([&] {
  3164. svr.stop();
  3165. th.join();
  3166. ASSERT_FALSE(svr.is_running());
  3167. });
  3168. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3169. // actually starts anything, so the condition !svr.is_running() will
  3170. // always remain true, and the loop never stops.
  3171. // This basically counts how many milliseconds have passed since the
  3172. // call to svr.listen(), and if after 5 seconds nothing started yet
  3173. // aborts the test.
  3174. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3175. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3176. ASSERT_LT(milliseconds, 5000U);
  3177. }
  3178. {
  3179. Client cli("::1", PORT);
  3180. cli.set_follow_location(true);
  3181. std::string body;
  3182. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3183. body.append(data, data_length);
  3184. return true;
  3185. });
  3186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3187. EXPECT_EQ(StatusCode::OK_200, res->status);
  3188. EXPECT_EQ("Hello World!", body);
  3189. }
  3190. {
  3191. Client cli("::1", PORT);
  3192. std::string body;
  3193. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3194. body.append(data, data_length);
  3195. return true;
  3196. });
  3197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3198. EXPECT_EQ(StatusCode::Found_302, res->status);
  3199. EXPECT_EQ("___", body);
  3200. }
  3201. }
  3202. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3203. Server svr;
  3204. svr.Get("/foo", [](const Request &req, Response &res) {
  3205. auto a = req.params.find("a");
  3206. if (a != req.params.end()) {
  3207. res.set_content((*a).second, "text/plain");
  3208. res.status = StatusCode::OK_200;
  3209. } else {
  3210. res.status = StatusCode::BadRequest_400;
  3211. }
  3212. });
  3213. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3214. auto se = detail::scope_exit([&] {
  3215. svr.stop();
  3216. thread.join();
  3217. ASSERT_FALSE(svr.is_running());
  3218. });
  3219. svr.wait_until_ready();
  3220. {
  3221. Client cli(HOST, PORT);
  3222. cli.set_path_encode(false);
  3223. auto res = cli.Get("/foo?a=explicitly+encoded");
  3224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3225. EXPECT_EQ(StatusCode::OK_200, res->status);
  3226. // This expects it back with a space, as the `+` won't have been
  3227. // url-encoded, and server-side the params get decoded turning `+`
  3228. // into spaces.
  3229. EXPECT_EQ("explicitly encoded", res->body);
  3230. }
  3231. }
  3232. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3233. // When path encoding is disabled the client must transmit the supplied
  3234. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3235. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3236. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3237. // than a space (0x20). Assert on the raw wire target to catch this.
  3238. Server svr;
  3239. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3240. svr.Get("/foo", [&](const Request &req, Response &res) {
  3241. EXPECT_EQ(expected_target, req.target);
  3242. res.status = StatusCode::OK_200;
  3243. });
  3244. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3245. auto se = detail::scope_exit([&] {
  3246. svr.stop();
  3247. thread.join();
  3248. ASSERT_FALSE(svr.is_running());
  3249. });
  3250. svr.wait_until_ready();
  3251. {
  3252. Client cli(HOST, PORT);
  3253. cli.set_path_encode(false);
  3254. auto res = cli.Get(expected_target.c_str());
  3255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3256. EXPECT_EQ(StatusCode::OK_200, res->status);
  3257. }
  3258. }
  3259. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3260. // `open_stream()` used to skip the path encoding that the buffered send
  3261. // path applies, so the same `path` produced different bytes in the request
  3262. // line depending on which API was used. Assert the two agree.
  3263. Server svr;
  3264. std::string target;
  3265. svr.Get(".*", [&](const Request &req, Response &res) {
  3266. target = req.target;
  3267. res.status = StatusCode::OK_200;
  3268. });
  3269. auto port = svr.bind_to_any_port(HOST);
  3270. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3271. auto se = detail::scope_exit([&] {
  3272. svr.stop();
  3273. thread.join();
  3274. ASSERT_FALSE(svr.is_running());
  3275. });
  3276. svr.wait_until_ready();
  3277. struct {
  3278. const char *path;
  3279. const char *expected;
  3280. } cases[] = {
  3281. {"/a b?x=1", "/a%20b?x=1"},
  3282. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3283. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3284. };
  3285. for (const auto &c : cases) {
  3286. Client cli(HOST, port);
  3287. target.clear();
  3288. auto res = cli.Get(c.path);
  3289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3290. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3291. auto buffered_target = target;
  3292. target.clear();
  3293. auto handle = cli.open_stream("GET", c.path);
  3294. EXPECT_TRUE(handle.is_valid())
  3295. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3296. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3297. }
  3298. }
  3299. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3300. // The `set_path_encode(false)` contract — transmit the supplied target
  3301. // verbatim — must hold for the streaming API too.
  3302. Server svr;
  3303. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3304. std::string target;
  3305. svr.Get("/foo", [&](const Request &req, Response &res) {
  3306. target = req.target;
  3307. res.status = StatusCode::OK_200;
  3308. });
  3309. auto port = svr.bind_to_any_port(HOST);
  3310. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3311. auto se = detail::scope_exit([&] {
  3312. svr.stop();
  3313. thread.join();
  3314. ASSERT_FALSE(svr.is_running());
  3315. });
  3316. svr.wait_until_ready();
  3317. {
  3318. Client cli(HOST, port);
  3319. cli.set_path_encode(false);
  3320. auto handle = cli.open_stream("GET", expected_target);
  3321. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3322. EXPECT_EQ(expected_target, target);
  3323. }
  3324. }
  3325. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3326. // With path encoding enabled a CR/LF in the target is percent-encoded
  3327. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3328. // write_request_line still backstops `set_path_encode(false)`, which is
  3329. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3330. Server svr;
  3331. // Captured before routing: the decoded path contains a newline, which a
  3332. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3333. std::string target;
  3334. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3335. target = req.target;
  3336. res.status = StatusCode::OK_200;
  3337. return Server::HandlerResponse::Handled;
  3338. });
  3339. auto port = svr.bind_to_any_port(HOST);
  3340. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3341. auto se = detail::scope_exit([&] {
  3342. svr.stop();
  3343. thread.join();
  3344. ASSERT_FALSE(svr.is_running());
  3345. });
  3346. svr.wait_until_ready();
  3347. {
  3348. Client cli(HOST, port);
  3349. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3350. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3351. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3352. }
  3353. }
  3354. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3355. // Nothing may reach the wire: a raw CR/LF target would split the request
  3356. // line and inject headers.
  3357. Server svr;
  3358. // Pre-routing so that "not called" means nothing reached the server at all,
  3359. // rather than merely failing to match a handler pattern.
  3360. auto handler_called = false;
  3361. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3362. handler_called = true;
  3363. res.status = StatusCode::OK_200;
  3364. return Server::HandlerResponse::Handled;
  3365. });
  3366. auto port = svr.bind_to_any_port(HOST);
  3367. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3368. auto se = detail::scope_exit([&] {
  3369. svr.stop();
  3370. thread.join();
  3371. ASSERT_FALSE(svr.is_running());
  3372. });
  3373. svr.wait_until_ready();
  3374. {
  3375. Client cli(HOST, port);
  3376. cli.set_path_encode(false);
  3377. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3378. EXPECT_FALSE(handle.is_valid());
  3379. EXPECT_EQ(Error::Write, handle.error);
  3380. EXPECT_FALSE(handler_called);
  3381. }
  3382. }
  3383. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3384. // Which of the two branches runs is decided by whether the query component
  3385. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3386. // an empty query and must still fall back to building one from
  3387. // `req.params`, while a non-empty query must win over `req.params`.
  3388. Server svr;
  3389. std::string target;
  3390. svr.Get("/foo", [&](const Request &req, Response &res) {
  3391. target = req.target;
  3392. res.status = StatusCode::OK_200;
  3393. });
  3394. auto port = svr.bind_to_any_port(HOST);
  3395. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3396. auto se = detail::scope_exit([&] {
  3397. svr.stop();
  3398. thread.join();
  3399. ASSERT_FALSE(svr.is_running());
  3400. });
  3401. svr.wait_until_ready();
  3402. {
  3403. // Trailing `?` -> empty query component -> `req.params` is used.
  3404. Client cli(HOST, port);
  3405. Request req;
  3406. req.method = "GET";
  3407. req.path = "/foo?";
  3408. req.params.emplace("a", "1");
  3409. target.clear();
  3410. auto res = cli.send(req);
  3411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3412. EXPECT_EQ("/foo?a=1", target);
  3413. }
  3414. {
  3415. // Non-empty query in `req.path` -> `req.params` is not appended.
  3416. Client cli(HOST, port);
  3417. Request req;
  3418. req.method = "GET";
  3419. req.path = "/foo?b=2";
  3420. req.params.emplace("a", "1");
  3421. target.clear();
  3422. auto res = cli.send(req);
  3423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3424. EXPECT_EQ("/foo?b=2", target);
  3425. }
  3426. }
  3427. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3428. Server svr;
  3429. svr.Get("/", [](const Request &req, Response &) {
  3430. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3431. });
  3432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3433. auto se = detail::scope_exit([&] {
  3434. svr.stop();
  3435. thread.join();
  3436. ASSERT_FALSE(svr.is_running());
  3437. });
  3438. svr.wait_until_ready();
  3439. {
  3440. Client cli(HOST, PORT);
  3441. cli.set_path_encode(false);
  3442. auto res = cli.Get("/?something=%0A");
  3443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3444. EXPECT_EQ(StatusCode::OK_200, res->status);
  3445. }
  3446. }
  3447. TEST(BindServerTest, BindDualStack) {
  3448. Server svr;
  3449. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3450. res.set_content("Hello World!", "text/plain");
  3451. });
  3452. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3453. auto se = detail::scope_exit([&] {
  3454. svr.stop();
  3455. thread.join();
  3456. ASSERT_FALSE(svr.is_running());
  3457. });
  3458. svr.wait_until_ready();
  3459. {
  3460. Client cli("127.0.0.1", PORT);
  3461. auto res = cli.Get("/1");
  3462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3463. EXPECT_EQ(StatusCode::OK_200, res->status);
  3464. EXPECT_EQ("Hello World!", res->body);
  3465. }
  3466. {
  3467. Client cli("::1", PORT);
  3468. auto res = cli.Get("/1");
  3469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3470. EXPECT_EQ(StatusCode::OK_200, res->status);
  3471. EXPECT_EQ("Hello World!", res->body);
  3472. }
  3473. }
  3474. TEST(BindServerTest, BindAndListenSeparately) {
  3475. Server svr;
  3476. int port = svr.bind_to_any_port("0.0.0.0");
  3477. ASSERT_TRUE(svr.is_valid());
  3478. ASSERT_TRUE(port > 0);
  3479. svr.stop();
  3480. }
  3481. // Reports whether anything is still listening on a loopback port. A plain
  3482. // connect() is used instead of a Client request because a socket left bound by
  3483. // mistake accepts the connection into its backlog and never answers, which
  3484. // would hang the test instead of failing it.
  3485. static bool is_loopback_port_accepting(int port) {
  3486. sockaddr_in addr{};
  3487. addr.sin_family = AF_INET;
  3488. addr.sin_port = htons(static_cast<uint16_t>(port));
  3489. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3490. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3491. EXPECT_NE(sock, INVALID_SOCKET);
  3492. if (sock == INVALID_SOCKET) { return false; }
  3493. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3494. static_cast<socklen_t>(sizeof(addr)));
  3495. detail::close_socket(sock);
  3496. return ret == 0;
  3497. }
  3498. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3499. Server svr;
  3500. auto port = svr.bind_to_any_port("127.0.0.1");
  3501. ASSERT_TRUE(port > 0);
  3502. svr.stop();
  3503. // bind_to_any_port() already called listen(2), so until stop() closed the
  3504. // descriptor the port kept accepting connections into the backlog. ASSERT
  3505. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3506. // below blocks forever in the accept loop.
  3507. ASSERT_FALSE(is_loopback_port_accepting(port));
  3508. // Nothing is left to accept on, so listen_after_bind() must report failure
  3509. // instead of returning success without ever serving.
  3510. EXPECT_FALSE(svr.listen_after_bind());
  3511. // The failed listen marks the server decommissioned, so a waiter returns
  3512. // instead of spinning forever.
  3513. svr.wait_until_ready();
  3514. }
  3515. #ifdef CPPHTTPLIB_SSL_ENABLED
  3516. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3518. CLIENT_CA_CERT_DIR);
  3519. int port = svr.bind_to_any_port("0.0.0.0");
  3520. ASSERT_TRUE(svr.is_valid());
  3521. ASSERT_TRUE(port > 0);
  3522. svr.stop();
  3523. }
  3524. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3525. // or a rejected CustomRoute() registration would not stop the server binding.
  3526. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3527. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3528. CLIENT_CA_CERT_DIR);
  3529. ASSERT_TRUE(svr.is_valid());
  3530. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3531. EXPECT_FALSE(svr.is_valid());
  3532. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3533. }
  3534. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3535. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3536. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3537. int port = svr.bind_to_any_port("0.0.0.0");
  3538. ASSERT_TRUE(svr.is_valid());
  3539. ASSERT_TRUE(port > 0);
  3540. svr.stop();
  3541. }
  3542. TEST(BindServerTest, UpdateCertsPem) {
  3543. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3544. int port = svr.bind_to_any_port("0.0.0.0");
  3545. ASSERT_TRUE(svr.is_valid());
  3546. ASSERT_TRUE(port > 0);
  3547. // Read PEM files
  3548. std::string cert_pem, key_pem, ca_pem;
  3549. read_file(SERVER_CERT_FILE, cert_pem);
  3550. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3551. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3552. // Update server certificates using PEM API
  3553. ASSERT_TRUE(
  3554. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3555. ASSERT_TRUE(svr.is_valid());
  3556. svr.stop();
  3557. }
  3558. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3559. // Start server with client CA (enables client auth)
  3560. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3561. ASSERT_TRUE(svr.is_valid());
  3562. bool handler_called = false;
  3563. svr.Get("/test", [&](const Request &req, Response &res) {
  3564. handler_called = true;
  3565. // Verify client certificate is present
  3566. auto cert = req.peer_cert();
  3567. EXPECT_TRUE(static_cast<bool>(cert));
  3568. res.set_content("ok", "text/plain");
  3569. });
  3570. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3571. auto se = detail::scope_exit([&] {
  3572. svr.stop();
  3573. t.join();
  3574. ASSERT_FALSE(svr.is_running());
  3575. });
  3576. svr.wait_until_ready();
  3577. // Read PEM files
  3578. std::string cert_pem, key_pem, ca_pem;
  3579. read_file(SERVER_CERT_FILE, cert_pem);
  3580. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3581. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3582. // Update server certificates and client CA using PEM API while server running
  3583. ASSERT_TRUE(
  3584. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3585. // Connect with client certificate
  3586. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3587. cli.enable_server_certificate_verification(false);
  3588. cli.set_connection_timeout(30);
  3589. auto res = cli.Get("/test");
  3590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3591. ASSERT_EQ(StatusCode::OK_200, res->status);
  3592. ASSERT_TRUE(handler_called);
  3593. EXPECT_EQ("ok", res->body);
  3594. }
  3595. #endif
  3596. TEST(ErrorHandlerTest, ContentLength) {
  3597. Server svr;
  3598. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3599. res.status = StatusCode::OK_200;
  3600. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3601. "text/html"); // <= Content-Length still 13
  3602. });
  3603. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3604. res.set_content("Hello World!\n", "text/plain");
  3605. res.status = 524;
  3606. });
  3607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3608. auto se = detail::scope_exit([&] {
  3609. svr.stop();
  3610. thread.join();
  3611. ASSERT_FALSE(svr.is_running());
  3612. });
  3613. svr.wait_until_ready();
  3614. {
  3615. Client cli(HOST, PORT);
  3616. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3618. EXPECT_EQ(StatusCode::OK_200, res->status);
  3619. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3620. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3621. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3622. }
  3623. }
  3624. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3625. TEST(ExceptionTest, WithoutExceptionHandler) {
  3626. Server svr;
  3627. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3628. throw std::runtime_error("exception...");
  3629. });
  3630. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3631. throw std::runtime_error("exception\r\n...");
  3632. });
  3633. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3634. auto se = detail::scope_exit([&] {
  3635. svr.stop();
  3636. listen_thread.join();
  3637. ASSERT_FALSE(svr.is_running());
  3638. });
  3639. svr.wait_until_ready();
  3640. Client cli("localhost", PORT);
  3641. {
  3642. auto res = cli.Get("/exception");
  3643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3644. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3645. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3646. }
  3647. {
  3648. auto res = cli.Get("/unknown");
  3649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3650. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3651. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3652. }
  3653. }
  3654. TEST(ExceptionTest, WithExceptionHandler) {
  3655. Server svr;
  3656. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3657. std::exception_ptr ep) {
  3658. EXPECT_FALSE(ep == nullptr);
  3659. try {
  3660. std::rethrow_exception(ep);
  3661. } catch (std::exception &e) {
  3662. EXPECT_EQ("abc", std::string(e.what()));
  3663. } catch (...) {}
  3664. res.status = StatusCode::InternalServerError_500;
  3665. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3666. "text/html"); // <= Content-Length still 13 at this point
  3667. });
  3668. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3669. res.set_content("Hello World!\n", "text/plain");
  3670. throw std::runtime_error("abc");
  3671. });
  3672. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3673. auto se = detail::scope_exit([&] {
  3674. svr.stop();
  3675. thread.join();
  3676. ASSERT_FALSE(svr.is_running());
  3677. });
  3678. svr.wait_until_ready();
  3679. for (size_t i = 0; i < 10; i++) {
  3680. Client cli(HOST, PORT);
  3681. for (size_t j = 0; j < 100; j++) {
  3682. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3684. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3685. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3686. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3687. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3688. }
  3689. cli.set_keep_alive(true);
  3690. for (size_t j = 0; j < 100; j++) {
  3691. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3693. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3694. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3695. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3696. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3697. }
  3698. }
  3699. }
  3700. TEST(ExceptionTest, AndErrorHandler) {
  3701. Server svr;
  3702. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3703. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3704. });
  3705. svr.set_exception_handler(
  3706. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3707. EXPECT_FALSE(ep == nullptr);
  3708. try {
  3709. std::rethrow_exception(ep);
  3710. } catch (std::exception &e) {
  3711. res.set_content(e.what(), "text/html");
  3712. } catch (...) {}
  3713. res.status = StatusCode::InternalServerError_500;
  3714. });
  3715. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3716. throw std::runtime_error("EXCEPTION");
  3717. });
  3718. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3719. res.set_content("ERROR", "text/html");
  3720. res.status = StatusCode::InternalServerError_500;
  3721. });
  3722. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3723. auto se = detail::scope_exit([&] {
  3724. svr.stop();
  3725. thread.join();
  3726. ASSERT_FALSE(svr.is_running());
  3727. });
  3728. svr.wait_until_ready();
  3729. Client cli(HOST, PORT);
  3730. {
  3731. auto res = cli.Get("/exception");
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3734. EXPECT_EQ("EXCEPTION", res->body);
  3735. }
  3736. {
  3737. auto res = cli.Get("/error");
  3738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3739. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3740. EXPECT_EQ("ERROR", res->body);
  3741. }
  3742. {
  3743. auto res = cli.Get("/invalid");
  3744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3746. EXPECT_EQ("NOT_FOUND", res->body);
  3747. }
  3748. }
  3749. #endif
  3750. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3751. // process_request() wraps only routing() in a try/catch, so an exception from
  3752. // any other user callback used to unwind into the task queue - which does not
  3753. // catch - and terminate the process. Each test below runs the server on a
  3754. // single worker thread: a guard that catches the exception but still loses the
  3755. // thread would otherwise be hidden by a spare worker serving the follow-up
  3756. // request. Note that a regression here aborts the whole test binary rather
  3757. // than failing one test.
  3758. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3759. Server svr;
  3760. svr.new_task_queue = [] { return new ThreadPool(1); };
  3761. std::atomic<int> reported{0};
  3762. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3763. if (err == Error::UserCallbackException) { reported++; }
  3764. });
  3765. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3766. res.set_content_provider(
  3767. 1024, "text/plain",
  3768. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3769. sink.write("hello", 5);
  3770. throw std::runtime_error("from the content provider");
  3771. });
  3772. });
  3773. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3774. res.set_content("ok", "text/plain");
  3775. });
  3776. auto port = svr.bind_to_any_port(HOST);
  3777. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3778. auto se = detail::scope_exit([&] {
  3779. svr.stop();
  3780. listen_thread.join();
  3781. ASSERT_FALSE(svr.is_running());
  3782. });
  3783. svr.wait_until_ready();
  3784. {
  3785. Client cli(HOST, port);
  3786. cli.set_read_timeout(5, 0);
  3787. EXPECT_FALSE(cli.Get("/throw"));
  3788. }
  3789. EXPECT_TRUE(svr.is_running());
  3790. EXPECT_EQ(1, reported.load());
  3791. // A request on a fresh connection is still served.
  3792. {
  3793. Client cli(HOST, port);
  3794. auto res = cli.Get("/ok");
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. EXPECT_EQ("ok", res->body);
  3798. }
  3799. }
  3800. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3801. Server svr;
  3802. svr.new_task_queue = [] { return new ThreadPool(1); };
  3803. std::atomic<bool> should_throw{true};
  3804. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3805. res.set_content("hi", "text/plain");
  3806. });
  3807. svr.set_post_routing_handler(
  3808. [&](const Request & /*req*/, Response & /*res*/) {
  3809. if (should_throw) {
  3810. throw std::runtime_error("from the post-routing handler");
  3811. }
  3812. });
  3813. auto port = svr.bind_to_any_port(HOST);
  3814. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3815. auto se = detail::scope_exit([&] {
  3816. svr.stop();
  3817. listen_thread.join();
  3818. ASSERT_FALSE(svr.is_running());
  3819. });
  3820. svr.wait_until_ready();
  3821. {
  3822. Client cli(HOST, port);
  3823. cli.set_read_timeout(5, 0);
  3824. EXPECT_FALSE(cli.Get("/hi"));
  3825. }
  3826. EXPECT_TRUE(svr.is_running());
  3827. should_throw = false;
  3828. {
  3829. Client cli(HOST, port);
  3830. auto res = cli.Get("/hi");
  3831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3832. EXPECT_EQ(StatusCode::OK_200, res->status);
  3833. EXPECT_EQ("hi", res->body);
  3834. }
  3835. }
  3836. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3837. // The guard reports the caught exception through the error logger, which is
  3838. // a user callback too. A logger that throws has to be contained as well, or
  3839. // the process would terminate from inside the catch.
  3840. Server svr;
  3841. svr.new_task_queue = [] { return new ThreadPool(1); };
  3842. std::atomic<int> reported{0};
  3843. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3844. if (err == Error::UserCallbackException) {
  3845. reported++;
  3846. throw std::runtime_error("from the error logger");
  3847. }
  3848. });
  3849. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3850. res.set_content_provider(
  3851. 1024, "text/plain",
  3852. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3853. sink.write("hello", 5);
  3854. throw std::runtime_error("from the content provider");
  3855. });
  3856. });
  3857. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3858. res.set_content("ok", "text/plain");
  3859. });
  3860. auto port = svr.bind_to_any_port(HOST);
  3861. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3862. auto se = detail::scope_exit([&] {
  3863. svr.stop();
  3864. listen_thread.join();
  3865. ASSERT_FALSE(svr.is_running());
  3866. });
  3867. svr.wait_until_ready();
  3868. {
  3869. Client cli(HOST, port);
  3870. cli.set_read_timeout(5, 0);
  3871. EXPECT_FALSE(cli.Get("/throw"));
  3872. }
  3873. EXPECT_TRUE(svr.is_running());
  3874. EXPECT_EQ(1, reported.load());
  3875. {
  3876. Client cli(HOST, port);
  3877. auto res = cli.Get("/ok");
  3878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3879. EXPECT_EQ(StatusCode::OK_200, res->status);
  3880. EXPECT_EQ("ok", res->body);
  3881. }
  3882. }
  3883. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3884. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3885. // so the exception unwinds through the ws::WebSocket object on its way to
  3886. // the guard. None of the HTTP cases above cross that.
  3887. Server svr;
  3888. svr.new_task_queue = [] { return new ThreadPool(1); };
  3889. std::atomic<int> reported{0};
  3890. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3891. if (err == Error::UserCallbackException) { reported++; }
  3892. });
  3893. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3894. throw std::runtime_error("from the WebSocket handler");
  3895. });
  3896. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3897. res.set_content("ok", "text/plain");
  3898. });
  3899. auto port = svr.bind_to_any_port(HOST);
  3900. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3901. auto se = detail::scope_exit([&] {
  3902. svr.stop();
  3903. listen_thread.join();
  3904. ASSERT_FALSE(svr.is_running());
  3905. });
  3906. svr.wait_until_ready();
  3907. {
  3908. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3909. "/ws");
  3910. auto res = client.connect();
  3911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3912. // The server dropped the connection instead of dying.
  3913. std::string msg;
  3914. EXPECT_FALSE(client.read(msg));
  3915. client.close();
  3916. }
  3917. EXPECT_TRUE(svr.is_running());
  3918. EXPECT_EQ(1, reported.load());
  3919. {
  3920. Client cli(HOST, port);
  3921. auto res = cli.Get("/ok");
  3922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3923. EXPECT_EQ(StatusCode::OK_200, res->status);
  3924. EXPECT_EQ("ok", res->body);
  3925. }
  3926. }
  3927. #ifdef CPPHTTPLIB_SSL_ENABLED
  3928. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3929. // SSLServer::process_and_close_socket() is a separate overload with its own
  3930. // guard, so it is exercised on its own.
  3931. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3932. ASSERT_TRUE(svr.is_valid());
  3933. svr.new_task_queue = [] { return new ThreadPool(1); };
  3934. std::atomic<int> reported{0};
  3935. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3936. if (err == Error::UserCallbackException) { reported++; }
  3937. });
  3938. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3939. res.set_content_provider(
  3940. 1024, "text/plain",
  3941. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3942. sink.write("hello", 5);
  3943. throw std::runtime_error("from the content provider");
  3944. });
  3945. });
  3946. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3947. res.set_content("ok", "text/plain");
  3948. });
  3949. auto port = svr.bind_to_any_port(HOST);
  3950. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3951. auto se = detail::scope_exit([&] {
  3952. svr.stop();
  3953. listen_thread.join();
  3954. ASSERT_FALSE(svr.is_running());
  3955. });
  3956. svr.wait_until_ready();
  3957. {
  3958. SSLClient cli(HOST, port);
  3959. cli.enable_server_certificate_verification(false);
  3960. cli.set_read_timeout(5, 0);
  3961. EXPECT_FALSE(cli.Get("/throw"));
  3962. }
  3963. EXPECT_TRUE(svr.is_running());
  3964. EXPECT_EQ(1, reported.load());
  3965. {
  3966. SSLClient cli(HOST, port);
  3967. cli.enable_server_certificate_verification(false);
  3968. auto res = cli.Get("/ok");
  3969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3970. EXPECT_EQ(StatusCode::OK_200, res->status);
  3971. EXPECT_EQ("ok", res->body);
  3972. }
  3973. }
  3974. #endif
  3975. #endif
  3976. TEST(NoContentTest, ContentLength) {
  3977. Server svr;
  3978. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3979. res.status = StatusCode::NoContent_204;
  3980. });
  3981. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3982. auto se = detail::scope_exit([&] {
  3983. svr.stop();
  3984. thread.join();
  3985. ASSERT_FALSE(svr.is_running());
  3986. });
  3987. svr.wait_until_ready();
  3988. {
  3989. Client cli(HOST, PORT);
  3990. auto res = cli.Get("/hi");
  3991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3992. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3993. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3994. }
  3995. }
  3996. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3997. #ifdef CPPHTTPLIB_SSL_ENABLED
  3998. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3999. ASSERT_TRUE(svr.is_valid());
  4000. #else
  4001. Server svr;
  4002. #endif
  4003. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4004. if (req.path == "/routing_handler") {
  4005. res.set_header("PRE_ROUTING", "on");
  4006. res.set_content("Routing Handler", "text/plain");
  4007. return httplib::Server::HandlerResponse::Handled;
  4008. }
  4009. return httplib::Server::HandlerResponse::Unhandled;
  4010. });
  4011. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4012. res.set_content("Error", "text/html");
  4013. });
  4014. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4015. if (req.path == "/routing_handler") {
  4016. res.set_header("POST_ROUTING", "on");
  4017. }
  4018. });
  4019. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4020. res.set_content("Hello World!\n", "text/plain");
  4021. });
  4022. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4023. auto se = detail::scope_exit([&] {
  4024. svr.stop();
  4025. thread.join();
  4026. ASSERT_FALSE(svr.is_running());
  4027. });
  4028. svr.wait_until_ready();
  4029. {
  4030. #ifdef CPPHTTPLIB_SSL_ENABLED
  4031. SSLClient cli(HOST, PORT);
  4032. cli.enable_server_certificate_verification(false);
  4033. #else
  4034. Client cli(HOST, PORT);
  4035. #endif
  4036. auto res = cli.Get("/routing_handler");
  4037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4038. EXPECT_EQ(StatusCode::OK_200, res->status);
  4039. EXPECT_EQ("Routing Handler", res->body);
  4040. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4041. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4042. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4043. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4044. }
  4045. {
  4046. #ifdef CPPHTTPLIB_SSL_ENABLED
  4047. SSLClient cli(HOST, PORT);
  4048. cli.enable_server_certificate_verification(false);
  4049. #else
  4050. Client cli(HOST, PORT);
  4051. #endif
  4052. auto res = cli.Get("/hi");
  4053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4054. EXPECT_EQ(StatusCode::OK_200, res->status);
  4055. EXPECT_EQ("Hello World!\n", res->body);
  4056. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4057. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4058. }
  4059. {
  4060. #ifdef CPPHTTPLIB_SSL_ENABLED
  4061. SSLClient cli(HOST, PORT);
  4062. cli.enable_server_certificate_verification(false);
  4063. #else
  4064. Client cli(HOST, PORT);
  4065. #endif
  4066. auto res = cli.Get("/aaa");
  4067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4068. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4069. EXPECT_EQ("Error", res->body);
  4070. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4071. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4072. }
  4073. }
  4074. TEST(RequestHandlerTest, PreRequestHandler) {
  4075. auto route_path = "/user/:user";
  4076. Server svr;
  4077. svr.Get("/hi", [](const Request &, Response &res) {
  4078. res.set_content("hi", "text/plain");
  4079. });
  4080. svr.Get(route_path, [](const Request &req, Response &res) {
  4081. res.set_content(req.path_params.at("user"), "text/plain");
  4082. });
  4083. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4084. if (req.matched_route == route_path) {
  4085. auto user = req.path_params.at("user");
  4086. if (user != "john") {
  4087. res.status = StatusCode::Forbidden_403;
  4088. res.set_content("error", "text/html");
  4089. return Server::HandlerResponse::Handled;
  4090. }
  4091. }
  4092. return Server::HandlerResponse::Unhandled;
  4093. });
  4094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4095. auto se = detail::scope_exit([&] {
  4096. svr.stop();
  4097. thread.join();
  4098. ASSERT_FALSE(svr.is_running());
  4099. });
  4100. svr.wait_until_ready();
  4101. Client cli(HOST, PORT);
  4102. {
  4103. auto res = cli.Get("/hi");
  4104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4105. EXPECT_EQ(StatusCode::OK_200, res->status);
  4106. EXPECT_EQ("hi", res->body);
  4107. }
  4108. {
  4109. auto res = cli.Get("/user/john");
  4110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4111. EXPECT_EQ(StatusCode::OK_200, res->status);
  4112. EXPECT_EQ("john", res->body);
  4113. }
  4114. {
  4115. auto res = cli.Get("/user/invalid-user");
  4116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4117. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4118. EXPECT_EQ("error", res->body);
  4119. }
  4120. }
  4121. // The pre-request handler must run before the request body is read, so a
  4122. // rejected request never forces the server to buffer a (potentially large)
  4123. // body. Here the posted body is larger than the payload limit: if the body
  4124. // were read first the server would answer 413, but because the pre-request
  4125. // handler runs first it answers 403 and the body is never read.
  4126. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4127. Server svr;
  4128. svr.set_payload_max_length(8);
  4129. auto handler_ran = false;
  4130. svr.Post("/reject", [&](const Request &req, Response &res) {
  4131. handler_ran = true;
  4132. res.set_content(req.body, "text/plain");
  4133. });
  4134. svr.Post("/accept", [](const Request &req, Response &res) {
  4135. res.set_content(req.body, "text/plain");
  4136. });
  4137. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4138. if (req.matched_route == "/reject") {
  4139. res.status = StatusCode::Forbidden_403;
  4140. res.set_content("denied", "text/plain");
  4141. return Server::HandlerResponse::Handled;
  4142. }
  4143. return Server::HandlerResponse::Unhandled;
  4144. });
  4145. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4146. auto se = detail::scope_exit([&] {
  4147. svr.stop();
  4148. thread.join();
  4149. ASSERT_FALSE(svr.is_running());
  4150. });
  4151. svr.wait_until_ready();
  4152. Client cli(HOST, PORT);
  4153. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4154. // rejects with 403 before the body is read, so 413 is never reached.
  4155. {
  4156. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4158. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4159. EXPECT_EQ("denied", res->body);
  4160. EXPECT_FALSE(handler_ran);
  4161. }
  4162. // An approved route still reads the body and enforces the payload limit.
  4163. {
  4164. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4166. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4167. }
  4168. }
  4169. TEST(UserDataTest, BasicOperations) {
  4170. httplib::UserData ud;
  4171. // Initially empty
  4172. EXPECT_FALSE(ud.has("key"));
  4173. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4174. // set and get
  4175. ud.set("key", 42);
  4176. EXPECT_TRUE(ud.has("key"));
  4177. auto *p = ud.get<int>("key");
  4178. ASSERT_NE(nullptr, p);
  4179. EXPECT_EQ(42, *p);
  4180. // Type mismatch → nullptr
  4181. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4182. // Overwrite with different type
  4183. ud.set("key", std::string("hello"));
  4184. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4185. auto *s = ud.get<std::string>("key");
  4186. ASSERT_NE(nullptr, s);
  4187. EXPECT_EQ("hello", *s);
  4188. // erase
  4189. ud.erase("key");
  4190. EXPECT_FALSE(ud.has("key"));
  4191. // clear
  4192. ud.set("a", 1);
  4193. ud.set("b", 2);
  4194. ud.clear();
  4195. EXPECT_FALSE(ud.has("a"));
  4196. EXPECT_FALSE(ud.has("b"));
  4197. }
  4198. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4199. struct AuthCtx {
  4200. std::string user_id;
  4201. };
  4202. Server svr;
  4203. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4204. res.user_data.set("auth", AuthCtx{"alice"});
  4205. return Server::HandlerResponse::Unhandled;
  4206. });
  4207. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4208. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4209. ASSERT_NE(nullptr, ctx);
  4210. res.set_content("Hello " + ctx->user_id, "text/plain");
  4211. });
  4212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4213. auto se = detail::scope_exit([&] {
  4214. svr.stop();
  4215. thread.join();
  4216. ASSERT_FALSE(svr.is_running());
  4217. });
  4218. svr.wait_until_ready();
  4219. Client cli(HOST, PORT);
  4220. auto res = cli.Get("/me");
  4221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4222. EXPECT_EQ(StatusCode::OK_200, res->status);
  4223. EXPECT_EQ("Hello alice", res->body);
  4224. }
  4225. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4226. struct RoleCtx {
  4227. std::string role;
  4228. };
  4229. Server svr;
  4230. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4231. res.user_data.set("role", RoleCtx{"admin"});
  4232. return Server::HandlerResponse::Unhandled;
  4233. });
  4234. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4235. auto *ctx = res.user_data.get<RoleCtx>("role");
  4236. ASSERT_NE(nullptr, ctx);
  4237. res.set_content(ctx->role, "text/plain");
  4238. });
  4239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4240. auto se = detail::scope_exit([&] {
  4241. svr.stop();
  4242. thread.join();
  4243. ASSERT_FALSE(svr.is_running());
  4244. });
  4245. svr.wait_until_ready();
  4246. Client cli(HOST, PORT);
  4247. auto res = cli.Get("/role");
  4248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4249. EXPECT_EQ(StatusCode::OK_200, res->status);
  4250. EXPECT_EQ("admin", res->body);
  4251. }
  4252. TEST(InvalidFormatTest, StatusCode) {
  4253. Server svr;
  4254. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4255. res.set_content("Hello World!\n", "text/plain");
  4256. res.status = 9999; // Status should be a three-digit code...
  4257. });
  4258. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4259. auto se = detail::scope_exit([&] {
  4260. svr.stop();
  4261. thread.join();
  4262. ASSERT_FALSE(svr.is_running());
  4263. });
  4264. svr.wait_until_ready();
  4265. {
  4266. Client cli(HOST, PORT);
  4267. auto res = cli.Get("/hi");
  4268. ASSERT_FALSE(res);
  4269. }
  4270. }
  4271. TEST(URLFragmentTest, WithFragment) {
  4272. Server svr;
  4273. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4274. EXPECT_TRUE(req.target == "/hi");
  4275. });
  4276. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4277. auto se = detail::scope_exit([&] {
  4278. svr.stop();
  4279. thread.join();
  4280. ASSERT_FALSE(svr.is_running());
  4281. });
  4282. svr.wait_until_ready();
  4283. {
  4284. Client cli(HOST, PORT);
  4285. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4286. EXPECT_TRUE(res);
  4287. EXPECT_EQ(StatusCode::OK_200, res->status);
  4288. res = cli.Get("/hi%23key1=val1=key2=val2");
  4289. EXPECT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4291. }
  4292. }
  4293. TEST(HeaderWriter, SetHeaderWriter) {
  4294. Server svr;
  4295. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4296. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4297. return detail::write_headers(strm, hdrs);
  4298. });
  4299. svr.Get("/hi", [](const Request &req, Response &res) {
  4300. auto it = req.headers.find("CustomClientHeader");
  4301. EXPECT_TRUE(it != req.headers.end());
  4302. EXPECT_EQ(it->second, "CustomClientValue");
  4303. res.set_content("Hello World!\n", "text/plain");
  4304. });
  4305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4306. auto se = detail::scope_exit([&] {
  4307. svr.stop();
  4308. thread.join();
  4309. ASSERT_FALSE(svr.is_running());
  4310. });
  4311. svr.wait_until_ready();
  4312. {
  4313. Client cli(HOST, PORT);
  4314. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4315. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4316. return detail::write_headers(strm, hdrs);
  4317. });
  4318. auto res = cli.Get("/hi");
  4319. EXPECT_TRUE(res);
  4320. EXPECT_EQ(StatusCode::OK_200, res->status);
  4321. auto it = res->headers.find("CustomServerHeader");
  4322. EXPECT_TRUE(it != res->headers.end());
  4323. EXPECT_EQ(it->second, "CustomServerValue");
  4324. }
  4325. }
  4326. class ServerTest : public ::testing::Test {
  4327. protected:
  4328. ServerTest()
  4329. : cli_(HOST, PORT)
  4330. #ifdef CPPHTTPLIB_SSL_ENABLED
  4331. ,
  4332. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4333. #endif
  4334. {
  4335. #ifdef CPPHTTPLIB_SSL_ENABLED
  4336. cli_.enable_server_certificate_verification(false);
  4337. #endif
  4338. // Allow LARGE_DATA (100MB) responses
  4339. cli_.set_payload_max_length(200 * 1024 * 1024);
  4340. }
  4341. virtual void SetUp() {
  4342. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4343. svr_.set_payload_max_length(200 * 1024 * 1024);
  4344. svr_.set_mount_point("/", "./www");
  4345. svr_.set_mount_point("/mount", "./www2");
  4346. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4347. svr_.Get("/hi",
  4348. [&](const Request & /*req*/, Response &res) {
  4349. res.set_content("Hello World!", "text/plain");
  4350. })
  4351. .Get("/file_content",
  4352. [&](const Request & /*req*/, Response &res) {
  4353. res.set_file_content("./www/dir/test.html");
  4354. })
  4355. .Get("/file_content_with_content_type",
  4356. [&](const Request & /*req*/, Response &res) {
  4357. res.set_file_content("./www/file", "text/plain");
  4358. })
  4359. .Get("/invalid_file_content",
  4360. [&](const Request & /*req*/, Response &res) {
  4361. res.set_file_content("./www/dir/invalid_file_path");
  4362. })
  4363. .Get("/http_response_splitting",
  4364. [&](const Request & /*req*/, Response &res) {
  4365. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4366. EXPECT_EQ(0U, res.headers.size());
  4367. EXPECT_FALSE(res.has_header("a"));
  4368. res.set_header("a", "1\nSet-Cookie: a=1");
  4369. EXPECT_EQ(0U, res.headers.size());
  4370. EXPECT_FALSE(res.has_header("a"));
  4371. res.set_header("a", "1\rSet-Cookie: a=1");
  4372. EXPECT_EQ(0U, res.headers.size());
  4373. EXPECT_FALSE(res.has_header("a"));
  4374. res.set_header("a\r\nb", "0");
  4375. EXPECT_EQ(0U, res.headers.size());
  4376. EXPECT_FALSE(res.has_header("a"));
  4377. res.set_header("a\rb", "0");
  4378. EXPECT_EQ(0U, res.headers.size());
  4379. EXPECT_FALSE(res.has_header("a"));
  4380. res.set_header("a\nb", "0");
  4381. EXPECT_EQ(0U, res.headers.size());
  4382. EXPECT_FALSE(res.has_header("a"));
  4383. res.set_redirect("1\r\nSet-Cookie: a=1");
  4384. EXPECT_EQ(0U, res.headers.size());
  4385. EXPECT_FALSE(res.has_header("Location"));
  4386. })
  4387. .Get("/slow",
  4388. [&](const Request & /*req*/, Response &res) {
  4389. std::this_thread::sleep_for(std::chrono::seconds(4));
  4390. res.set_content("slow", "text/plain");
  4391. })
  4392. #if 0
  4393. .Post("/slowpost",
  4394. [&](const Request & /*req*/, Response &res) {
  4395. std::this_thread::sleep_for(std::chrono::seconds(2));
  4396. res.set_content("slow", "text/plain");
  4397. })
  4398. #endif
  4399. .Get("/remote_addr",
  4400. [&](const Request &req, Response &res) {
  4401. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4402. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4403. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4404. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4405. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4406. #endif
  4407. res.set_content(req.remote_addr, "text/plain");
  4408. })
  4409. .Get("/local_addr",
  4410. [&](const Request &req, Response &res) {
  4411. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4412. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4413. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4414. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4415. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4416. #endif
  4417. auto local_addr = req.local_addr;
  4418. auto local_port = std::to_string(req.local_port);
  4419. res.set_content(local_addr.append(":").append(local_port),
  4420. "text/plain");
  4421. })
  4422. .Get("/endwith%",
  4423. [&](const Request & /*req*/, Response &res) {
  4424. res.set_content("Hello World!", "text/plain");
  4425. })
  4426. .Get("/a\\+\\+b",
  4427. [&](const Request &req, Response &res) {
  4428. ASSERT_TRUE(req.has_param("a +b"));
  4429. auto val = req.get_param_value("a +b");
  4430. res.set_content(val, "text/plain");
  4431. })
  4432. .Get("/", [&](const Request & /*req*/,
  4433. Response &res) { res.set_redirect("/hi"); })
  4434. .Post("/1",
  4435. [](const Request & /*req*/, Response &res) {
  4436. res.set_redirect("/2", StatusCode::SeeOther_303);
  4437. })
  4438. .Get("/2",
  4439. [](const Request & /*req*/, Response &res) {
  4440. res.set_content("redirected.", "text/plain");
  4441. res.status = StatusCode::OK_200;
  4442. })
  4443. .Post("/person",
  4444. [&](const Request &req, Response &res) {
  4445. if (req.has_param("name") && req.has_param("note")) {
  4446. persons_[req.get_param_value("name")] =
  4447. req.get_param_value("note");
  4448. } else {
  4449. res.status = StatusCode::BadRequest_400;
  4450. }
  4451. })
  4452. .Put("/person",
  4453. [&](const Request &req, Response &res) {
  4454. if (req.has_param("name") && req.has_param("note")) {
  4455. persons_[req.get_param_value("name")] =
  4456. req.get_param_value("note");
  4457. } else {
  4458. res.status = StatusCode::BadRequest_400;
  4459. }
  4460. })
  4461. .Get("/person/(.*)",
  4462. [&](const Request &req, Response &res) {
  4463. string name = req.matches[1];
  4464. if (persons_.find(name) != persons_.end()) {
  4465. auto note = persons_[name];
  4466. res.set_content(note, "text/plain");
  4467. } else {
  4468. res.status = StatusCode::NotFound_404;
  4469. }
  4470. })
  4471. .Delete("/person",
  4472. [&](const Request &req, Response &res) {
  4473. if (req.has_param("name")) {
  4474. string name = req.get_param_value("name");
  4475. if (persons_.find(name) != persons_.end()) {
  4476. persons_.erase(name);
  4477. res.set_content("DELETED", "text/plain");
  4478. } else {
  4479. res.status = StatusCode::NotFound_404;
  4480. }
  4481. } else {
  4482. res.status = StatusCode::BadRequest_400;
  4483. }
  4484. })
  4485. .Post("/x-www-form-urlencoded-json",
  4486. [&](const Request &req, Response &res) {
  4487. auto json = req.get_param_value("json");
  4488. ASSERT_EQ(JSON_DATA, json);
  4489. res.set_content(json, "appliation/json");
  4490. res.status = StatusCode::OK_200;
  4491. })
  4492. .Get("/streamed-chunked",
  4493. [&](const Request & /*req*/, Response &res) {
  4494. res.set_chunked_content_provider(
  4495. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4496. sink.os << "123";
  4497. sink.os << "456";
  4498. sink.os << "789";
  4499. sink.done();
  4500. return true;
  4501. });
  4502. })
  4503. .Get("/streamed-chunked-with-prohibited-trailer",
  4504. [&](const Request & /*req*/, Response &res) {
  4505. auto i = new int(0);
  4506. // Declare both a prohibited trailer (Content-Length) and an
  4507. // allowed one
  4508. res.set_header("Trailer", "Content-Length, X-Allowed");
  4509. res.set_chunked_content_provider(
  4510. "text/plain",
  4511. [i](size_t /*offset*/, DataSink &sink) {
  4512. switch (*i) {
  4513. case 0: sink.os << "123"; break;
  4514. case 1: sink.os << "456"; break;
  4515. case 2: sink.os << "789"; break;
  4516. case 3: {
  4517. sink.done_with_trailer(
  4518. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4519. } break;
  4520. }
  4521. (*i)++;
  4522. return true;
  4523. },
  4524. [i](bool success) {
  4525. EXPECT_TRUE(success);
  4526. delete i;
  4527. });
  4528. })
  4529. .Get("/streamed-chunked2",
  4530. [&](const Request & /*req*/, Response &res) {
  4531. auto i = new int(0);
  4532. res.set_chunked_content_provider(
  4533. "text/plain",
  4534. [i](size_t /*offset*/, DataSink &sink) {
  4535. switch (*i) {
  4536. case 0: sink.os << "123"; break;
  4537. case 1: sink.os << "456"; break;
  4538. case 2: sink.os << "789"; break;
  4539. case 3: sink.done(); break;
  4540. }
  4541. (*i)++;
  4542. return true;
  4543. },
  4544. [i](bool success) {
  4545. EXPECT_TRUE(success);
  4546. delete i;
  4547. });
  4548. })
  4549. .Get("/streamed-chunked-with-trailer",
  4550. [&](const Request & /*req*/, Response &res) {
  4551. auto i = new int(0);
  4552. res.set_header("Trailer", "Dummy1, Dummy2");
  4553. res.set_chunked_content_provider(
  4554. "text/plain",
  4555. [i](size_t /*offset*/, DataSink &sink) {
  4556. switch (*i) {
  4557. case 0: sink.os << "123"; break;
  4558. case 1: sink.os << "456"; break;
  4559. case 2: sink.os << "789"; break;
  4560. case 3: {
  4561. sink.done_with_trailer(
  4562. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4563. } break;
  4564. }
  4565. (*i)++;
  4566. return true;
  4567. },
  4568. [i](bool success) {
  4569. EXPECT_TRUE(success);
  4570. delete i;
  4571. });
  4572. })
  4573. .Get("/streamed",
  4574. [&](const Request & /*req*/, Response &res) {
  4575. res.set_content_provider(
  4576. 6, "text/plain",
  4577. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4578. sink.os << (offset < 3 ? "a" : "b");
  4579. return true;
  4580. });
  4581. })
  4582. .Get("/streamed-without-length",
  4583. [&](const Request & /*req*/, Response &res) {
  4584. auto data = new std::string("abcdefg");
  4585. res.set_content_provider(
  4586. "text/plain",
  4587. [data](size_t offset, DataSink &sink) {
  4588. if (offset < data->size()) {
  4589. sink.os << data->substr(offset);
  4590. }
  4591. sink.done();
  4592. return true;
  4593. },
  4594. [data](bool success) {
  4595. EXPECT_TRUE(success);
  4596. delete data;
  4597. });
  4598. })
  4599. .Get("/streamed-with-range",
  4600. [&](const Request &req, Response &res) {
  4601. auto data = new std::string("abcdefg");
  4602. // An explicit status keeps the server from picking the 206 it
  4603. // would otherwise choose for a ranged request, so the response
  4604. // is not a partial representation.
  4605. auto status = req.get_param_value("status");
  4606. if (status == "200") {
  4607. res.status = StatusCode::OK_200;
  4608. } else if (status == "403") {
  4609. res.status = StatusCode::Forbidden_403;
  4610. }
  4611. res.set_content_provider(
  4612. data->size(), "text/plain",
  4613. [data](size_t offset, size_t length, DataSink &sink) {
  4614. size_t DATA_CHUNK_SIZE = 4;
  4615. const auto &d = *data;
  4616. auto out_len =
  4617. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4618. auto ret =
  4619. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4620. EXPECT_TRUE(ret);
  4621. return true;
  4622. },
  4623. [data, &req](bool success) {
  4624. EXPECT_EQ(success, !req.has_param("error"));
  4625. delete data;
  4626. });
  4627. })
  4628. .Get("/streamed-cancel",
  4629. [&](const Request & /*req*/, Response &res) {
  4630. res.set_content_provider(
  4631. size_t(-1), "text/plain",
  4632. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4633. sink.os << "data_chunk";
  4634. return true;
  4635. });
  4636. })
  4637. .Get("/regex-with-delimiter",
  4638. [&](const Request &req, Response & /*res*/) {
  4639. ASSERT_TRUE(req.has_param("key"));
  4640. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4641. })
  4642. .Get("/with-range",
  4643. [&](const Request & /*req*/, Response &res) {
  4644. res.set_content("abcdefg", "text/plain");
  4645. })
  4646. .Get("/test-start-time",
  4647. [&](const Request &req, Response & /*res*/) {
  4648. EXPECT_NE(req.start_time_,
  4649. std::chrono::steady_clock::time_point::min());
  4650. })
  4651. .Get("/with-range-customized-response",
  4652. [&](const Request & /*req*/, Response &res) {
  4653. res.status = StatusCode::BadRequest_400;
  4654. res.set_content(JSON_DATA, "application/json");
  4655. })
  4656. .Post("/chunked",
  4657. [&](const Request &req, Response & /*res*/) {
  4658. EXPECT_EQ(req.body, "dechunked post body");
  4659. })
  4660. .Post("/large-chunked",
  4661. [&](const Request &req, Response & /*res*/) {
  4662. std::string expected(6 * 30 * 1024u, 'a');
  4663. EXPECT_EQ(req.body, expected);
  4664. })
  4665. .Post("/multipart",
  4666. [&](const Request &req, Response & /*res*/) {
  4667. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4668. req.form.get_field_count("text2") +
  4669. req.form.get_field_count("file3") +
  4670. req.form.get_field_count("file4"));
  4671. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4672. req.form.get_file_count("file2"));
  4673. ASSERT_TRUE(!req.form.has_file("???"));
  4674. ASSERT_TRUE(!req.form.has_field("???"));
  4675. ASSERT_TRUE(req.body.empty());
  4676. {
  4677. const auto &text = req.form.get_field("text1");
  4678. EXPECT_EQ("text default", text);
  4679. }
  4680. {
  4681. const auto &text = req.form.get_field("text2");
  4682. EXPECT_EQ("aωb", text);
  4683. }
  4684. {
  4685. const auto &file = req.form.get_file("file1");
  4686. EXPECT_EQ("hello.txt", file.filename);
  4687. EXPECT_EQ("text/plain", file.content_type);
  4688. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4689. }
  4690. {
  4691. const auto &file = req.form.get_file("file2");
  4692. EXPECT_EQ("world.json", file.filename);
  4693. EXPECT_EQ("application/json", file.content_type);
  4694. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4695. }
  4696. {
  4697. const auto &text = req.form.get_field("file3");
  4698. EXPECT_EQ(0u, text.size());
  4699. }
  4700. {
  4701. const auto &text = req.form.get_field("file4");
  4702. EXPECT_EQ(0u, text.size());
  4703. }
  4704. })
  4705. .Post("/multipart/multi_file_values",
  4706. [&](const Request &req, Response & /*res*/) {
  4707. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4708. req.form.get_field_count("multi_text1"));
  4709. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4710. ASSERT_TRUE(!req.form.has_file("???"));
  4711. ASSERT_TRUE(!req.form.has_field("???"));
  4712. ASSERT_TRUE(req.body.empty());
  4713. {
  4714. const auto &text = req.form.get_field("text");
  4715. EXPECT_EQ("default text", text);
  4716. }
  4717. {
  4718. const auto &text1_values = req.form.get_fields("multi_text1");
  4719. EXPECT_EQ(2u, text1_values.size());
  4720. EXPECT_EQ("aaaaa", text1_values[0]);
  4721. EXPECT_EQ("bbbbb", text1_values[1]);
  4722. }
  4723. {
  4724. const auto &file1_values = req.form.get_files("multi_file1");
  4725. EXPECT_EQ(2u, file1_values.size());
  4726. auto file1 = file1_values[0];
  4727. EXPECT_EQ(file1.filename, "hello.txt");
  4728. EXPECT_EQ(file1.content_type, "text/plain");
  4729. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4730. auto file2 = file1_values[1];
  4731. EXPECT_EQ(file2.filename, "world.json");
  4732. EXPECT_EQ(file2.content_type, "application/json");
  4733. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4734. }
  4735. })
  4736. .Post("/empty",
  4737. [&](const Request &req, Response &res) {
  4738. EXPECT_EQ(req.body, "");
  4739. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4740. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4741. res.set_content("empty", "text/plain");
  4742. })
  4743. .Post("/empty-no-content-type",
  4744. [&](const Request &req, Response &res) {
  4745. EXPECT_EQ(req.body, "");
  4746. EXPECT_FALSE(req.has_header("Content-Type"));
  4747. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4748. res.set_content("empty-no-content-type", "text/plain");
  4749. })
  4750. .Post("/path-only",
  4751. [&](const Request &req, Response &res) {
  4752. EXPECT_EQ(req.body, "");
  4753. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4754. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4755. res.set_content("path-only", "text/plain");
  4756. })
  4757. .Post("/path-headers-only",
  4758. [&](const Request &req, Response &res) {
  4759. EXPECT_EQ(req.body, "");
  4760. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4761. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4762. EXPECT_EQ("world", req.get_header_value("hello"));
  4763. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4764. res.set_content("path-headers-only", "text/plain");
  4765. })
  4766. .Post("/post-large",
  4767. [&](const Request &req, Response &res) {
  4768. EXPECT_EQ(req.body, LARGE_DATA);
  4769. res.set_content(req.body, "text/plain");
  4770. })
  4771. .Post("/post-loopback",
  4772. [&](const Request &, Response &res,
  4773. ContentReader const &content_reader) {
  4774. std::string body;
  4775. content_reader([&](const char *data, size_t data_length) {
  4776. body.append(data, data_length);
  4777. return true;
  4778. });
  4779. res.set_content(body, "text/plain");
  4780. })
  4781. .Put("/put-loopback",
  4782. [&](const Request &, Response &res,
  4783. ContentReader const &content_reader) {
  4784. std::string body;
  4785. content_reader([&](const char *data, size_t data_length) {
  4786. body.append(data, data_length);
  4787. return true;
  4788. });
  4789. res.set_content(body, "text/plain");
  4790. })
  4791. .Patch("/patch-loopback",
  4792. [&](const Request &, Response &res,
  4793. ContentReader const &content_reader) {
  4794. std::string body;
  4795. content_reader([&](const char *data, size_t data_length) {
  4796. body.append(data, data_length);
  4797. return true;
  4798. });
  4799. res.set_content(body, "text/plain");
  4800. })
  4801. .Put("/empty-no-content-type",
  4802. [&](const Request &req, Response &res) {
  4803. EXPECT_EQ(req.body, "");
  4804. EXPECT_FALSE(req.has_header("Content-Type"));
  4805. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4806. res.set_content("empty-no-content-type", "text/plain");
  4807. })
  4808. .Put("/put",
  4809. [&](const Request &req, Response &res) {
  4810. EXPECT_EQ(req.body, "PUT");
  4811. res.set_content(req.body, "text/plain");
  4812. })
  4813. .Put("/put-large",
  4814. [&](const Request &req, Response &res) {
  4815. EXPECT_EQ(req.body, LARGE_DATA);
  4816. res.set_content(req.body, "text/plain");
  4817. })
  4818. .Patch("/patch",
  4819. [&](const Request &req, Response &res) {
  4820. EXPECT_EQ(req.body, "PATCH");
  4821. res.set_content(req.body, "text/plain");
  4822. })
  4823. .Delete("/delete",
  4824. [&](const Request & /*req*/, Response &res) {
  4825. res.set_content("DELETE", "text/plain");
  4826. })
  4827. .Delete("/delete-body",
  4828. [&](const Request &req, Response &res) {
  4829. EXPECT_EQ(req.body, "content");
  4830. res.set_content(req.body, "text/plain");
  4831. })
  4832. .Options(R"(\*)",
  4833. [&](const Request & /*req*/, Response &res) {
  4834. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4835. })
  4836. .CustomRoute("PROPFIND", "/dav/:id",
  4837. [&](const Request &req, Response &res) {
  4838. res.set_header("x-body-size",
  4839. std::to_string(req.body.size()));
  4840. res.set_header("x-matched-route", req.matched_route);
  4841. res.set_header("x-dav-id", req.path_params.at("id"));
  4842. res.status = StatusCode::MultiStatus_207;
  4843. res.set_content(req.body, "application/xml");
  4844. })
  4845. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4846. [&](const Request &req, Response &res) {
  4847. res.set_header("x-dav-match", req.matches[1]);
  4848. res.status = StatusCode::MultiStatus_207;
  4849. })
  4850. .CustomRoute("MKCOL", "/dav-mkcol",
  4851. [&](const Request &req, Response &res) {
  4852. EXPECT_TRUE(req.body.empty());
  4853. res.status = StatusCode::Created_201;
  4854. })
  4855. .CustomRoute(
  4856. "REPORT", "/dav-report",
  4857. [&](const Request & /*req*/, Response &res,
  4858. const ContentReader &content_reader) {
  4859. std::string body;
  4860. content_reader([&](const char *data, size_t data_length) {
  4861. body.append(data, data_length);
  4862. return true;
  4863. });
  4864. res.set_header("x-body-size", std::to_string(body.size()));
  4865. res.status = StatusCode::MultiStatus_207;
  4866. res.set_content(body, "application/xml");
  4867. })
  4868. .Get("/request-target",
  4869. [&](const Request &req, Response & /*res*/) {
  4870. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4871. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4872. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4873. })
  4874. .Get("/long-query-value",
  4875. [&](const Request &req, Response & /*res*/) {
  4876. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4877. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4878. })
  4879. .Get("/too-long-query-value",
  4880. [&](const Request &req, Response & /*res*/) {
  4881. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4882. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4883. })
  4884. .Get("/array-param",
  4885. [&](const Request &req, Response & /*res*/) {
  4886. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4887. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4888. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4889. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4890. })
  4891. .Get("/array-param-values",
  4892. [&](const Request &req, Response & /*res*/) {
  4893. auto values = req.get_param_values("array");
  4894. EXPECT_EQ(3u, values.size());
  4895. EXPECT_EQ("value1", values[0]);
  4896. EXPECT_EQ("value2", values[1]);
  4897. EXPECT_EQ("value3", values[2]);
  4898. auto empty = req.get_param_values("nonexistent");
  4899. EXPECT_TRUE(empty.empty());
  4900. })
  4901. .Post("/validate-no-multiple-headers",
  4902. [&](const Request &req, Response & /*res*/) {
  4903. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4904. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4905. })
  4906. .Post("/content_receiver",
  4907. [&](const Request &req, Response &res,
  4908. const ContentReader &content_reader) {
  4909. if (req.is_multipart_form_data()) {
  4910. std::vector<FormData> items;
  4911. content_reader(
  4912. [&](const FormData &file) {
  4913. items.push_back(file);
  4914. return true;
  4915. },
  4916. [&](const char *data, size_t data_length) {
  4917. items.back().content.append(data, data_length);
  4918. return true;
  4919. });
  4920. EXPECT_EQ(5u, items.size());
  4921. {
  4922. const auto &file = get_file_value(items, "text1");
  4923. EXPECT_TRUE(file.filename.empty());
  4924. EXPECT_EQ("text default", file.content);
  4925. }
  4926. {
  4927. const auto &file = get_file_value(items, "text2");
  4928. EXPECT_TRUE(file.filename.empty());
  4929. EXPECT_EQ("aωb", file.content);
  4930. }
  4931. {
  4932. const auto &file = get_file_value(items, "file1");
  4933. EXPECT_EQ("hello.txt", file.filename);
  4934. EXPECT_EQ("text/plain", file.content_type);
  4935. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4936. }
  4937. {
  4938. const auto &file = get_file_value(items, "file2");
  4939. EXPECT_EQ("world.json", file.filename);
  4940. EXPECT_EQ("application/json", file.content_type);
  4941. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4942. }
  4943. {
  4944. const auto &file = get_file_value(items, "file3");
  4945. EXPECT_TRUE(file.filename.empty());
  4946. EXPECT_EQ("application/octet-stream", file.content_type);
  4947. EXPECT_EQ(0u, file.content.size());
  4948. }
  4949. } else {
  4950. std::string body;
  4951. content_reader([&](const char *data, size_t data_length) {
  4952. EXPECT_EQ(7U, data_length);
  4953. body.append(data, data_length);
  4954. return true;
  4955. });
  4956. EXPECT_EQ(body, "content");
  4957. res.set_content(body, "text/plain");
  4958. }
  4959. })
  4960. .Put("/content_receiver",
  4961. [&](const Request & /*req*/, Response &res,
  4962. const ContentReader &content_reader) {
  4963. std::string body;
  4964. content_reader([&](const char *data, size_t data_length) {
  4965. body.append(data, data_length);
  4966. return true;
  4967. });
  4968. EXPECT_EQ(body, "content");
  4969. res.set_content(body, "text/plain");
  4970. })
  4971. .Patch("/content_receiver",
  4972. [&](const Request & /*req*/, Response &res,
  4973. const ContentReader &content_reader) {
  4974. std::string body;
  4975. content_reader([&](const char *data, size_t data_length) {
  4976. body.append(data, data_length);
  4977. return true;
  4978. });
  4979. EXPECT_EQ(body, "content");
  4980. res.set_content(body, "text/plain");
  4981. })
  4982. .Post("/query-string-and-body",
  4983. [&](const Request &req, Response & /*res*/) {
  4984. ASSERT_TRUE(req.has_param("key"));
  4985. EXPECT_EQ(req.get_param_value("key"), "value");
  4986. EXPECT_EQ(req.body, "content");
  4987. })
  4988. .Get("/last-request",
  4989. [&](const Request &req, Response & /*res*/) {
  4990. EXPECT_EQ("close", req.get_header_value("Connection"));
  4991. })
  4992. .Get(R"(/redirect/(\d+))",
  4993. [&](const Request &req, Response &res) {
  4994. auto num = std::stoi(req.matches[1]) + 1;
  4995. std::string url = "/redirect/" + std::to_string(num);
  4996. res.set_redirect(url);
  4997. })
  4998. .Post("/binary",
  4999. [&](const Request &req, Response &res) {
  5000. EXPECT_EQ(4U, req.body.size());
  5001. EXPECT_EQ("application/octet-stream",
  5002. req.get_header_value("Content-Type"));
  5003. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5004. res.set_content(req.body, "application/octet-stream");
  5005. })
  5006. .Put("/binary",
  5007. [&](const Request &req, Response &res) {
  5008. EXPECT_EQ(4U, req.body.size());
  5009. EXPECT_EQ("application/octet-stream",
  5010. req.get_header_value("Content-Type"));
  5011. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5012. res.set_content(req.body, "application/octet-stream");
  5013. })
  5014. .Patch("/binary",
  5015. [&](const Request &req, Response &res) {
  5016. EXPECT_EQ(4U, req.body.size());
  5017. EXPECT_EQ("application/octet-stream",
  5018. req.get_header_value("Content-Type"));
  5019. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5020. res.set_content(req.body, "application/octet-stream");
  5021. })
  5022. .Delete("/binary",
  5023. [&](const Request &req, Response &res) {
  5024. EXPECT_EQ(4U, req.body.size());
  5025. EXPECT_EQ("application/octet-stream",
  5026. req.get_header_value("Content-Type"));
  5027. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5028. res.set_content(req.body, "application/octet-stream");
  5029. })
  5030. .Get("/issue1772",
  5031. [&](const Request & /*req*/, Response &res) {
  5032. res.status = 401;
  5033. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5034. })
  5035. .Delete("/issue609",
  5036. [](const httplib::Request &, httplib::Response &res,
  5037. const httplib::ContentReader &) {
  5038. res.set_content("ok", "text/plain");
  5039. })
  5040. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5041. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5042. .Get("/compress",
  5043. [&](const Request & /*req*/, Response &res) {
  5044. res.set_content(
  5045. "12345678901234567890123456789012345678901234567890123456789"
  5046. "01234567890123456789012345678901234567890",
  5047. "text/plain");
  5048. })
  5049. .Get("/compress-with-charset",
  5050. [&](const Request & /*req*/, Response &res) {
  5051. res.set_content(
  5052. "12345678901234567890123456789012345678901234567890123456789"
  5053. "01234567890123456789012345678901234567890",
  5054. "application/json; charset=utf-8");
  5055. })
  5056. .Get("/nocompress",
  5057. [&](const Request & /*req*/, Response &res) {
  5058. res.set_content(
  5059. "12345678901234567890123456789012345678901234567890123456789"
  5060. "01234567890123456789012345678901234567890",
  5061. "application/octet-stream");
  5062. })
  5063. .Post("/compress-multipart",
  5064. [&](const Request &req, Response & /*res*/) {
  5065. EXPECT_EQ(2u, req.form.fields.size());
  5066. ASSERT_TRUE(!req.form.has_field("???"));
  5067. {
  5068. const auto &text = req.form.get_field("key1");
  5069. EXPECT_EQ("test", text);
  5070. }
  5071. {
  5072. const auto &text = req.form.get_field("key2");
  5073. EXPECT_EQ("--abcdefg123", text);
  5074. }
  5075. })
  5076. #endif
  5077. ;
  5078. persons_["john"] = "programmer";
  5079. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5080. svr_.wait_until_ready();
  5081. }
  5082. virtual void TearDown() {
  5083. svr_.stop();
  5084. if (!request_threads_.empty()) {
  5085. std::this_thread::sleep_for(std::chrono::seconds(1));
  5086. for (auto &t : request_threads_) {
  5087. t.join();
  5088. }
  5089. }
  5090. t_.join();
  5091. }
  5092. map<string, string> persons_;
  5093. #ifdef CPPHTTPLIB_SSL_ENABLED
  5094. SSLClient cli_;
  5095. SSLServer svr_;
  5096. #else
  5097. Client cli_;
  5098. Server svr_;
  5099. #endif
  5100. thread t_;
  5101. std::vector<thread> request_threads_;
  5102. };
  5103. TEST_F(ServerTest, GetMethod200) {
  5104. auto res = cli_.Get("/hi");
  5105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5106. EXPECT_EQ("HTTP/1.1", res->version);
  5107. EXPECT_EQ(StatusCode::OK_200, res->status);
  5108. EXPECT_EQ("OK", res->reason);
  5109. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5110. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5111. EXPECT_EQ("Hello World!", res->body);
  5112. }
  5113. TEST_F(ServerTest, GetEmptyFile) {
  5114. auto res = cli_.Get("/empty_file");
  5115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5116. EXPECT_EQ(StatusCode::OK_200, res->status);
  5117. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5118. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5119. EXPECT_EQ("", res->body);
  5120. }
  5121. TEST_F(ServerTest, GetFileContent) {
  5122. auto res = cli_.Get("/file_content");
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. EXPECT_EQ(StatusCode::OK_200, res->status);
  5125. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5126. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5127. EXPECT_EQ("test.html", res->body);
  5128. }
  5129. TEST_F(ServerTest, GetFileContentWithRange) {
  5130. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5132. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5133. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5134. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5135. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5136. EXPECT_EQ("est", res->body);
  5137. }
  5138. TEST_F(ServerTest, GetFileContentWithContentType) {
  5139. auto res = cli_.Get("/file_content_with_content_type");
  5140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5141. EXPECT_EQ(StatusCode::OK_200, res->status);
  5142. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5143. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5144. EXPECT_EQ("file\n", res->body);
  5145. }
  5146. TEST_F(ServerTest, GetInvalidFileContent) {
  5147. auto res = cli_.Get("/invalid_file_content");
  5148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5149. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5150. }
  5151. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5152. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5154. EXPECT_EQ("HTTP/1.1", res->version);
  5155. EXPECT_EQ(StatusCode::OK_200, res->status);
  5156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5157. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5158. EXPECT_EQ("Hello World!", res->body);
  5159. }
  5160. TEST_F(ServerTest, GetMethod302) {
  5161. auto res = cli_.Get("/");
  5162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5163. EXPECT_EQ(StatusCode::Found_302, res->status);
  5164. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5165. }
  5166. TEST_F(ServerTest, GetMethod302Redirect) {
  5167. cli_.set_follow_location(true);
  5168. auto res = cli_.Get("/");
  5169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5170. EXPECT_EQ(StatusCode::OK_200, res->status);
  5171. EXPECT_EQ("Hello World!", res->body);
  5172. EXPECT_EQ("/hi", res->location);
  5173. }
  5174. TEST_F(ServerTest, GetMethod404) {
  5175. auto res = cli_.Get("/invalid");
  5176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5177. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5178. }
  5179. TEST_F(ServerTest, HeadMethod200) {
  5180. auto res = cli_.Head("/hi");
  5181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5182. EXPECT_EQ(StatusCode::OK_200, res->status);
  5183. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5184. EXPECT_TRUE(res->body.empty());
  5185. }
  5186. TEST_F(ServerTest, HeadMethod200Static) {
  5187. auto res = cli_.Head("/mount/dir/index.html");
  5188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5189. EXPECT_EQ(StatusCode::OK_200, res->status);
  5190. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5191. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5192. EXPECT_TRUE(res->body.empty());
  5193. }
  5194. TEST_F(ServerTest, HeadMethod404) {
  5195. auto res = cli_.Head("/invalid");
  5196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5197. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5198. EXPECT_TRUE(res->body.empty());
  5199. }
  5200. TEST_F(ServerTest, GetMethodPersonJohn) {
  5201. auto res = cli_.Get("/person/john");
  5202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5203. EXPECT_EQ(StatusCode::OK_200, res->status);
  5204. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5205. EXPECT_EQ("programmer", res->body);
  5206. }
  5207. TEST_F(ServerTest, PostMethod1) {
  5208. auto res = cli_.Get("/person/john1");
  5209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5210. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5211. res = cli_.Post("/person", "name=john1&note=coder",
  5212. "application/x-www-form-urlencoded");
  5213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5214. ASSERT_EQ(StatusCode::OK_200, res->status);
  5215. res = cli_.Get("/person/john1");
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. ASSERT_EQ(StatusCode::OK_200, res->status);
  5218. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5219. ASSERT_EQ("coder", res->body);
  5220. }
  5221. TEST_F(ServerTest, PostMethod2) {
  5222. auto res = cli_.Get("/person/john2");
  5223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5224. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5225. Params params;
  5226. params.emplace("name", "john2");
  5227. params.emplace("note", "coder");
  5228. res = cli_.Post("/person", params);
  5229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5230. ASSERT_EQ(StatusCode::OK_200, res->status);
  5231. res = cli_.Get("/person/john2");
  5232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5233. ASSERT_EQ(StatusCode::OK_200, res->status);
  5234. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5235. ASSERT_EQ("coder", res->body);
  5236. }
  5237. TEST_F(ServerTest, PutMethod3) {
  5238. auto res = cli_.Get("/person/john3");
  5239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5240. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5241. Params params;
  5242. params.emplace("name", "john3");
  5243. params.emplace("note", "coder");
  5244. res = cli_.Put("/person", params);
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. ASSERT_EQ(StatusCode::OK_200, res->status);
  5247. res = cli_.Get("/person/john3");
  5248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5249. ASSERT_EQ(StatusCode::OK_200, res->status);
  5250. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5251. ASSERT_EQ("coder", res->body);
  5252. }
  5253. TEST_F(ServerTest, DeleteMethod1) {
  5254. auto res = cli_.Get("/person/john4");
  5255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5256. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5257. Params params;
  5258. params.emplace("name", "john4");
  5259. params.emplace("note", "coder");
  5260. res = cli_.Post("/person", params);
  5261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5262. ASSERT_EQ(StatusCode::OK_200, res->status);
  5263. res = cli_.Get("/person/john4");
  5264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5265. ASSERT_EQ(StatusCode::OK_200, res->status);
  5266. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5267. ASSERT_EQ("coder", res->body);
  5268. Params delete_params;
  5269. delete_params.emplace("name", "john4");
  5270. res = cli_.Delete("/person", delete_params);
  5271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5272. ASSERT_EQ(StatusCode::OK_200, res->status);
  5273. ASSERT_EQ("DELETED", res->body);
  5274. res = cli_.Get("/person/john4");
  5275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5276. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5277. }
  5278. TEST_F(ServerTest, DeleteMethod2) {
  5279. auto res = cli_.Get("/person/john5");
  5280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5281. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5282. Params params;
  5283. params.emplace("name", "john5");
  5284. params.emplace("note", "developer");
  5285. res = cli_.Post("/person", params);
  5286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5287. ASSERT_EQ(StatusCode::OK_200, res->status);
  5288. res = cli_.Get("/person/john5");
  5289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5290. ASSERT_EQ(StatusCode::OK_200, res->status);
  5291. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5292. ASSERT_EQ("developer", res->body);
  5293. Params delete_params;
  5294. delete_params.emplace("name", "john5");
  5295. Headers headers;
  5296. headers.emplace("Custom-Header", "test-value");
  5297. res = cli_.Delete("/person", headers, delete_params);
  5298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5299. ASSERT_EQ(StatusCode::OK_200, res->status);
  5300. ASSERT_EQ("DELETED", res->body);
  5301. res = cli_.Get("/person/john5");
  5302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5303. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5304. }
  5305. TEST_F(ServerTest, DeleteMethod3) {
  5306. auto res = cli_.Get("/person/john6");
  5307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5308. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5309. Params params;
  5310. params.emplace("name", "john6");
  5311. params.emplace("note", "tester");
  5312. res = cli_.Post("/person", params);
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. ASSERT_EQ(StatusCode::OK_200, res->status);
  5315. res = cli_.Get("/person/john6");
  5316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5317. ASSERT_EQ(StatusCode::OK_200, res->status);
  5318. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5319. ASSERT_EQ("tester", res->body);
  5320. Params delete_params;
  5321. delete_params.emplace("name", "john6");
  5322. Headers headers;
  5323. headers.emplace("Custom-Header", "test-value");
  5324. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5326. ASSERT_EQ(StatusCode::OK_200, res->status);
  5327. ASSERT_EQ("DELETED", res->body);
  5328. res = cli_.Get("/person/john6");
  5329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5330. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5331. }
  5332. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5333. Params params;
  5334. params.emplace("json", JSON_DATA);
  5335. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5337. ASSERT_EQ(StatusCode::OK_200, res->status);
  5338. ASSERT_EQ(JSON_DATA, res->body);
  5339. }
  5340. TEST_F(ServerTest, PostEmptyContent) {
  5341. auto res = cli_.Post("/empty", "", "text/plain");
  5342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5343. ASSERT_EQ(StatusCode::OK_200, res->status);
  5344. ASSERT_EQ("empty", res->body);
  5345. }
  5346. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5347. auto res = cli_.Post("/empty-no-content-type");
  5348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5349. ASSERT_EQ(StatusCode::OK_200, res->status);
  5350. ASSERT_EQ("empty-no-content-type", res->body);
  5351. }
  5352. TEST_F(ServerTest, PostPathOnly) {
  5353. auto res = cli_.Post("/path-only");
  5354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5355. ASSERT_EQ(StatusCode::OK_200, res->status);
  5356. ASSERT_EQ("path-only", res->body);
  5357. }
  5358. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5359. auto res = cli_.Post("/path-headers-only",
  5360. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5362. ASSERT_EQ(StatusCode::OK_200, res->status);
  5363. ASSERT_EQ("path-headers-only", res->body);
  5364. }
  5365. TEST_F(ServerTest, PostLarge) {
  5366. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5368. ASSERT_EQ(StatusCode::OK_200, res->status);
  5369. EXPECT_EQ(LARGE_DATA, res->body);
  5370. }
  5371. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5372. auto res = cli_.Put("/empty-no-content-type");
  5373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5374. ASSERT_EQ(StatusCode::OK_200, res->status);
  5375. ASSERT_EQ("empty-no-content-type", res->body);
  5376. }
  5377. TEST_F(ServerTest, GetMethodDir) {
  5378. auto res = cli_.Get("/dir/");
  5379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5380. EXPECT_EQ(StatusCode::OK_200, res->status);
  5381. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5382. auto body = R"(<html>
  5383. <head>
  5384. </head>
  5385. <body>
  5386. <a href="/dir/test.html">Test</a>
  5387. <a href="/hi">hi</a>
  5388. </body>
  5389. </html>
  5390. )";
  5391. EXPECT_EQ(body, res->body);
  5392. }
  5393. TEST_F(ServerTest, GetMethodDirTest) {
  5394. auto res = cli_.Get("/dir/test.html");
  5395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5396. EXPECT_EQ(StatusCode::OK_200, res->status);
  5397. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5398. EXPECT_EQ("test.html", res->body);
  5399. }
  5400. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5401. auto res = cli_.Get("/dir/../dir/test.html");
  5402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5403. EXPECT_EQ(StatusCode::OK_200, res->status);
  5404. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5405. EXPECT_EQ("test.html", res->body);
  5406. }
  5407. TEST_F(ServerTest, GetMethodInvalidPath) {
  5408. auto res = cli_.Get("/dir/../test.html");
  5409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5410. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5411. }
  5412. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5413. auto res = cli_.Get("/../www/dir/test.html");
  5414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5415. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5416. }
  5417. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5418. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5420. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5421. }
  5422. TEST_F(ServerTest, GetMethodDirMountTest) {
  5423. auto res = cli_.Get("/mount/dir/test.html");
  5424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5425. EXPECT_EQ(StatusCode::OK_200, res->status);
  5426. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5427. EXPECT_EQ("test.html", res->body);
  5428. }
  5429. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5430. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5432. EXPECT_EQ(StatusCode::OK_200, res->status);
  5433. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5434. EXPECT_EQ("test.html", res->body);
  5435. }
  5436. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5437. auto res = cli_.Get("/mount/dir/../test.html");
  5438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5439. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5440. }
  5441. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5442. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5444. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5445. }
  5446. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5447. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5449. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5450. }
  5451. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5452. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5454. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5455. }
  5456. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5457. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5460. }
  5461. TEST_F(ServerTest, PostMethod303) {
  5462. auto res = cli_.Post("/1", "body", "text/plain");
  5463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5464. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5465. EXPECT_EQ("/2", res->get_header_value("Location"));
  5466. }
  5467. TEST_F(ServerTest, PostMethod303Redirect) {
  5468. cli_.set_follow_location(true);
  5469. auto res = cli_.Post("/1", "body", "text/plain");
  5470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5471. EXPECT_EQ(StatusCode::OK_200, res->status);
  5472. EXPECT_EQ("redirected.", res->body);
  5473. EXPECT_EQ("/2", res->location);
  5474. }
  5475. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5476. auto res = cli_.Get("/dir/test.abcde");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ(StatusCode::OK_200, res->status);
  5479. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5480. EXPECT_EQ("abcde", res->body);
  5481. }
  5482. TEST_F(ServerTest, StaticFileRange) {
  5483. auto res =
  5484. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5486. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5487. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5488. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5489. EXPECT_EQ(true, res->has_header("Content-Range"));
  5490. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5491. EXPECT_EQ(std::string("cd"), res->body);
  5492. }
  5493. TEST_F(ServerTest, StaticFileRanges) {
  5494. auto res = cli_.Get("/dir/test.abcde",
  5495. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5497. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5498. EXPECT_TRUE(
  5499. res->get_header_value("Content-Type")
  5500. .find(
  5501. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5502. 0);
  5503. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5504. }
  5505. TEST_F(ServerTest, StaticFileRangeHead) {
  5506. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5508. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5509. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5510. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5511. EXPECT_EQ(true, res->has_header("Content-Range"));
  5512. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5513. }
  5514. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5515. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5517. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5518. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5519. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5520. EXPECT_EQ(true, res->has_header("Content-Range"));
  5521. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5522. res->get_header_value("Content-Range"));
  5523. EXPECT_EQ("LAST\n", res->body);
  5524. }
  5525. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5526. auto res =
  5527. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5529. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5530. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5531. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5532. EXPECT_EQ(true, res->has_header("Content-Range"));
  5533. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5534. }
  5535. TEST_F(ServerTest, StaticFileBigFile) {
  5536. auto res = cli_.Get("/dir/1MB.txt");
  5537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5538. EXPECT_EQ(StatusCode::OK_200, res->status);
  5539. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5540. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5541. }
  5542. TEST_F(ServerTest, InvalidBaseDirMount) {
  5543. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5544. }
  5545. TEST_F(ServerTest, Binary) {
  5546. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5547. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5548. "application/octet-stream");
  5549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5550. ASSERT_EQ(StatusCode::OK_200, res->status);
  5551. ASSERT_EQ(4U, res->body.size());
  5552. res = cli_.Put("/binary", binary.data(), binary.size(),
  5553. "application/octet-stream");
  5554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5555. ASSERT_EQ(StatusCode::OK_200, res->status);
  5556. ASSERT_EQ(4U, res->body.size());
  5557. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5558. "application/octet-stream");
  5559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5560. ASSERT_EQ(StatusCode::OK_200, res->status);
  5561. ASSERT_EQ(4U, res->body.size());
  5562. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5563. "application/octet-stream");
  5564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5565. ASSERT_EQ(StatusCode::OK_200, res->status);
  5566. ASSERT_EQ(4U, res->body.size());
  5567. }
  5568. TEST_F(ServerTest, BinaryString) {
  5569. auto binary = std::string("\x00\x01\x02\x03", 4);
  5570. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5572. ASSERT_EQ(StatusCode::OK_200, res->status);
  5573. ASSERT_EQ(4U, res->body.size());
  5574. res = cli_.Put("/binary", binary, "application/octet-stream");
  5575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5576. ASSERT_EQ(StatusCode::OK_200, res->status);
  5577. ASSERT_EQ(4U, res->body.size());
  5578. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5580. ASSERT_EQ(StatusCode::OK_200, res->status);
  5581. ASSERT_EQ(4U, res->body.size());
  5582. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5584. ASSERT_EQ(StatusCode::OK_200, res->status);
  5585. ASSERT_EQ(4U, res->body.size());
  5586. }
  5587. TEST_F(ServerTest, EmptyRequest) {
  5588. auto res = cli_.Get("");
  5589. ASSERT_TRUE(!res);
  5590. EXPECT_EQ(Error::Connection, res.error());
  5591. }
  5592. TEST_F(ServerTest, LongRequest) {
  5593. std::string request;
  5594. for (size_t i = 0; i < 545; i++) {
  5595. request += "/TooLongRequest";
  5596. }
  5597. request += "OK";
  5598. auto res = cli_.Get(request.c_str());
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5601. }
  5602. TEST_F(ServerTest, TooLongRequest) {
  5603. std::string request;
  5604. for (size_t i = 0; i < 546; i++) {
  5605. request += "/TooLongRequest";
  5606. }
  5607. request += "_NG";
  5608. auto start = std::chrono::high_resolution_clock::now();
  5609. cli_.set_keep_alive(true);
  5610. auto res = cli_.Get(request.c_str());
  5611. auto end = std::chrono::high_resolution_clock::now();
  5612. auto elapsed =
  5613. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5614. .count();
  5615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5616. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5617. EXPECT_LE(elapsed, 1000);
  5618. EXPECT_EQ("close", res->get_header_value("Connection"));
  5619. EXPECT_FALSE(cli_.is_socket_open());
  5620. }
  5621. TEST_F(ServerTest, AlmostTooLongRequest) {
  5622. // test for #2046 - URI length check shouldn't include other content on req
  5623. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5624. // leading /, space, HTTP/1.1)
  5625. std::string request =
  5626. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5627. auto res = cli_.Get(request.c_str());
  5628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5629. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5630. }
  5631. TEST_F(ServerTest, LongHeader) {
  5632. Request req;
  5633. req.method = "GET";
  5634. req.path = "/hi";
  5635. std::string host_and_port;
  5636. host_and_port += HOST;
  5637. host_and_port += ":";
  5638. host_and_port += std::to_string(PORT);
  5639. req.headers.emplace("Host", host_and_port.c_str());
  5640. req.headers.emplace("Accept", "*/*");
  5641. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5642. req.headers.emplace(
  5643. "Header-Name",
  5644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5657. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5672. "@@@@@@@@@@@@@@@@");
  5673. auto res = std::make_shared<Response>();
  5674. auto error = Error::Success;
  5675. auto ret = cli_.send(req, *res, error);
  5676. ASSERT_TRUE(ret);
  5677. EXPECT_EQ(StatusCode::OK_200, res->status);
  5678. }
  5679. TEST_F(ServerTest, LongQueryValue) {
  5680. auto start = std::chrono::high_resolution_clock::now();
  5681. cli_.set_keep_alive(true);
  5682. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5683. auto end = std::chrono::high_resolution_clock::now();
  5684. auto elapsed =
  5685. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5686. .count();
  5687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5688. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5689. EXPECT_LE(elapsed, 1000);
  5690. EXPECT_EQ("close", res->get_header_value("Connection"));
  5691. EXPECT_FALSE(cli_.is_socket_open());
  5692. }
  5693. TEST_F(ServerTest, TooLongQueryValue) {
  5694. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5695. ASSERT_FALSE(res);
  5696. EXPECT_EQ(Error::Read, res.error());
  5697. }
  5698. TEST_F(ServerTest, TooLongHeader) {
  5699. Request req;
  5700. req.method = "GET";
  5701. req.path = "/hi";
  5702. std::string host_and_port;
  5703. host_and_port += HOST;
  5704. host_and_port += ":";
  5705. host_and_port += std::to_string(PORT);
  5706. req.headers.emplace("Host", host_and_port.c_str());
  5707. req.headers.emplace("Accept", "*/*");
  5708. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5709. req.headers.emplace(
  5710. "Header-Name",
  5711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5739. "@@@@@@@@@@@@@@@@@");
  5740. auto res = std::make_shared<Response>();
  5741. auto error = Error::Success;
  5742. auto ret = cli_.send(req, *res, error);
  5743. ASSERT_TRUE(ret);
  5744. EXPECT_EQ(StatusCode::OK_200, res->status);
  5745. }
  5746. TEST_F(ServerTest, HeaderCountAtLimit) {
  5747. // Test with headers just under the 100 limit
  5748. httplib::Headers headers;
  5749. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5750. // This should keep us just under the 100 header limit
  5751. for (int i = 0; i < 95; i++) {
  5752. std::string name = "X-Test-Header-" + std::to_string(i);
  5753. std::string value = "value" + std::to_string(i);
  5754. headers.emplace(name, value);
  5755. }
  5756. // This should work fine as we're under the limit
  5757. auto res = cli_.Get("/hi", headers);
  5758. EXPECT_TRUE(res);
  5759. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5760. }
  5761. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5762. // Test with many headers to exceed the 100 limit
  5763. httplib::Headers headers;
  5764. // Add 150 headers to definitely exceed the 100 limit
  5765. for (int i = 0; i < 150; i++) {
  5766. std::string name = "X-Test-Header-" + std::to_string(i);
  5767. std::string value = "value" + std::to_string(i);
  5768. headers.emplace(name, value);
  5769. }
  5770. // This should fail due to exceeding header count limit
  5771. cli_.set_keep_alive(true);
  5772. auto res = cli_.Get("/hi", headers);
  5773. // The server should respond with 400 Bad Request
  5774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5775. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5776. EXPECT_EQ("close", res->get_header_value("Connection"));
  5777. EXPECT_FALSE(cli_.is_socket_open());
  5778. }
  5779. TEST_F(ServerTest, PercentEncoding) {
  5780. auto res = cli_.Get("/e%6edwith%");
  5781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5782. EXPECT_EQ(StatusCode::OK_200, res->status);
  5783. }
  5784. TEST_F(ServerTest, PercentEncodingUnicode) {
  5785. auto res = cli_.Get("/e%u006edwith%");
  5786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5787. EXPECT_EQ(StatusCode::OK_200, res->status);
  5788. }
  5789. TEST_F(ServerTest, InvalidPercentEncoding) {
  5790. auto res = cli_.Get("/%endwith%");
  5791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5793. }
  5794. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5795. auto res = cli_.Get("/%uendwith%");
  5796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5797. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5798. }
  5799. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5800. auto res = cli_.Get("/hello?aaa=bbb%");
  5801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5802. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5803. }
  5804. TEST_F(ServerTest, PlusSignEncoding) {
  5805. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5807. EXPECT_EQ(StatusCode::OK_200, res->status);
  5808. EXPECT_EQ("a +b", res->body);
  5809. }
  5810. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5811. // This test simulates a potential DoS attack using many headers
  5812. // to verify our security fix prevents memory exhaustion
  5813. httplib::Headers attack_headers;
  5814. // Attempt to add many headers like an attacker would (200 headers to far
  5815. // exceed limit)
  5816. for (int i = 0; i < 200; i++) {
  5817. std::string name = "X-Attack-Header-" + std::to_string(i);
  5818. std::string value = "attack_payload_" + std::to_string(i);
  5819. attack_headers.emplace(name, value);
  5820. }
  5821. // Try to POST with excessive headers
  5822. cli_.set_keep_alive(true);
  5823. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5824. // Should either fail or return 400 Bad Request due to security limit
  5825. if (res) {
  5826. // If we get a response, it should be 400 Bad Request
  5827. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5828. EXPECT_EQ("close", res->get_header_value("Connection"));
  5829. }
  5830. EXPECT_FALSE(cli_.is_socket_open());
  5831. }
  5832. TEST_F(ServerTest, MultipartFormData) {
  5833. UploadFormDataItems items = {
  5834. {"text1", "text default", "", ""},
  5835. {"text2", "aωb", "", ""},
  5836. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5837. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5838. {"file3", "", "", "application/octet-stream"},
  5839. {"file4", "", "", " application/json tmp-string "}};
  5840. auto res = cli_.Post("/multipart", items);
  5841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5842. EXPECT_EQ(StatusCode::OK_200, res->status);
  5843. }
  5844. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5845. UploadFormDataItems items = {
  5846. {"text", "default text", "", ""},
  5847. {"multi_text1", "aaaaa", "", ""},
  5848. {"multi_text1", "bbbbb", "", ""},
  5849. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5850. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5851. "application/json"},
  5852. };
  5853. auto res = cli_.Post("/multipart/multi_file_values", items);
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. }
  5857. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5858. auto res = cli_.Get("/hi");
  5859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5860. EXPECT_EQ(StatusCode::OK_200, res->status);
  5861. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5862. EXPECT_EQ("Hello World!", res->body);
  5863. }
  5864. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5865. Request req;
  5866. req.method = "POST";
  5867. req.path = "/chunked";
  5868. std::string host_and_port;
  5869. host_and_port += HOST;
  5870. host_and_port += ":";
  5871. host_and_port += std::to_string(PORT);
  5872. req.headers.emplace("Host", host_and_port.c_str());
  5873. req.headers.emplace("Accept", "*/*");
  5874. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5875. req.headers.emplace("Content-Type", "text/plain");
  5876. req.headers.emplace("Content-Length", "0");
  5877. req.headers.emplace(
  5878. "Transfer-Encoding",
  5879. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5880. // Client does not chunk, so make a chunked body manually.
  5881. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5882. auto res = std::make_shared<Response>();
  5883. auto error = Error::Success;
  5884. auto ret = cli_.send(req, *res, error);
  5885. ASSERT_TRUE(ret);
  5886. EXPECT_EQ(StatusCode::OK_200, res->status);
  5887. }
  5888. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5889. // rather than treat them as valid lengths.
  5890. template <typename ClientT>
  5891. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5892. Request req;
  5893. req.method = "POST";
  5894. req.path = "/chunked";
  5895. std::string host_and_port;
  5896. host_and_port += HOST;
  5897. host_and_port += ":";
  5898. host_and_port += std::to_string(PORT);
  5899. req.headers.emplace("Host", host_and_port.c_str());
  5900. req.headers.emplace("Content-Length", "0");
  5901. req.headers.emplace("Transfer-Encoding", "chunked");
  5902. req.body = body;
  5903. auto res = std::make_shared<Response>();
  5904. auto error = Error::Success;
  5905. ASSERT_TRUE(cli.send(req, *res, error));
  5906. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5907. }
  5908. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5909. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5910. }
  5911. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5912. expect_chunked_body_rejected(
  5913. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5914. }
  5915. TEST_F(ServerTest, GetStreamed2) {
  5916. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5919. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5920. EXPECT_EQ(true, res->has_header("Content-Range"));
  5921. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5922. EXPECT_EQ(std::string("ab"), res->body);
  5923. }
  5924. TEST_F(ServerTest, GetStreamed) {
  5925. auto res = cli_.Get("/streamed");
  5926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5927. EXPECT_EQ(StatusCode::OK_200, res->status);
  5928. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5929. EXPECT_EQ(std::string("aaabbb"), res->body);
  5930. }
  5931. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5932. auto res = cli_.Get("/streamed-without-length",
  5933. Headers{make_range_header({{0, -1}})});
  5934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5935. EXPECT_EQ(StatusCode::OK_200, res->status);
  5936. EXPECT_EQ(false, res->has_header("Content-Length"));
  5937. EXPECT_EQ(false, res->has_header("Content-Range"));
  5938. EXPECT_EQ(std::string("abcdefg"), res->body);
  5939. }
  5940. TEST_F(ServerTest, GetStreamedWithRange1) {
  5941. auto res =
  5942. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5944. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5945. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5946. EXPECT_EQ(true, res->has_header("Content-Range"));
  5947. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5948. EXPECT_EQ(std::string("def"), res->body);
  5949. }
  5950. TEST_F(ServerTest, GetStreamedWithRange2) {
  5951. auto res =
  5952. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5954. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5955. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5956. EXPECT_EQ(true, res->has_header("Content-Range"));
  5957. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5958. EXPECT_EQ(std::string("bcdefg"), res->body);
  5959. }
  5960. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5961. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5963. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5964. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5965. EXPECT_EQ(true, res->has_header("Content-Range"));
  5966. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5967. EXPECT_EQ(std::string("efg"), res->body);
  5968. }
  5969. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5970. auto res =
  5971. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5973. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5974. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5975. EXPECT_EQ(false, res->has_header("Content-Range"));
  5976. EXPECT_EQ(0U, res->body.size());
  5977. }
  5978. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5979. // Only a 206 is served as a partial representation. Under any other status
  5980. // `apply_ranges()` reported the full content length, so the body must match
  5981. // that header, and the content provider must never be asked for an offset
  5982. // outside the representation.
  5983. auto check = [&](int status, const char *range) {
  5984. auto path =
  5985. std::string("/streamed-with-range?status=") + std::to_string(status);
  5986. auto ctx = path + " Range: " + range;
  5987. auto res = cli_.Get(path, Headers{{"Range", range}});
  5988. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5989. EXPECT_EQ(status, res->status) << ctx;
  5990. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5991. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5992. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5993. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5994. };
  5995. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5996. check(403, "bytes=3-5");
  5997. // The offset is far past the representation.
  5998. check(403, "bytes=100000-100200");
  5999. // `first_pos` is still -1 here, and the bounds asserts in
  6000. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6001. check(403, "bytes=-3");
  6002. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6003. // multipart branch would have written one that is empty.
  6004. check(403, "bytes=1-2, 4-5");
  6005. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6006. // covers the whole representation.
  6007. check(200, "bytes=3-5");
  6008. check(200, "bytes=1-2, 4-5");
  6009. }
  6010. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6011. auto res =
  6012. cli_.Get("/streamed-with-range",
  6013. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6014. "92233720368547758079223372036854775807"}});
  6015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6016. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6017. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6018. EXPECT_EQ(false, res->has_header("Content-Range"));
  6019. EXPECT_EQ(0U, res->body.size());
  6020. }
  6021. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6022. auto res = cli_.Get(
  6023. "/with-range",
  6024. Headers{{"Range",
  6025. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6026. {"Accept-Encoding", ""}});
  6027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6028. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6029. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6030. EXPECT_EQ(true, res->has_header("Content-Range"));
  6031. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6032. EXPECT_EQ(std::string("abcdefg"), res->body);
  6033. }
  6034. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6035. auto res = cli_.Get("/with-range", Headers{
  6036. {"Range", "bytes=0-"},
  6037. {"Accept-Encoding", ""},
  6038. });
  6039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6040. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6041. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6042. EXPECT_EQ(true, res->has_header("Content-Range"));
  6043. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6044. EXPECT_EQ(std::string("abcdefg"), res->body);
  6045. }
  6046. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6047. auto res = cli_.Get("/streamed-with-range",
  6048. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6050. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6051. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6052. EXPECT_EQ(false, res->has_header("Content-Range"));
  6053. EXPECT_EQ(267U, res->body.size());
  6054. // Check that both range contents are present
  6055. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6056. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6057. // Check that Content-Range headers are present for both ranges
  6058. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6059. std::string::npos);
  6060. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6061. std::string::npos);
  6062. }
  6063. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6064. Ranges ranges;
  6065. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6066. ranges.emplace_back(0, -1);
  6067. }
  6068. auto res = cli_.Get("/streamed-with-range?error",
  6069. Headers{{make_range_header(ranges)}});
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6072. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6073. EXPECT_EQ(false, res->has_header("Content-Range"));
  6074. EXPECT_EQ(0U, res->body.size());
  6075. }
  6076. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6077. auto res = cli_.Get("/streamed-with-range",
  6078. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6080. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6081. EXPECT_EQ(5U, res->body.size());
  6082. // Check that overlapping ranges are coalesced into a single range
  6083. EXPECT_EQ("bcdef", res->body);
  6084. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6085. // Should be single range, not multipart
  6086. EXPECT_TRUE(res->has_header("Content-Range"));
  6087. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6088. }
  6089. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6090. auto res = cli_.Get("/streamed-with-range",
  6091. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6093. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6094. EXPECT_EQ(268U, res->body.size());
  6095. // Check that both range contents are present
  6096. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6097. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6098. // Check that Content-Range headers are present for both ranges
  6099. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6100. std::string::npos);
  6101. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6102. std::string::npos);
  6103. }
  6104. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6105. auto res = cli_.Get("/streamed-with-range",
  6106. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6108. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6109. EXPECT_EQ(269U, res->body.size());
  6110. // Check that both duplicate range contents are present
  6111. size_t first_abc = res->body.find("abc\r\n");
  6112. EXPECT_TRUE(first_abc != std::string::npos);
  6113. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6114. EXPECT_TRUE(second_abc != std::string::npos);
  6115. // Check that Content-Range headers are present for both ranges
  6116. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6117. EXPECT_TRUE(first_range != std::string::npos);
  6118. size_t second_range =
  6119. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6120. EXPECT_TRUE(second_range != std::string::npos);
  6121. }
  6122. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6123. auto res =
  6124. cli_.Get("/streamed-with-range?error",
  6125. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6128. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6129. EXPECT_EQ(false, res->has_header("Content-Range"));
  6130. EXPECT_EQ(0U, res->body.size());
  6131. }
  6132. TEST_F(ServerTest, GetStreamedEndless) {
  6133. uint64_t offset = 0;
  6134. auto res = cli_.Get("/streamed-cancel",
  6135. [&](const char * /*data*/, uint64_t data_length) {
  6136. if (offset < 100) {
  6137. offset += data_length;
  6138. return true;
  6139. }
  6140. return false;
  6141. });
  6142. ASSERT_TRUE(!res);
  6143. EXPECT_EQ(Error::Canceled, res.error());
  6144. }
  6145. TEST_F(ServerTest, ClientStop) {
  6146. std::atomic_size_t count{4};
  6147. std::vector<std::thread> threads;
  6148. for (auto i = count.load(); i != 0; --i) {
  6149. threads.emplace_back([&]() {
  6150. auto res = cli_.Get("/streamed-cancel",
  6151. [&](const char *, uint64_t) { return true; });
  6152. --count;
  6153. ASSERT_TRUE(!res);
  6154. EXPECT_TRUE(res.error() == Error::Canceled ||
  6155. res.error() == Error::Read || res.error() == Error::Write);
  6156. });
  6157. }
  6158. std::this_thread::sleep_for(std::chrono::seconds(2));
  6159. while (count != 0) {
  6160. cli_.stop();
  6161. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6162. }
  6163. for (auto &t : threads) {
  6164. t.join();
  6165. }
  6166. }
  6167. TEST_F(ServerTest, GetWithRange1) {
  6168. auto res = cli_.Get("/with-range", Headers{
  6169. make_range_header({{3, 5}}),
  6170. {"Accept-Encoding", ""},
  6171. });
  6172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6174. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6175. EXPECT_EQ(true, res->has_header("Content-Range"));
  6176. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6177. EXPECT_EQ(std::string("def"), res->body);
  6178. }
  6179. TEST_F(ServerTest, GetWithRange2) {
  6180. auto res = cli_.Get("/with-range", Headers{
  6181. make_range_header({{1, -1}}),
  6182. {"Accept-Encoding", ""},
  6183. });
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6186. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6187. EXPECT_EQ(true, res->has_header("Content-Range"));
  6188. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6189. EXPECT_EQ(std::string("bcdefg"), res->body);
  6190. }
  6191. TEST_F(ServerTest, GetWithRange3) {
  6192. auto res = cli_.Get("/with-range", Headers{
  6193. make_range_header({{0, 0}}),
  6194. {"Accept-Encoding", ""},
  6195. });
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6198. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6199. EXPECT_EQ(true, res->has_header("Content-Range"));
  6200. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6201. EXPECT_EQ(std::string("a"), res->body);
  6202. }
  6203. TEST_F(ServerTest, GetWithRange4) {
  6204. auto res = cli_.Get("/with-range", Headers{
  6205. make_range_header({{-1, 2}}),
  6206. {"Accept-Encoding", ""},
  6207. });
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6210. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6211. EXPECT_EQ(true, res->has_header("Content-Range"));
  6212. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6213. EXPECT_EQ(std::string("fg"), res->body);
  6214. }
  6215. TEST_F(ServerTest, GetWithRange5) {
  6216. auto res = cli_.Get("/with-range", Headers{
  6217. make_range_header({{0, 5}}),
  6218. {"Accept-Encoding", ""},
  6219. });
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6222. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6223. EXPECT_EQ(true, res->has_header("Content-Range"));
  6224. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6225. EXPECT_EQ(std::string("abcdef"), res->body);
  6226. }
  6227. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6228. auto res =
  6229. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6232. }
  6233. TEST_F(ServerTest, GetWithRangeMultipart) {
  6234. auto res =
  6235. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6238. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6239. EXPECT_EQ(false, res->has_header("Content-Range"));
  6240. EXPECT_EQ(267U, res->body.size());
  6241. }
  6242. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6243. auto res = cli_.Get("/with-range",
  6244. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6246. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6247. }
  6248. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6249. auto res = cli_.Get("/with-range-customized-response",
  6250. Headers{{make_range_header({{1, 2}})}});
  6251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6252. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6253. EXPECT_EQ(true, res->has_header("Content-Length"));
  6254. EXPECT_EQ(false, res->has_header("Content-Range"));
  6255. EXPECT_EQ(JSON_DATA, res->body);
  6256. }
  6257. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6258. auto res = cli_.Get("/with-range-customized-response",
  6259. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6261. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6262. EXPECT_EQ(true, res->has_header("Content-Length"));
  6263. EXPECT_EQ(false, res->has_header("Content-Range"));
  6264. EXPECT_EQ(JSON_DATA, res->body);
  6265. }
  6266. TEST_F(ServerTest, Issue1772) {
  6267. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6270. }
  6271. TEST_F(ServerTest, Issue609) {
  6272. auto res = cli_.Delete("/issue609");
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. EXPECT_EQ(std::string("ok"), res->body);
  6276. }
  6277. TEST_F(ServerTest, GetStreamedChunked) {
  6278. auto res = cli_.Get("/streamed-chunked");
  6279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6280. EXPECT_EQ(StatusCode::OK_200, res->status);
  6281. EXPECT_EQ(std::string("123456789"), res->body);
  6282. }
  6283. TEST_F(ServerTest, GetStreamedChunked2) {
  6284. auto res = cli_.Get("/streamed-chunked2");
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ(StatusCode::OK_200, res->status);
  6287. EXPECT_EQ(std::string("123456789"), res->body);
  6288. }
  6289. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6290. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. EXPECT_EQ(StatusCode::OK_200, res->status);
  6293. EXPECT_EQ(std::string("123456789"), res->body);
  6294. EXPECT_TRUE(res->has_header("Trailer"));
  6295. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6296. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6297. // Trailers are now stored separately from headers (security fix)
  6298. EXPECT_EQ(2U, res->trailers.size());
  6299. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6300. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6301. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6302. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6303. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6304. // Verify trailers are NOT in headers (security verification)
  6305. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6306. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6307. }
  6308. TEST_F(ServerTest, LargeChunkedPost) {
  6309. Request req;
  6310. req.method = "POST";
  6311. req.path = "/large-chunked";
  6312. std::string host_and_port;
  6313. host_and_port += HOST;
  6314. host_and_port += ":";
  6315. host_and_port += std::to_string(PORT);
  6316. req.headers.emplace("Host", host_and_port.c_str());
  6317. req.headers.emplace("Accept", "*/*");
  6318. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6319. req.headers.emplace("Content-Type", "text/plain");
  6320. req.headers.emplace("Content-Length", "0");
  6321. req.headers.emplace("Transfer-Encoding", "chunked");
  6322. std::string long_string(30 * 1024u, 'a');
  6323. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6324. // Attempt to make a large enough post to exceed OS buffers, to test that
  6325. // the server handles short reads if the full chunk data isn't available.
  6326. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6327. auto res = std::make_shared<Response>();
  6328. auto error = Error::Success;
  6329. auto ret = cli_.send(req, *res, error);
  6330. ASSERT_TRUE(ret);
  6331. EXPECT_EQ(StatusCode::OK_200, res->status);
  6332. }
  6333. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6334. auto res = cli_.Get("/remote_addr");
  6335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6336. EXPECT_EQ(StatusCode::OK_200, res->status);
  6337. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6338. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6339. }
  6340. TEST_F(ServerTest, GetMethodLocalAddr) {
  6341. auto res = cli_.Get("/local_addr");
  6342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6343. EXPECT_EQ(StatusCode::OK_200, res->status);
  6344. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6345. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6346. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6347. }
  6348. TEST_F(ServerTest, HTTPResponseSplitting) {
  6349. auto res = cli_.Get("/http_response_splitting");
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. EXPECT_EQ(StatusCode::OK_200, res->status);
  6352. }
  6353. TEST_F(ServerTest, SlowRequest) {
  6354. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6355. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6356. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6357. }
  6358. #if 0
  6359. TEST_F(ServerTest, SlowPost) {
  6360. char buffer[64 * 1024];
  6361. memset(buffer, 0x42, sizeof(buffer));
  6362. auto res = cli_.Post(
  6363. "/slowpost", 64 * 1024 * 1024,
  6364. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6365. auto ret = sink.write(buffer, sizeof(buffer));
  6366. EXPECT_TRUE(ret);
  6367. return true;
  6368. },
  6369. "text/plain");
  6370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6371. EXPECT_EQ(StatusCode::OK_200, res->status);
  6372. }
  6373. TEST_F(ServerTest, SlowPostFail) {
  6374. char buffer[64 * 1024];
  6375. memset(buffer, 0x42, sizeof(buffer));
  6376. cli_.set_write_timeout(std::chrono::seconds(0));
  6377. auto res = cli_.Post(
  6378. "/slowpost", 64 * 1024 * 1024,
  6379. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6380. sink.write(buffer, sizeof(buffer));
  6381. return true;
  6382. },
  6383. "text/plain");
  6384. ASSERT_TRUE(!res);
  6385. EXPECT_EQ(Error::Write, res.error());
  6386. }
  6387. #endif
  6388. TEST_F(ServerTest, Put) {
  6389. auto res = cli_.Put("/put", "PUT", "text/plain");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. EXPECT_EQ("PUT", res->body);
  6393. }
  6394. TEST_F(ServerTest, PutWithContentProvider) {
  6395. auto res = cli_.Put(
  6396. "/put", 3,
  6397. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6398. sink.os << "PUT";
  6399. return true;
  6400. },
  6401. "text/plain");
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::OK_200, res->status);
  6404. EXPECT_EQ("PUT", res->body);
  6405. }
  6406. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6407. auto res = cli_.Post(
  6408. "/post", 42,
  6409. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6410. return false;
  6411. },
  6412. "text/plain");
  6413. ASSERT_TRUE(!res);
  6414. EXPECT_EQ(Error::Canceled, res.error());
  6415. }
  6416. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6417. auto res = cli_.Put(
  6418. "/put",
  6419. [](size_t /*offset*/, DataSink &sink) {
  6420. sink.os << "PUT";
  6421. sink.done();
  6422. return true;
  6423. },
  6424. "text/plain");
  6425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6426. EXPECT_EQ(StatusCode::OK_200, res->status);
  6427. EXPECT_EQ("PUT", res->body);
  6428. }
  6429. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6430. auto res = cli_.Post(
  6431. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6432. "text/plain");
  6433. ASSERT_TRUE(!res);
  6434. EXPECT_EQ(Error::Canceled, res.error());
  6435. }
  6436. TEST_F(ServerTest, PostLoopBack) {
  6437. std::string body;
  6438. auto res = cli_.Post(
  6439. "/post-loopback", 9,
  6440. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6441. EXPECT_EQ(9u, length);
  6442. sink.write("123", 3);
  6443. sink.write("456", 3);
  6444. sink.write("789", 3);
  6445. return true;
  6446. },
  6447. "text/plain",
  6448. [&body](const char *data, size_t data_length) {
  6449. body.append(data, data_length);
  6450. return true;
  6451. });
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. EXPECT_EQ(StatusCode::OK_200, res->status);
  6454. EXPECT_EQ("123456789", body);
  6455. }
  6456. TEST_F(ServerTest, PutLoopBack) {
  6457. std::string body;
  6458. auto res = cli_.Put(
  6459. "/put-loopback", 9,
  6460. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6461. EXPECT_EQ(9u, length);
  6462. sink.write("123", 3);
  6463. sink.write("456", 3);
  6464. sink.write("789", 3);
  6465. return true;
  6466. },
  6467. "text/plain",
  6468. [&body](const char *data, size_t data_length) {
  6469. body.append(data, data_length);
  6470. return true;
  6471. });
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::OK_200, res->status);
  6474. EXPECT_EQ("123456789", body);
  6475. }
  6476. TEST_F(ServerTest, PatchLoopBack) {
  6477. std::string body;
  6478. auto res = cli_.Patch(
  6479. "/patch-loopback", 9,
  6480. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6481. EXPECT_EQ(9u, length);
  6482. sink.write("123", 3);
  6483. sink.write("456", 3);
  6484. sink.write("789", 3);
  6485. return true;
  6486. },
  6487. "text/plain",
  6488. [&body](const char *data, size_t data_length) {
  6489. body.append(data, data_length);
  6490. return true;
  6491. });
  6492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6493. EXPECT_EQ(StatusCode::OK_200, res->status);
  6494. EXPECT_EQ("123456789", body);
  6495. }
  6496. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6497. std::string body;
  6498. auto res = cli_.Post(
  6499. "/post-loopback",
  6500. [](size_t /*offset*/, DataSink &sink) {
  6501. sink.write("123", 3);
  6502. sink.write("456", 3);
  6503. sink.write("789", 3);
  6504. sink.done();
  6505. return true;
  6506. },
  6507. "text/plain",
  6508. [&body](const char *data, size_t data_length) {
  6509. body.append(data, data_length);
  6510. return true;
  6511. });
  6512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6513. EXPECT_EQ(StatusCode::OK_200, res->status);
  6514. EXPECT_EQ("123456789", body);
  6515. }
  6516. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6517. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6518. cli_.set_compress(true);
  6519. auto res = cli_.Put(
  6520. "/put", 3,
  6521. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6522. sink.os << "PUT";
  6523. return true;
  6524. },
  6525. "text/plain");
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. EXPECT_EQ(StatusCode::OK_200, res->status);
  6528. EXPECT_EQ("PUT", res->body);
  6529. }
  6530. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6531. cli_.set_compress(true);
  6532. auto res = cli_.Post(
  6533. "/post", 42,
  6534. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6535. return false;
  6536. },
  6537. "text/plain");
  6538. ASSERT_TRUE(!res);
  6539. EXPECT_EQ(Error::Canceled, res.error());
  6540. }
  6541. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6542. cli_.set_compress(true);
  6543. auto res = cli_.Put(
  6544. "/put",
  6545. [](size_t /*offset*/, DataSink &sink) {
  6546. sink.os << "PUT";
  6547. sink.done();
  6548. return true;
  6549. },
  6550. "text/plain");
  6551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6552. EXPECT_EQ(StatusCode::OK_200, res->status);
  6553. EXPECT_EQ("PUT", res->body);
  6554. }
  6555. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6556. cli_.set_compress(true);
  6557. auto res = cli_.Post(
  6558. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6559. "text/plain");
  6560. ASSERT_TRUE(!res);
  6561. EXPECT_EQ(Error::Canceled, res.error());
  6562. }
  6563. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6564. cli_.set_compress(true);
  6565. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6567. EXPECT_EQ(StatusCode::OK_200, res->status);
  6568. EXPECT_EQ(LARGE_DATA, res->body);
  6569. }
  6570. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6571. #ifdef CPPHTTPLIB_SSL_ENABLED
  6572. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6573. Client cli(s.c_str());
  6574. cli.enable_server_certificate_verification(false);
  6575. #else
  6576. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6577. Client cli(s.c_str());
  6578. #endif
  6579. cli.set_compress(true);
  6580. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6582. EXPECT_EQ(StatusCode::OK_200, res->status);
  6583. EXPECT_EQ(LARGE_DATA, res->body);
  6584. // The compressed size should be less than a 10th of the original. May vary
  6585. // depending on the zlib library.
  6586. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6587. static_cast<uint64_t>(10 * 1024 * 1024));
  6588. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6589. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6590. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6591. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6592. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6593. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6594. #endif
  6595. }
  6596. TEST_F(ServerTest, PutContentWithDeflate) {
  6597. cli_.set_compress(false);
  6598. Headers headers;
  6599. headers.emplace("Content-Encoding", "deflate");
  6600. // PUT in deflate format:
  6601. auto res = cli_.Put("/put", headers,
  6602. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6604. EXPECT_EQ(StatusCode::OK_200, res->status);
  6605. EXPECT_EQ("PUT", res->body);
  6606. }
  6607. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6608. Headers headers;
  6609. headers.emplace("Accept-Encoding", "gzip, deflate");
  6610. auto res = cli_.Get("/streamed-chunked", headers);
  6611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6612. EXPECT_EQ(StatusCode::OK_200, res->status);
  6613. EXPECT_EQ(std::string("123456789"), res->body);
  6614. }
  6615. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6616. Headers headers;
  6617. headers.emplace("Accept-Encoding", "gzip, deflate");
  6618. auto res = cli_.Get("/streamed-chunked2", headers);
  6619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6620. EXPECT_EQ(StatusCode::OK_200, res->status);
  6621. EXPECT_EQ(std::string("123456789"), res->body);
  6622. }
  6623. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6624. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6626. EXPECT_EQ(StatusCode::OK_200, res->status);
  6627. }
  6628. TEST(GzipDecompressor, ChunkedDecompression) {
  6629. std::string data;
  6630. for (size_t i = 0; i < 32 * 1024; ++i) {
  6631. data.push_back(static_cast<char>('a' + i % 26));
  6632. }
  6633. std::string compressed_data;
  6634. {
  6635. httplib::detail::gzip_compressor compressor;
  6636. bool result = compressor.compress(
  6637. data.data(), data.size(),
  6638. /*last=*/true,
  6639. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6640. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6641. compressed_data_size);
  6642. return true;
  6643. });
  6644. ASSERT_TRUE(result);
  6645. }
  6646. std::string decompressed_data;
  6647. {
  6648. httplib::detail::gzip_decompressor decompressor;
  6649. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6650. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6651. size_t chunk_size = 130;
  6652. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6653. chunk_begin += chunk_size) {
  6654. size_t current_chunk_size =
  6655. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6656. bool result = decompressor.decompress(
  6657. compressed_data.data() + chunk_begin, current_chunk_size,
  6658. [&](const char *decompressed_data_chunk,
  6659. size_t decompressed_data_chunk_size) {
  6660. decompressed_data.insert(decompressed_data.size(),
  6661. decompressed_data_chunk,
  6662. decompressed_data_chunk_size);
  6663. return true;
  6664. });
  6665. ASSERT_TRUE(result);
  6666. }
  6667. }
  6668. ASSERT_EQ(data, decompressed_data);
  6669. }
  6670. TEST(GzipDecompressor, DeflateDecompression) {
  6671. std::string original_text = "Raw deflate without gzip";
  6672. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6673. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6674. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6675. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6676. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6677. std::string decompressed_data;
  6678. {
  6679. httplib::detail::gzip_decompressor decompressor;
  6680. bool result = decompressor.decompress(
  6681. compressed_data.data(), compressed_data.size(),
  6682. [&](const char *decompressed_data_chunk,
  6683. size_t decompressed_data_chunk_size) {
  6684. decompressed_data.insert(decompressed_data.size(),
  6685. decompressed_data_chunk,
  6686. decompressed_data_chunk_size);
  6687. return true;
  6688. });
  6689. ASSERT_TRUE(result);
  6690. }
  6691. ASSERT_EQ(original_text, decompressed_data);
  6692. }
  6693. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6694. std::string original_text = "Raw deflate without gzip";
  6695. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6696. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6697. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6698. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6699. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6700. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6701. std::string decompressed_data;
  6702. {
  6703. httplib::detail::gzip_decompressor decompressor;
  6704. bool result = decompressor.decompress(
  6705. compressed_data.data(), compressed_data.size(),
  6706. [&](const char *decompressed_data_chunk,
  6707. size_t decompressed_data_chunk_size) {
  6708. decompressed_data.insert(decompressed_data.size(),
  6709. decompressed_data_chunk,
  6710. decompressed_data_chunk_size);
  6711. return true;
  6712. });
  6713. ASSERT_TRUE(result);
  6714. }
  6715. ASSERT_EQ(original_text, decompressed_data);
  6716. }
  6717. #endif
  6718. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6719. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6720. Headers headers;
  6721. headers.emplace("Accept-Encoding", "br");
  6722. auto res = cli_.Get("/streamed-chunked", headers);
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. EXPECT_EQ(StatusCode::OK_200, res->status);
  6725. EXPECT_EQ(std::string("123456789"), res->body);
  6726. }
  6727. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6728. Headers headers;
  6729. headers.emplace("Accept-Encoding", "br");
  6730. auto res = cli_.Get("/streamed-chunked2", headers);
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ(StatusCode::OK_200, res->status);
  6733. EXPECT_EQ(std::string("123456789"), res->body);
  6734. }
  6735. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6736. cli_.set_compress(true);
  6737. auto res = cli_.Put(
  6738. "/put", 3,
  6739. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6740. sink.os << "PUT";
  6741. return true;
  6742. },
  6743. "text/plain");
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. EXPECT_EQ("PUT", res->body);
  6747. }
  6748. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6749. cli_.set_compress(true);
  6750. auto res = cli_.Put(
  6751. "/put",
  6752. [](size_t /*offset*/, DataSink &sink) {
  6753. sink.os << "PUT";
  6754. sink.done();
  6755. return true;
  6756. },
  6757. "text/plain");
  6758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6759. EXPECT_EQ(StatusCode::OK_200, res->status);
  6760. EXPECT_EQ("PUT", res->body);
  6761. }
  6762. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6763. cli_.set_compress(true);
  6764. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ(LARGE_DATA, res->body);
  6768. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6769. }
  6770. #endif
  6771. TEST_F(ServerTest, Patch) {
  6772. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6774. EXPECT_EQ(StatusCode::OK_200, res->status);
  6775. EXPECT_EQ("PATCH", res->body);
  6776. }
  6777. TEST_F(ServerTest, Delete) {
  6778. auto res = cli_.Delete("/delete");
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. EXPECT_EQ("DELETE", res->body);
  6782. }
  6783. TEST_F(ServerTest, DeleteContentReceiver) {
  6784. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6786. EXPECT_EQ(StatusCode::OK_200, res->status);
  6787. EXPECT_EQ("content", res->body);
  6788. }
  6789. TEST_F(ServerTest, Options) {
  6790. auto res = cli_.Options("*");
  6791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6792. EXPECT_EQ(StatusCode::OK_200, res->status);
  6793. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6794. EXPECT_TRUE(res->body.empty());
  6795. }
  6796. TEST_F(ServerTest, URL) {
  6797. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6799. EXPECT_EQ(StatusCode::OK_200, res->status);
  6800. }
  6801. TEST_F(ServerTest, ArrayParam) {
  6802. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6804. EXPECT_EQ(StatusCode::OK_200, res->status);
  6805. }
  6806. TEST_F(ServerTest, ArrayParamValues) {
  6807. auto res =
  6808. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6810. EXPECT_EQ(StatusCode::OK_200, res->status);
  6811. }
  6812. TEST_F(ServerTest, NoMultipleHeaders) {
  6813. Headers headers = {{"Content-Length", "5"}};
  6814. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6815. "text/plain");
  6816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6817. EXPECT_EQ(StatusCode::OK_200, res->status);
  6818. }
  6819. TEST_F(ServerTest, PostContentReceiver) {
  6820. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6822. ASSERT_EQ(StatusCode::OK_200, res->status);
  6823. ASSERT_EQ("content", res->body);
  6824. }
  6825. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6826. UploadFormDataItems items = {
  6827. {"text1", "text default", "", ""},
  6828. {"text2", "aωb", "", ""},
  6829. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6830. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6831. {"file3", "", "", "application/octet-stream"},
  6832. };
  6833. auto res = cli_.Post("/content_receiver", items);
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ(StatusCode::OK_200, res->status);
  6836. }
  6837. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6838. UploadFormDataItems items = {
  6839. {"text1", "text default", "", ""},
  6840. {"text2", "aωb", "", ""},
  6841. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6842. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6843. {"file3", "", "", "application/octet-stream"},
  6844. };
  6845. auto boundary = std::string("+++++");
  6846. std::string body;
  6847. for (const auto &item : items) {
  6848. body += "--" + boundary + "\r\n";
  6849. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6850. if (!item.filename.empty()) {
  6851. body += "; filename=\"" + item.filename + "\"";
  6852. }
  6853. body += "\r\n";
  6854. if (!item.content_type.empty()) {
  6855. body += "Content-Type: " + item.content_type + "\r\n";
  6856. }
  6857. body += "\r\n";
  6858. body += item.content + "\r\n";
  6859. }
  6860. body += "--" + boundary + "--\r\n";
  6861. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6862. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6864. EXPECT_EQ(StatusCode::OK_200, res->status);
  6865. }
  6866. TEST(MultipartFormDataTest, FieldEscaping) {
  6867. Server svr;
  6868. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6869. const ContentReader &content_reader) {
  6870. ASSERT_TRUE(req.is_multipart_form_data());
  6871. std::vector<FormData> received;
  6872. content_reader(
  6873. [&](const FormData &file) {
  6874. received.push_back(file);
  6875. return true;
  6876. },
  6877. [&](const char *data, size_t data_length) {
  6878. received.back().content.append(data, data_length);
  6879. return true;
  6880. });
  6881. // '"', CR and LF in names and filenames are escaped following the
  6882. // WHATWG HTML standard, so each part still parses as a single part
  6883. // with no injected headers. Content types get CR/LF escaped too,
  6884. // while '"' (legal there, e.g. quoted charset) is preserved.
  6885. ASSERT_EQ(4U, received.size());
  6886. EXPECT_EQ("na%22me", received[0].name);
  6887. EXPECT_EQ("quoted name", received[0].content);
  6888. EXPECT_EQ("file", received[1].name);
  6889. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6890. received[1].filename);
  6891. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6892. EXPECT_EQ("injected", received[1].content);
  6893. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6894. EXPECT_EQ("my%22file.txt", received[2].filename);
  6895. EXPECT_EQ("cr lf name", received[2].content);
  6896. EXPECT_EQ("typed", received[3].name);
  6897. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6898. received[3].content_type);
  6899. EXPECT_EQ("typed content", received[3].content);
  6900. });
  6901. auto port = svr.bind_to_any_port("localhost");
  6902. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6903. auto se = detail::scope_exit([&] {
  6904. svr.stop();
  6905. t.join();
  6906. ASSERT_FALSE(svr.is_running());
  6907. });
  6908. svr.wait_until_ready();
  6909. Client cli("localhost", port);
  6910. UploadFormDataItems items = {
  6911. {"na\"me", "quoted name", "", ""},
  6912. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6913. "application/octet-stream"},
  6914. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6915. {"typed", "typed content", "",
  6916. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6917. };
  6918. auto res = cli.Post("/post", items);
  6919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6920. EXPECT_EQ(StatusCode::OK_200, res->status);
  6921. }
  6922. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6923. const UploadFormDataItems items = {
  6924. {"name1", "Content 1", "", ""},
  6925. {"name2", "Content 2", "file2.txt", "text/plain"},
  6926. };
  6927. Server svr;
  6928. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6929. const ContentReader &content_reader) {
  6930. ASSERT_TRUE(req.is_multipart_form_data());
  6931. std::vector<FormData> received;
  6932. content_reader(
  6933. [&](const FormData &file) {
  6934. received.push_back(file);
  6935. return true;
  6936. },
  6937. [&](const char *data, size_t data_length) {
  6938. received.back().content.append(data, data_length);
  6939. return true;
  6940. });
  6941. ASSERT_EQ(2U, received.size());
  6942. EXPECT_EQ("name1", received[0].name);
  6943. EXPECT_EQ("Content 1", received[0].content);
  6944. EXPECT_EQ("name2", received[1].name);
  6945. EXPECT_EQ("Content 2", received[1].content);
  6946. EXPECT_EQ("file2.txt", received[1].filename);
  6947. EXPECT_EQ("text/plain", received[1].content_type);
  6948. });
  6949. auto port = svr.bind_to_any_port("localhost");
  6950. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6951. auto se = detail::scope_exit([&] {
  6952. svr.stop();
  6953. t.join();
  6954. ASSERT_FALSE(svr.is_running());
  6955. });
  6956. svr.wait_until_ready();
  6957. Client cli("localhost", port);
  6958. // Whole-body serialization with a generated boundary
  6959. {
  6960. MultipartFormDataWriter writer;
  6961. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6962. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6963. writer.content_type());
  6964. auto body = writer.serialize(items);
  6965. EXPECT_EQ(body.size(), writer.content_length(items));
  6966. auto res = cli.Post("/post", body, writer.content_type());
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. EXPECT_EQ(StatusCode::OK_200, res->status);
  6969. }
  6970. // Per-part framing with a custom boundary via a content provider
  6971. {
  6972. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6973. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6974. MultipartFormDataWriter writer("custom-boundary_123");
  6975. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6976. std::string body;
  6977. for (const auto &item : items) {
  6978. body += writer.item_begin(item);
  6979. body += item.content;
  6980. body += MultipartFormDataWriter::item_end();
  6981. }
  6982. body += writer.finish();
  6983. EXPECT_EQ(body.size(), writer.content_length(items));
  6984. auto res = cli.Post(
  6985. "/post", body.size(),
  6986. [&](size_t offset, size_t length, DataSink &sink) {
  6987. sink.write(body.data() + offset, length);
  6988. return true;
  6989. },
  6990. writer.content_type());
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::OK_200, res->status);
  6993. }
  6994. }
  6995. TEST_F(ServerTest, PostContentReceiverGzip) {
  6996. cli_.set_compress(true);
  6997. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6999. ASSERT_EQ(StatusCode::OK_200, res->status);
  7000. ASSERT_EQ("content", res->body);
  7001. }
  7002. TEST_F(ServerTest, PutContentReceiver) {
  7003. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. ASSERT_EQ(StatusCode::OK_200, res->status);
  7006. ASSERT_EQ("content", res->body);
  7007. }
  7008. TEST_F(ServerTest, PatchContentReceiver) {
  7009. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7011. ASSERT_EQ(StatusCode::OK_200, res->status);
  7012. ASSERT_EQ("content", res->body);
  7013. }
  7014. template <typename ClientType>
  7015. void TestWithHeadersAndContentReceiver(
  7016. ClientType &cli,
  7017. std::function<Result(ClientType &, const std::string &, const Headers &,
  7018. const std::string &, const std::string &,
  7019. ContentReceiver, DownloadProgress)>
  7020. request_func) {
  7021. Headers headers;
  7022. headers.emplace("X-Custom-Header", "test-value");
  7023. std::string received_body;
  7024. auto res = request_func(
  7025. cli, "/content_receiver", headers, "content", "application/json",
  7026. [&](const char *data, size_t data_length) {
  7027. received_body.append(data, data_length);
  7028. return true;
  7029. },
  7030. nullptr);
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::OK_200, res->status);
  7033. EXPECT_EQ("content", received_body);
  7034. }
  7035. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7036. #ifdef CPPHTTPLIB_SSL_ENABLED
  7037. using ClientT = SSLClient;
  7038. #else
  7039. using ClientT = Client;
  7040. #endif
  7041. TestWithHeadersAndContentReceiver<ClientT>(
  7042. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7043. const std::string &body, const std::string &content_type,
  7044. ContentReceiver receiver, DownloadProgress progress) {
  7045. return cli.Post(path, headers, body, content_type, receiver, progress);
  7046. });
  7047. }
  7048. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7049. #ifdef CPPHTTPLIB_SSL_ENABLED
  7050. using ClientT = SSLClient;
  7051. #else
  7052. using ClientT = Client;
  7053. #endif
  7054. TestWithHeadersAndContentReceiver<ClientT>(
  7055. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7056. const std::string &body, const std::string &content_type,
  7057. ContentReceiver receiver, DownloadProgress progress) {
  7058. return cli.Put(path, headers, body, content_type, receiver, progress);
  7059. });
  7060. }
  7061. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7062. #ifdef CPPHTTPLIB_SSL_ENABLED
  7063. using ClientT = SSLClient;
  7064. #else
  7065. using ClientT = Client;
  7066. #endif
  7067. TestWithHeadersAndContentReceiver<ClientT>(
  7068. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7069. const std::string &body, const std::string &content_type,
  7070. ContentReceiver receiver, DownloadProgress progress) {
  7071. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7072. });
  7073. }
  7074. template <typename ClientType>
  7075. void TestWithHeadersAndContentReceiverWithProgress(
  7076. ClientType &cli,
  7077. std::function<Result(ClientType &, const std::string &, const Headers &,
  7078. const std::string &, const std::string &,
  7079. ContentReceiver, DownloadProgress)>
  7080. request_func) {
  7081. Headers headers;
  7082. headers.emplace("X-Test-Header", "progress-test");
  7083. std::string received_body;
  7084. auto progress_called = false;
  7085. auto res = request_func(
  7086. cli, "/content_receiver", headers, "content", "text/plain",
  7087. [&](const char *data, size_t data_length) {
  7088. received_body.append(data, data_length);
  7089. return true;
  7090. },
  7091. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7092. progress_called = true;
  7093. return true;
  7094. });
  7095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7096. EXPECT_EQ(StatusCode::OK_200, res->status);
  7097. EXPECT_EQ("content", received_body);
  7098. EXPECT_TRUE(progress_called);
  7099. }
  7100. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7101. #ifdef CPPHTTPLIB_SSL_ENABLED
  7102. using ClientT = SSLClient;
  7103. #else
  7104. using ClientT = Client;
  7105. #endif
  7106. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7107. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7108. const std::string &body, const std::string &content_type,
  7109. ContentReceiver receiver, DownloadProgress progress) {
  7110. return cli.Post(path, headers, body, content_type, receiver, progress);
  7111. });
  7112. }
  7113. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7114. #ifdef CPPHTTPLIB_SSL_ENABLED
  7115. using ClientT = SSLClient;
  7116. #else
  7117. using ClientT = Client;
  7118. #endif
  7119. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7120. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7121. const std::string &body, const std::string &content_type,
  7122. ContentReceiver receiver, DownloadProgress progress) {
  7123. return cli.Put(path, headers, body, content_type, receiver, progress);
  7124. });
  7125. }
  7126. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7127. #ifdef CPPHTTPLIB_SSL_ENABLED
  7128. using ClientT = SSLClient;
  7129. #else
  7130. using ClientT = Client;
  7131. #endif
  7132. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7133. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7134. const std::string &body, const std::string &content_type,
  7135. ContentReceiver receiver, DownloadProgress progress) {
  7136. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7137. });
  7138. }
  7139. template <typename ClientType>
  7140. void TestWithHeadersAndContentReceiverError(
  7141. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7142. const Headers &, const std::string &,
  7143. const std::string &, ContentReceiver)>
  7144. request_func) {
  7145. Headers headers;
  7146. headers.emplace("X-Error-Test", "true");
  7147. std::string received_body;
  7148. auto receiver_failed = false;
  7149. auto res =
  7150. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7151. [&](const char *data, size_t data_length) {
  7152. received_body.append(data, data_length);
  7153. receiver_failed = true;
  7154. return false;
  7155. });
  7156. ASSERT_FALSE(res);
  7157. EXPECT_TRUE(receiver_failed);
  7158. }
  7159. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7160. #ifdef CPPHTTPLIB_SSL_ENABLED
  7161. using ClientT = SSLClient;
  7162. #else
  7163. using ClientT = Client;
  7164. #endif
  7165. TestWithHeadersAndContentReceiverError<ClientT>(
  7166. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7167. const std::string &body, const std::string &content_type,
  7168. ContentReceiver receiver) {
  7169. return cli.Post(path, headers, body, content_type, receiver);
  7170. });
  7171. }
  7172. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7173. #ifdef CPPHTTPLIB_SSL_ENABLED
  7174. using ClientT = SSLClient;
  7175. #else
  7176. using ClientT = Client;
  7177. #endif
  7178. TestWithHeadersAndContentReceiverError<ClientT>(
  7179. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7180. const std::string &body, const std::string &content_type,
  7181. ContentReceiver receiver) {
  7182. return cli.Put(path, headers, body, content_type, receiver);
  7183. });
  7184. }
  7185. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7186. #ifdef CPPHTTPLIB_SSL_ENABLED
  7187. using ClientT = SSLClient;
  7188. #else
  7189. using ClientT = Client;
  7190. #endif
  7191. TestWithHeadersAndContentReceiverError<ClientT>(
  7192. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7193. const std::string &body, const std::string &content_type,
  7194. ContentReceiver receiver) {
  7195. return cli.Patch(path, headers, body, content_type, receiver);
  7196. });
  7197. }
  7198. TEST_F(ServerTest, PostQueryStringAndBody) {
  7199. auto res =
  7200. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. ASSERT_EQ(StatusCode::OK_200, res->status);
  7203. }
  7204. TEST_F(ServerTest, HTTP2Magic) {
  7205. Request req;
  7206. req.method = "PRI";
  7207. req.path = "*";
  7208. req.body = "SM";
  7209. auto res = std::make_shared<Response>();
  7210. auto error = Error::Success;
  7211. auto ret = cli_.send(req, *res, error);
  7212. ASSERT_TRUE(ret);
  7213. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7214. }
  7215. TEST_F(ServerTest, KeepAlive) {
  7216. auto res = cli_.Get("/hi");
  7217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7218. EXPECT_EQ(StatusCode::OK_200, res->status);
  7219. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7220. EXPECT_EQ("Hello World!", res->body);
  7221. res = cli_.Get("/hi");
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::OK_200, res->status);
  7224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7225. EXPECT_EQ("Hello World!", res->body);
  7226. res = cli_.Get("/hi");
  7227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7228. EXPECT_EQ(StatusCode::OK_200, res->status);
  7229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7230. EXPECT_EQ("Hello World!", res->body);
  7231. res = cli_.Get("/not-exist");
  7232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7234. res = cli_.Post("/empty", "", "text/plain");
  7235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7236. EXPECT_EQ(StatusCode::OK_200, res->status);
  7237. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7238. EXPECT_EQ("empty", res->body);
  7239. EXPECT_EQ("close", res->get_header_value("Connection"));
  7240. res = cli_.Post(
  7241. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7242. "text/plain");
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7246. EXPECT_EQ("empty", res->body);
  7247. cli_.set_keep_alive(false);
  7248. res = cli_.Get("/last-request");
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::OK_200, res->status);
  7251. EXPECT_EQ("close", res->get_header_value("Connection"));
  7252. }
  7253. TEST_F(ServerTest, TooManyRedirect) {
  7254. cli_.set_follow_location(true);
  7255. auto res = cli_.Get("/redirect/0");
  7256. ASSERT_TRUE(!res);
  7257. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7258. }
  7259. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7260. Request req;
  7261. req.method = "FOOBAR";
  7262. req.path = "/hi";
  7263. cli_.set_keep_alive(true);
  7264. auto res = cli_.send(req);
  7265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7266. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7267. EXPECT_EQ("close", res->get_header_value("Connection"));
  7268. EXPECT_FALSE(cli_.is_socket_open());
  7269. }
  7270. TEST_F(ServerTest, CustomRouteReadsBody) {
  7271. const std::string xml =
  7272. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7273. Request req;
  7274. req.method = "PROPFIND";
  7275. req.path = "/dav/dir";
  7276. req.set_header("Depth", "1");
  7277. req.body = xml;
  7278. auto res = cli_.send(req);
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7281. EXPECT_EQ(xml, res->body);
  7282. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7283. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7284. }
  7285. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7286. Request req;
  7287. req.method = "PROPFIND";
  7288. req.path = "/dav/42";
  7289. auto res = cli_.send(req);
  7290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7291. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7292. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7293. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7294. }
  7295. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7296. Request req;
  7297. req.method = "PROPFIND";
  7298. req.path = "/dav-re/123";
  7299. auto res = cli_.send(req);
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7302. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7303. }
  7304. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7305. Request req;
  7306. req.method = "MKCOL";
  7307. req.path = "/dav-mkcol";
  7308. auto res = cli_.send(req);
  7309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7310. EXPECT_EQ(StatusCode::Created_201, res->status);
  7311. }
  7312. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7313. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7314. Request req;
  7315. req.method = "REPORT";
  7316. req.path = "/dav-report";
  7317. req.body = xml;
  7318. auto res = cli_.send(req);
  7319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7320. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7321. EXPECT_EQ(xml, res->body);
  7322. }
  7323. // A content reader route must fire even when the request carries no body,
  7324. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7325. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7326. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7327. Request req;
  7328. req.method = "REPORT";
  7329. req.path = "/dav-report";
  7330. auto res = cli_.send(req);
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7333. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7334. }
  7335. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7336. Request req;
  7337. req.method = "PROPFIND";
  7338. req.path = "/not-dav";
  7339. auto res = cli_.send(req);
  7340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7341. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7342. }
  7343. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7344. Request req;
  7345. req.method = "UNLOCK";
  7346. req.path = "/dav/dir";
  7347. cli_.set_keep_alive(true);
  7348. auto res = cli_.send(req);
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7351. EXPECT_EQ("close", res->get_header_value("Connection"));
  7352. EXPECT_FALSE(cli_.is_socket_open());
  7353. }
  7354. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7355. // The mount point serves this path, but only for GET and HEAD.
  7356. auto get_res = cli_.Get("/dir/index.html");
  7357. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7358. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7359. Request req;
  7360. req.method = "PROPFIND";
  7361. req.path = "/dir/index.html";
  7362. auto res = cli_.send(req);
  7363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7364. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7365. }
  7366. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7367. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7368. cli_.set_keep_alive(true);
  7369. for (auto i = 0; i < 2; i++) {
  7370. Request req;
  7371. req.method = "PROPFIND";
  7372. req.path = "/dav/dir";
  7373. req.body = xml;
  7374. auto res = cli_.send(req);
  7375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7376. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7377. EXPECT_EQ(xml, res->body);
  7378. EXPECT_TRUE(cli_.is_socket_open());
  7379. }
  7380. // A built-in method must still be served on the same connection.
  7381. cli_.set_keep_alive(false);
  7382. auto res = cli_.Get("/hi");
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::OK_200, res->status);
  7385. EXPECT_EQ("close", res->get_header_value("Connection"));
  7386. }
  7387. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7388. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7389. Request req;
  7390. req.method = "PROPFIND";
  7391. req.path = "/dav/dir";
  7392. req.set_header("Expect", "100-continue");
  7393. req.body = xml;
  7394. auto res = cli_.send(req);
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7397. EXPECT_EQ(xml, res->body);
  7398. }
  7399. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7400. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7401. TEST_F(ServerTest, Gzip) {
  7402. Headers headers;
  7403. headers.emplace("Accept-Encoding", "gzip, deflate");
  7404. auto res = cli_.Get("/compress", headers);
  7405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7406. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7407. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7408. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7409. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7410. "7890123456789012345678901234567890",
  7411. res->body);
  7412. EXPECT_EQ(StatusCode::OK_200, res->status);
  7413. }
  7414. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7415. Headers headers;
  7416. headers.emplace("Accept-Encoding", "gzip, deflate");
  7417. auto res = cli_.Get("/compress-with-charset", headers);
  7418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7419. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7420. EXPECT_EQ("application/json; charset=utf-8",
  7421. res->get_header_value("Content-Type"));
  7422. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7423. "7890123456789012345678901234567890",
  7424. res->body);
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. }
  7427. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7428. Headers headers;
  7429. headers.emplace("Accept-Encoding", "");
  7430. auto res = cli_.Get("/compress", headers);
  7431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7432. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7434. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7435. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7436. "7890123456789012345678901234567890",
  7437. res->body);
  7438. EXPECT_EQ(StatusCode::OK_200, res->status);
  7439. }
  7440. TEST_F(ServerTest, GzipWithContentReceiver) {
  7441. Headers headers;
  7442. headers.emplace("Accept-Encoding", "gzip, deflate");
  7443. std::string body;
  7444. auto res = cli_.Get("/compress", headers,
  7445. [&](const char *data, uint64_t data_length) {
  7446. EXPECT_EQ(100U, data_length);
  7447. body.append(data, data_length);
  7448. return true;
  7449. });
  7450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7451. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7452. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7453. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7454. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7455. "7890123456789012345678901234567890",
  7456. body);
  7457. EXPECT_EQ(StatusCode::OK_200, res->status);
  7458. }
  7459. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7460. Headers headers;
  7461. headers.emplace("Accept-Encoding", "gzip, deflate");
  7462. cli_.set_decompress(false);
  7463. auto res = cli_.Get("/compress", headers);
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7466. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7467. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7468. EXPECT_EQ(33U, res->body.size());
  7469. EXPECT_EQ(StatusCode::OK_200, res->status);
  7470. }
  7471. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7472. Headers headers;
  7473. headers.emplace("Accept-Encoding", "");
  7474. std::string body;
  7475. auto res = cli_.Get("/compress", headers,
  7476. [&](const char *data, uint64_t data_length) {
  7477. EXPECT_EQ(100U, data_length);
  7478. body.append(data, data_length);
  7479. return true;
  7480. });
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7484. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7485. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7486. "7890123456789012345678901234567890",
  7487. body);
  7488. EXPECT_EQ(StatusCode::OK_200, res->status);
  7489. }
  7490. TEST_F(ServerTest, NoGzip) {
  7491. Headers headers;
  7492. headers.emplace("Accept-Encoding", "gzip, deflate");
  7493. auto res = cli_.Get("/nocompress", headers);
  7494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7495. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7496. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7497. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7498. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7499. "7890123456789012345678901234567890",
  7500. res->body);
  7501. EXPECT_EQ(StatusCode::OK_200, res->status);
  7502. }
  7503. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7504. Headers headers;
  7505. headers.emplace("Accept-Encoding", "gzip, deflate");
  7506. std::string body;
  7507. auto res = cli_.Get("/nocompress", headers,
  7508. [&](const char *data, uint64_t data_length) {
  7509. EXPECT_EQ(100U, data_length);
  7510. body.append(data, data_length);
  7511. return true;
  7512. });
  7513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7514. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7515. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7516. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7517. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7518. "7890123456789012345678901234567890",
  7519. body);
  7520. EXPECT_EQ(StatusCode::OK_200, res->status);
  7521. }
  7522. TEST_F(ServerTest, MultipartFormDataGzip) {
  7523. UploadFormDataItems items = {
  7524. {"key1", "test", "", ""},
  7525. {"key2", "--abcdefg123", "", ""},
  7526. };
  7527. cli_.set_compress(true);
  7528. auto res = cli_.Post("/compress-multipart", items);
  7529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7530. EXPECT_EQ(StatusCode::OK_200, res->status);
  7531. }
  7532. #endif
  7533. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7534. // Static file compression is opt-in, so these run their own server rather than
  7535. // flipping it on for the shared ServerTest fixture, which would silently
  7536. // rewrite what every other static file test is asserting.
  7537. class StaticFileCompressionTest : public ::testing::Test {
  7538. protected:
  7539. void TearDown() override {
  7540. if (t_.joinable()) {
  7541. svr_.stop();
  7542. t_.join();
  7543. }
  7544. }
  7545. int start(const std::function<void(Server &)> &configure = nullptr) {
  7546. svr_.set_mount_point("/", "./www");
  7547. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7548. res.set_file_content("./www/dir/index.html", "text/html");
  7549. });
  7550. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7551. res.set_content_provider(
  7552. 6, "text/plain",
  7553. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7554. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7555. return true;
  7556. });
  7557. });
  7558. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7559. res.set_content_provider(
  7560. 1000, "text/plain",
  7561. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7562. if (offset < 100) {
  7563. std::string data(100, 'A');
  7564. sink.write(data.data(), data.size());
  7565. return true;
  7566. }
  7567. std::this_thread::sleep_for(std::chrono::seconds(2));
  7568. std::string data(900, 'B');
  7569. sink.write(data.data(), data.size());
  7570. return true;
  7571. });
  7572. });
  7573. if (configure) { configure(svr_); }
  7574. auto port = svr_.bind_to_any_port(HOST);
  7575. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7576. svr_.wait_until_ready();
  7577. return port;
  7578. }
  7579. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7580. // Every file under ./www except 1MB.txt is smaller than the default
  7581. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7582. // it out of the way.
  7583. static void enable_without_floor(Server &svr) {
  7584. svr.set_static_file_compression(true);
  7585. svr.set_static_file_compression_min_length(0);
  7586. }
  7587. Server svr_;
  7588. std::thread t_;
  7589. };
  7590. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7591. auto port = start();
  7592. Client cli(HOST, port);
  7593. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7595. EXPECT_EQ(StatusCode::OK_200, res->status);
  7596. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7597. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7598. EXPECT_EQ(1048576U, res->body.size());
  7599. }
  7600. TEST_F(StaticFileCompressionTest, MountPoint) {
  7601. auto port = start(enable);
  7602. Client cli(HOST, port);
  7603. cli.set_decompress(false);
  7604. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7606. EXPECT_EQ(StatusCode::OK_200, res->status);
  7607. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7608. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7609. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7610. // The response stays self-delimiting: a length, not a chunked body.
  7611. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7612. EXPECT_EQ(std::to_string(res->body.size()),
  7613. res->get_header_value("Content-Length"));
  7614. EXPECT_LT(res->body.size(), 1048576U);
  7615. EXPECT_FALSE(res->body.empty());
  7616. }
  7617. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7618. auto port = start(enable);
  7619. Client cli(HOST, port);
  7620. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7622. EXPECT_EQ(StatusCode::OK_200, res->status);
  7623. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7624. EXPECT_EQ(1048576U, res->body.size());
  7625. }
  7626. TEST_F(StaticFileCompressionTest, FileContent) {
  7627. auto port = start(enable_without_floor);
  7628. Client cli(HOST, port);
  7629. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7631. EXPECT_EQ(StatusCode::OK_200, res->status);
  7632. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7633. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7634. EXPECT_EQ(104U, res->body.size());
  7635. }
  7636. TEST_F(StaticFileCompressionTest, Head) {
  7637. auto port = start(enable);
  7638. Client cli(HOST, port);
  7639. cli.set_decompress(false);
  7640. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7641. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7642. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7644. EXPECT_EQ(StatusCode::OK_200, res->status);
  7645. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7646. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7647. // HEAD still reports the size a GET would return.
  7648. EXPECT_EQ(get->get_header_value("Content-Length"),
  7649. res->get_header_value("Content-Length"));
  7650. EXPECT_TRUE(res->body.empty());
  7651. }
  7652. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7653. auto port = start(enable);
  7654. Client cli(HOST, port);
  7655. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7656. {"Accept-Encoding", "gzip"}});
  7657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7658. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7659. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7660. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7661. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7662. EXPECT_EQ("cd", res->body);
  7663. }
  7664. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7665. auto port = start(enable);
  7666. Client cli(HOST, port);
  7667. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7669. EXPECT_EQ(StatusCode::OK_200, res->status);
  7670. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7671. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7672. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7673. }
  7674. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7675. auto port = start(enable);
  7676. Client cli(HOST, port);
  7677. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7679. EXPECT_EQ(StatusCode::OK_200, res->status);
  7680. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7681. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7682. EXPECT_TRUE(res->body.empty());
  7683. }
  7684. TEST_F(StaticFileCompressionTest, MinLength) {
  7685. auto port = start(enable);
  7686. Client cli(HOST, port);
  7687. // 104 bytes, well under the default floor. Compressing it would add the
  7688. // gzip header and trailer to a body that already fits in one packet.
  7689. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7691. EXPECT_EQ(StatusCode::OK_200, res->status);
  7692. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7693. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7694. }
  7695. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7696. auto port = start([](Server &svr) {
  7697. svr.set_static_file_compression(true);
  7698. svr.set_static_file_compression_min_length(1);
  7699. });
  7700. Client cli(HOST, port);
  7701. cli.set_decompress(false);
  7702. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7705. // A 9-byte file comes back larger than it went in, because gzip's header and
  7706. // trailer outweigh anything deflate can save. That is the end of the range
  7707. // the floor exists to keep out.
  7708. EXPECT_GT(res->body.size(), 9U);
  7709. }
  7710. TEST_F(StaticFileCompressionTest, MaxLength) {
  7711. auto port = start([](Server &svr) {
  7712. svr.set_static_file_compression(true);
  7713. svr.set_static_file_compression_min_length(0);
  7714. svr.set_static_file_compression_max_length(1024);
  7715. });
  7716. Client cli(HOST, port);
  7717. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7718. // defines `small` as a macro on Windows.
  7719. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7720. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7721. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7722. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7723. // Under it: compressed.
  7724. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7725. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7726. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7727. }
  7728. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7729. auto port = start(enable_without_floor);
  7730. Client cli(HOST, port);
  7731. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7732. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7733. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7734. auto identity_etag = identity->get_header_value("ETag");
  7735. ASSERT_FALSE(identity_etag.empty());
  7736. auto gzipped =
  7737. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7738. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7739. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7740. auto gzip_etag = gzipped->get_header_value("ETag");
  7741. ASSERT_FALSE(gzip_etag.empty());
  7742. // Two representations, two validators.
  7743. EXPECT_NE(identity_etag, gzip_etag);
  7744. // Each one revalidates against the request that would produce it...
  7745. auto fresh =
  7746. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7747. {"If-None-Match", gzip_etag}});
  7748. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7749. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7750. auto fresh_identity =
  7751. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7752. {"If-None-Match", identity_etag}});
  7753. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7754. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7755. // ...and not against the other representation.
  7756. auto crossed =
  7757. cli.Get("/dir/index.html",
  7758. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7759. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7760. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7761. }
  7762. // The opt-in covers responses the server reads off disk itself. A caller's own
  7763. // known-length provider keeps its Content-Length and, more importantly, keeps
  7764. // delivering incrementally: routing it through a compressor would hold every
  7765. // write back until zlib's window filled.
  7766. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7767. auto port = start(enable);
  7768. Client cli(HOST, port);
  7769. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. EXPECT_EQ(StatusCode::OK_200, res->status);
  7772. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7773. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7774. EXPECT_EQ("aaabbb", res->body);
  7775. }
  7776. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7777. auto port = start(enable);
  7778. Client cli(HOST, port);
  7779. cli.set_read_timeout(1, 0);
  7780. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7781. Headers{{"Accept-Encoding", "gzip"}});
  7782. ASSERT_TRUE(handle.is_valid());
  7783. // The provider writes 100 bytes and then stalls for longer than the read
  7784. // timeout. Those first bytes have to arrive anyway: run the response through
  7785. // a compressor and zlib holds them until its window fills, so the read would
  7786. // come back empty instead.
  7787. char buf[256];
  7788. auto n = handle.read(buf, sizeof(buf));
  7789. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7790. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7791. }
  7792. #endif
  7793. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7794. TEST_F(ServerTest, Brotli) {
  7795. Headers headers;
  7796. headers.emplace("Accept-Encoding", "br");
  7797. auto res = cli_.Get("/compress", headers);
  7798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7799. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7800. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7801. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7802. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7803. "7890123456789012345678901234567890",
  7804. res->body);
  7805. EXPECT_EQ(StatusCode::OK_200, res->status);
  7806. }
  7807. #endif
  7808. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7809. TEST_F(ServerTest, Zstd) {
  7810. Headers headers;
  7811. headers.emplace("Accept-Encoding", "zstd");
  7812. auto res = cli_.Get("/compress", headers);
  7813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7814. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7815. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7816. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7817. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7818. "7890123456789012345678901234567890",
  7819. res->body);
  7820. EXPECT_EQ(StatusCode::OK_200, res->status);
  7821. }
  7822. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7823. Headers headers;
  7824. headers.emplace("Accept-Encoding", "");
  7825. auto res = cli_.Get("/compress", headers);
  7826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7827. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7828. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7829. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7830. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7831. "7890123456789012345678901234567890",
  7832. res->body);
  7833. EXPECT_EQ(StatusCode::OK_200, res->status);
  7834. }
  7835. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7836. Headers headers;
  7837. headers.emplace("Accept-Encoding", "zstd");
  7838. std::string body;
  7839. auto res = cli_.Get("/compress", headers,
  7840. [&](const char *data, uint64_t data_length) {
  7841. EXPECT_EQ(100U, data_length);
  7842. body.append(data, data_length);
  7843. return true;
  7844. });
  7845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7846. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7847. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7848. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7849. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7850. "7890123456789012345678901234567890",
  7851. body);
  7852. EXPECT_EQ(StatusCode::OK_200, res->status);
  7853. }
  7854. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7855. Headers headers;
  7856. headers.emplace("Accept-Encoding", "zstd");
  7857. cli_.set_decompress(false);
  7858. auto res = cli_.Get("/compress", headers);
  7859. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7860. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7861. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7862. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7864. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7865. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7866. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7867. EXPECT_EQ(StatusCode::OK_200, res->status);
  7868. ASSERT_EQ(26U, res->body.size());
  7869. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7870. 0);
  7871. }
  7872. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7873. Headers headers;
  7874. headers.emplace("Accept-Encoding", "");
  7875. std::string body;
  7876. auto res = cli_.Get("/compress", headers,
  7877. [&](const char *data, uint64_t data_length) {
  7878. EXPECT_EQ(100U, data_length);
  7879. body.append(data, data_length);
  7880. return true;
  7881. });
  7882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7883. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7884. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7885. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7886. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7887. "7890123456789012345678901234567890",
  7888. body);
  7889. EXPECT_EQ(StatusCode::OK_200, res->status);
  7890. }
  7891. TEST_F(ServerTest, NoZstd) {
  7892. Headers headers;
  7893. headers.emplace("Accept-Encoding", "zstd");
  7894. auto res = cli_.Get("/nocompress", headers);
  7895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7896. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7897. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7898. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7899. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7900. "7890123456789012345678901234567890",
  7901. res->body);
  7902. EXPECT_EQ(StatusCode::OK_200, res->status);
  7903. }
  7904. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7905. Headers headers;
  7906. headers.emplace("Accept-Encoding", "zstd");
  7907. std::string body;
  7908. auto res = cli_.Get("/nocompress", headers,
  7909. [&](const char *data, uint64_t data_length) {
  7910. EXPECT_EQ(100U, data_length);
  7911. body.append(data, data_length);
  7912. return true;
  7913. });
  7914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7915. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7916. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7917. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7918. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7919. "7890123456789012345678901234567890",
  7920. body);
  7921. EXPECT_EQ(StatusCode::OK_200, res->status);
  7922. }
  7923. // TODO: How to enable zstd ??
  7924. TEST_F(ServerTest, MultipartFormDataZstd) {
  7925. UploadFormDataItems items = {
  7926. {"key1", "test", "", ""},
  7927. {"key2", "--abcdefg123", "", ""},
  7928. };
  7929. Headers headers;
  7930. headers.emplace("Accept-Encoding", "zstd");
  7931. cli_.set_compress(true);
  7932. auto res = cli_.Post("/compress-multipart", headers, items);
  7933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7934. EXPECT_EQ(StatusCode::OK_200, res->status);
  7935. }
  7936. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7937. Headers headers;
  7938. headers.emplace("Accept-Encoding", "zstd");
  7939. cli_.set_compress(true);
  7940. auto res = cli_.Put(
  7941. "/put", headers, 3,
  7942. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7943. sink.os << "PUT";
  7944. return true;
  7945. },
  7946. "text/plain");
  7947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7948. EXPECT_EQ(StatusCode::OK_200, res->status);
  7949. EXPECT_EQ("PUT", res->body);
  7950. }
  7951. // Pre-compression logging tests
  7952. TEST_F(ServerTest, PreCompressionLogging) {
  7953. // Test data for compression (matches the actual /compress endpoint content)
  7954. const std::string test_content =
  7955. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7956. "3456789012345678901234567890";
  7957. // Variables to capture logging data
  7958. std::string pre_compression_body;
  7959. std::string pre_compression_content_type;
  7960. std::string pre_compression_content_encoding;
  7961. std::string post_compression_body;
  7962. std::string post_compression_content_type;
  7963. std::string post_compression_content_encoding;
  7964. // Set up pre-compression logger
  7965. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7966. const Response &res) {
  7967. pre_compression_body = res.body;
  7968. pre_compression_content_type = res.get_header_value("Content-Type");
  7969. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7970. });
  7971. // Set up post-compression logger
  7972. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7973. post_compression_body = res.body;
  7974. post_compression_content_type = res.get_header_value("Content-Type");
  7975. post_compression_content_encoding =
  7976. res.get_header_value("Content-Encoding");
  7977. });
  7978. // Test with gzip compression
  7979. Headers headers;
  7980. headers.emplace("Accept-Encoding", "gzip");
  7981. auto res = cli_.Get("/compress", headers);
  7982. // Verify response was compressed
  7983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7986. // Verify pre-compression logger captured uncompressed content
  7987. EXPECT_EQ(test_content, pre_compression_body);
  7988. EXPECT_EQ("text/plain", pre_compression_content_type);
  7989. EXPECT_TRUE(pre_compression_content_encoding
  7990. .empty()); // No encoding header before compression
  7991. // Verify post-compression logger captured compressed content
  7992. EXPECT_NE(test_content,
  7993. post_compression_body); // Should be different after compression
  7994. EXPECT_EQ("text/plain", post_compression_content_type);
  7995. EXPECT_EQ("gzip", post_compression_content_encoding);
  7996. // Verify compressed content is smaller
  7997. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7998. }
  7999. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8000. const std::string test_content =
  8001. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8002. "3456789012345678901234567890";
  8003. std::string pre_compression_body;
  8004. std::string post_compression_body;
  8005. svr_.set_pre_compression_logger(
  8006. [&](const Request & /*req*/, const Response &res) {
  8007. pre_compression_body = res.body;
  8008. });
  8009. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8010. post_compression_body = res.body;
  8011. });
  8012. Headers headers;
  8013. headers.emplace("Accept-Encoding", "br");
  8014. auto res = cli_.Get("/compress", headers);
  8015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8016. EXPECT_EQ(StatusCode::OK_200, res->status);
  8017. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8018. // Verify pre-compression content is uncompressed
  8019. EXPECT_EQ(test_content, pre_compression_body);
  8020. // Verify post-compression content is compressed
  8021. EXPECT_NE(test_content, post_compression_body);
  8022. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8023. }
  8024. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8025. const std::string test_content =
  8026. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8027. "3456789012345678901234567890";
  8028. std::string pre_compression_body;
  8029. std::string post_compression_body;
  8030. svr_.set_pre_compression_logger(
  8031. [&](const Request & /*req*/, const Response &res) {
  8032. pre_compression_body = res.body;
  8033. });
  8034. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8035. post_compression_body = res.body;
  8036. });
  8037. // Request without compression (use /nocompress endpoint)
  8038. Headers headers;
  8039. auto res = cli_.Get("/nocompress", headers);
  8040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8041. EXPECT_EQ(StatusCode::OK_200, res->status);
  8042. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8043. // Pre-compression logger should not be called when no compression is applied
  8044. EXPECT_TRUE(
  8045. pre_compression_body.empty()); // Pre-compression logger not called
  8046. EXPECT_EQ(
  8047. test_content,
  8048. post_compression_body); // Post-compression logger captures final content
  8049. }
  8050. TEST_F(ServerTest, LoggerSeesContentLength) {
  8051. size_t logged_content_length = 0;
  8052. std::string logged_content_length_header;
  8053. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8054. logged_content_length = res.content_length_;
  8055. logged_content_length_header = res.get_header_value("Content-Length");
  8056. });
  8057. auto res = cli_.Get("/nocompress");
  8058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8059. EXPECT_EQ(StatusCode::OK_200, res->status);
  8060. EXPECT_EQ(res->body.size(), logged_content_length);
  8061. EXPECT_EQ(std::to_string(logged_content_length),
  8062. logged_content_length_header);
  8063. }
  8064. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8065. const std::string test_content =
  8066. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8067. "3456789012345678901234567890";
  8068. std::string pre_compression_body;
  8069. bool pre_logger_called = false;
  8070. // Set only pre-compression logger
  8071. svr_.set_pre_compression_logger(
  8072. [&](const Request & /*req*/, const Response &res) {
  8073. pre_compression_body = res.body;
  8074. pre_logger_called = true;
  8075. });
  8076. Headers headers;
  8077. headers.emplace("Accept-Encoding", "gzip");
  8078. auto res = cli_.Get("/compress", headers);
  8079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8080. EXPECT_EQ(StatusCode::OK_200, res->status);
  8081. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8082. // Verify pre-compression logger was called
  8083. EXPECT_TRUE(pre_logger_called);
  8084. EXPECT_EQ(test_content, pre_compression_body);
  8085. }
  8086. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8087. {
  8088. // Test with Expect: 100-continue header - success case
  8089. // Server returns 100 Continue, client sends body, server returns 200 OK
  8090. Request req;
  8091. req.method = "POST";
  8092. req.path = "/post-large";
  8093. req.set_header("Expect", "100-continue");
  8094. req.body = LARGE_DATA;
  8095. Response res;
  8096. auto error = Error::Success;
  8097. cli_.set_keep_alive(true);
  8098. auto ret = cli_.send(req, res, error);
  8099. EXPECT_TRUE(ret);
  8100. EXPECT_EQ(StatusCode::OK_200, res.status);
  8101. EXPECT_EQ(LARGE_DATA, res.body);
  8102. }
  8103. {
  8104. // Test with Expect: 100-continue header - error case
  8105. // Client should not send the body when server returns an error
  8106. Request req;
  8107. req.method = "POST";
  8108. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8109. req.set_header("Expect", "100-continue");
  8110. req.body = LARGE_DATA;
  8111. Response res;
  8112. auto error = Error::Success;
  8113. auto start = std::chrono::high_resolution_clock::now();
  8114. cli_.set_keep_alive(true);
  8115. auto ret = cli_.send(req, res, error);
  8116. auto end = std::chrono::high_resolution_clock::now();
  8117. auto elapsed =
  8118. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8119. .count();
  8120. // With Expect: 100-continue, request completes successfully but with error
  8121. EXPECT_TRUE(ret);
  8122. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8123. EXPECT_EQ("close", res.get_header_value("Connection"));
  8124. EXPECT_FALSE(cli_.is_socket_open());
  8125. EXPECT_LE(elapsed, 2000);
  8126. }
  8127. {
  8128. // Send an extra GET request to ensure error recovery without hanging
  8129. Request req;
  8130. req.method = "GET";
  8131. req.path = "/hi";
  8132. auto start = std::chrono::high_resolution_clock::now();
  8133. auto res = cli_.send(req);
  8134. auto end = std::chrono::high_resolution_clock::now();
  8135. auto elapsed =
  8136. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8137. .count();
  8138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8139. EXPECT_EQ(StatusCode::OK_200, res->status);
  8140. EXPECT_EQ("Hello World!", res->body);
  8141. EXPECT_LE(elapsed, 500);
  8142. }
  8143. }
  8144. TEST(ZstdDecompressor, ChunkedDecompression) {
  8145. std::string data;
  8146. for (size_t i = 0; i < 32 * 1024; ++i) {
  8147. data.push_back(static_cast<char>('a' + i % 26));
  8148. }
  8149. std::string compressed_data;
  8150. {
  8151. httplib::detail::zstd_compressor compressor;
  8152. bool result = compressor.compress(
  8153. data.data(), data.size(),
  8154. /*last=*/true,
  8155. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8156. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8157. compressed_data_size);
  8158. return true;
  8159. });
  8160. ASSERT_TRUE(result);
  8161. }
  8162. std::string decompressed_data;
  8163. {
  8164. httplib::detail::zstd_decompressor decompressor;
  8165. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8166. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8167. size_t chunk_size = 130;
  8168. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8169. chunk_begin += chunk_size) {
  8170. size_t current_chunk_size =
  8171. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8172. bool result = decompressor.decompress(
  8173. compressed_data.data() + chunk_begin, current_chunk_size,
  8174. [&](const char *decompressed_data_chunk,
  8175. size_t decompressed_data_chunk_size) {
  8176. decompressed_data.insert(decompressed_data.size(),
  8177. decompressed_data_chunk,
  8178. decompressed_data_chunk_size);
  8179. return true;
  8180. });
  8181. ASSERT_TRUE(result);
  8182. }
  8183. }
  8184. ASSERT_EQ(data, decompressed_data);
  8185. }
  8186. TEST(ZstdDecompressor, Decompress) {
  8187. std::string original_text = "Compressed with ZSTD";
  8188. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8189. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8190. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8191. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8192. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8193. std::string decompressed_data;
  8194. {
  8195. httplib::detail::zstd_decompressor decompressor;
  8196. bool result = decompressor.decompress(
  8197. compressed_data.data(), compressed_data.size(),
  8198. [&](const char *decompressed_data_chunk,
  8199. size_t decompressed_data_chunk_size) {
  8200. decompressed_data.insert(decompressed_data.size(),
  8201. decompressed_data_chunk,
  8202. decompressed_data_chunk_size);
  8203. return true;
  8204. });
  8205. ASSERT_TRUE(result);
  8206. }
  8207. ASSERT_EQ(original_text, decompressed_data);
  8208. }
  8209. #endif
  8210. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8211. // separate chunks so that the server sees each part in its own read(). Used to
  8212. // place a read boundary at a specific offset of a request body.
  8213. static bool send_request_in_parts(time_t read_timeout_sec,
  8214. const std::vector<std::string> &parts,
  8215. std::string *resp = nullptr,
  8216. int port = PORT) {
  8217. auto error = Error::Success;
  8218. auto client_sock = detail::create_client_socket(
  8219. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8220. /*connection_timeout_sec=*/5, 0,
  8221. /*read_timeout_sec=*/5, 0,
  8222. /*write_timeout_sec=*/5, 0, std::string(), error);
  8223. if (client_sock == INVALID_SOCKET) { return false; }
  8224. auto ret = detail::process_client_socket(
  8225. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8226. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8227. for (size_t i = 0; i < parts.size(); i++) {
  8228. const auto &part = parts[i];
  8229. if (part.size() !=
  8230. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8231. return false;
  8232. }
  8233. if (i + 1 < parts.size()) {
  8234. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8235. }
  8236. }
  8237. char buf[512];
  8238. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8239. while (line_reader.getline()) {
  8240. if (resp) { *resp += line_reader.ptr(); }
  8241. }
  8242. return true;
  8243. });
  8244. detail::close_socket(client_sock);
  8245. return ret;
  8246. }
  8247. // Sends a raw request to a server listening at HOST:PORT.
  8248. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8249. std::string *resp = nullptr, int port = PORT) {
  8250. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8251. }
  8252. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8253. Server svr;
  8254. std::string header_value;
  8255. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8256. header_value = req.get_header_value("foo");
  8257. res.set_content("ok", "text/plain");
  8258. });
  8259. thread t = thread([&] { svr.listen(HOST, PORT); });
  8260. auto se = detail::scope_exit([&] {
  8261. svr.stop();
  8262. t.join();
  8263. ASSERT_FALSE(svr.is_running());
  8264. });
  8265. svr.wait_until_ready();
  8266. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8267. // like characters are not treated the same - use vertical tab and escape.
  8268. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8269. "foo: \t \v bar \x1B\t \r\n"
  8270. "Connection: close\r\n"
  8271. "\r\n";
  8272. std::string res;
  8273. ASSERT_TRUE(send_request(5, req, &res));
  8274. EXPECT_EQ(header_value, "");
  8275. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8276. }
  8277. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8278. Server svr;
  8279. std::string received;
  8280. svr.Get("/order", [&](const Request &req, Response &res) {
  8281. received = entries_to_string(req.headers);
  8282. res.set_content("ok", "text/plain");
  8283. });
  8284. auto port = svr.bind_to_any_port(HOST);
  8285. thread t = thread([&] { svr.listen_after_bind(); });
  8286. auto se = detail::scope_exit([&] {
  8287. svr.stop();
  8288. t.join();
  8289. ASSERT_FALSE(svr.is_running());
  8290. });
  8291. svr.wait_until_ready();
  8292. const std::string req = "GET /order HTTP/1.1\r\n"
  8293. "X-First: 1\r\n"
  8294. "X-Dup: a\r\n"
  8295. "X-Second: 2\r\n"
  8296. "X-Dup: b\r\n"
  8297. "Connection: close\r\n"
  8298. "\r\n";
  8299. std::string res;
  8300. ASSERT_TRUE(send_request(5, req, &res, port));
  8301. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8302. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8303. }
  8304. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8305. Server svr;
  8306. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8307. res.set_header("Set-Cookie", "first=1");
  8308. res.set_header("X-Between", "y");
  8309. res.set_header("Set-Cookie", "second=2");
  8310. res.set_content("ok", "text/plain");
  8311. });
  8312. auto port = svr.bind_to_any_port(HOST);
  8313. thread t = thread([&] { svr.listen_after_bind(); });
  8314. auto se = detail::scope_exit([&] {
  8315. svr.stop();
  8316. t.join();
  8317. ASSERT_FALSE(svr.is_running());
  8318. });
  8319. svr.wait_until_ready();
  8320. Client cli(HOST, port);
  8321. auto res = cli.Get("/cookies");
  8322. ASSERT_TRUE(res);
  8323. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8324. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8325. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8326. }
  8327. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8328. Server svr;
  8329. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8330. auto i = new int(0);
  8331. res.set_header("Trailer", "X-Safe, X-Reflected");
  8332. res.set_chunked_content_provider(
  8333. "text/plain",
  8334. [i](size_t /*offset*/, DataSink &sink) {
  8335. if (*i == 0) {
  8336. sink.os << "body";
  8337. } else {
  8338. Headers trailer;
  8339. // A valid trailer that must survive.
  8340. trailer.emplace("X-Safe", "safe");
  8341. // Attacker-controlled value carrying CR/LF (response splitting).
  8342. trailer.emplace("X-Reflected",
  8343. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8344. // Attacker-controlled name carrying CR/LF.
  8345. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8346. sink.done_with_trailer(trailer);
  8347. }
  8348. (*i)++;
  8349. return true;
  8350. },
  8351. [i](bool /*success*/) { delete i; });
  8352. });
  8353. thread t = thread([&] { svr.listen(HOST, PORT); });
  8354. auto se = detail::scope_exit([&] {
  8355. svr.stop();
  8356. t.join();
  8357. ASSERT_FALSE(svr.is_running());
  8358. });
  8359. svr.wait_until_ready();
  8360. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8361. "Host: " + HOST +
  8362. "\r\n"
  8363. "Connection: close\r\n"
  8364. "\r\n";
  8365. std::string res;
  8366. ASSERT_TRUE(send_request(5, req, &res));
  8367. // The injected fields must not appear anywhere in the raw response.
  8368. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8369. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8370. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8371. // Invalid trailers are dropped entirely, matching set_header().
  8372. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8373. // The valid trailer still passes through.
  8374. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8375. }
  8376. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8377. Server svr;
  8378. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8379. // res.headers is a public field an application can populate directly,
  8380. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8381. // A valid header that must survive.
  8382. res.headers.emplace("X-Safe", "safe");
  8383. // Attacker-controlled value carrying CR/LF (response splitting).
  8384. res.headers.emplace("X-Reflected",
  8385. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8386. // Attacker-controlled name carrying CR/LF.
  8387. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8388. res.set_content("body", "text/plain");
  8389. });
  8390. thread t = thread([&] { svr.listen(HOST, PORT); });
  8391. auto se = detail::scope_exit([&] {
  8392. svr.stop();
  8393. t.join();
  8394. ASSERT_FALSE(svr.is_running());
  8395. });
  8396. svr.wait_until_ready();
  8397. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8398. "Host: " + HOST +
  8399. "\r\n"
  8400. "Connection: close\r\n"
  8401. "\r\n";
  8402. std::string res;
  8403. ASSERT_TRUE(send_request(5, req, &res));
  8404. // The injected fields must not appear anywhere in the raw response.
  8405. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8406. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8407. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8408. // Invalid headers are dropped entirely, matching set_header().
  8409. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8410. // The valid header still passes through.
  8411. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8412. }
  8413. // Forward declaration: in split builds split.py strips `inline` and moves the
  8414. // definition into httplib.cc, so detail::write_request_line is not visible from
  8415. // the public httplib.h. Re-declaring it here lets the tests link against the
  8416. // symbol in both header-only and split builds.
  8417. namespace httplib {
  8418. namespace detail {
  8419. ssize_t write_request_line(Stream &strm, const std::string &method,
  8420. const std::string &path);
  8421. } // namespace detail
  8422. } // namespace httplib
  8423. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  8424. // A well-formed target is written verbatim.
  8425. {
  8426. detail::BufferStream strm;
  8427. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8428. EXPECT_GT(n, 0);
  8429. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8430. }
  8431. // A target carrying CR/LF must be rejected before anything reaches the wire,
  8432. // otherwise it splits the request line and injects a header or a whole
  8433. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  8434. // when path encoding is disabled.
  8435. const std::string evil_targets[] = {
  8436. "/a\r\nInjected: pwned",
  8437. "/a\rInjected",
  8438. "/a\nInjected",
  8439. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8440. };
  8441. for (const auto &evil : evil_targets) {
  8442. detail::BufferStream strm;
  8443. auto n = detail::write_request_line(strm, "GET", evil);
  8444. EXPECT_LT(n, 0);
  8445. EXPECT_TRUE(strm.get_buffer().empty());
  8446. }
  8447. }
  8448. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8449. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  8450. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  8451. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  8452. // client must fail cleanly with Error::Write instead of putting a
  8453. // request-line-less, header-injecting request on the wire.
  8454. Server svr;
  8455. svr.Get("/a", [](const Request &, Response &res) {
  8456. res.set_content("ok", "text/plain");
  8457. });
  8458. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8459. auto se = detail::scope_exit([&] {
  8460. svr.stop();
  8461. thread.join();
  8462. ASSERT_FALSE(svr.is_running());
  8463. });
  8464. svr.wait_until_ready();
  8465. {
  8466. Client cli(HOST, PORT);
  8467. cli.set_path_encode(false);
  8468. // The request is rejected before anything is written, so the connection
  8469. // stays silent and the subsequent response read would otherwise block for
  8470. // the full default read timeout. Shorten it -- the assertion is on the
  8471. // error, not the timeout.
  8472. cli.set_read_timeout(1, 0);
  8473. auto res = cli.Get("/a\r\nInjected: pwned");
  8474. EXPECT_FALSE(res);
  8475. EXPECT_EQ(Error::Write, res.error());
  8476. }
  8477. }
  8478. // Sends a raw request and verifies that there isn't a crash or exception.
  8479. static void test_raw_request(const std::string &req,
  8480. std::string *out = nullptr) {
  8481. Server svr;
  8482. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8483. res.set_content("ok", "text/plain");
  8484. });
  8485. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8486. res.set_content("ok", "text/plain");
  8487. });
  8488. svr.Get("/header_field_value_check",
  8489. [&](const Request & /*req*/, Response &res) {
  8490. res.set_content("ok", "text/plain");
  8491. });
  8492. svr.CustomRoute("PROPFIND", "/dav",
  8493. [&](const Request & /*req*/, Response &res) {
  8494. res.status = StatusCode::MultiStatus_207;
  8495. });
  8496. // Server read timeout must be longer than the client read timeout for the
  8497. // bug to reproduce, probably to force the server to process a request
  8498. // without a trailing blank line.
  8499. const time_t client_read_timeout_sec = 1;
  8500. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8501. bool listen_thread_ok = false;
  8502. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8503. auto se = detail::scope_exit([&] {
  8504. svr.stop();
  8505. t.join();
  8506. ASSERT_FALSE(svr.is_running());
  8507. EXPECT_TRUE(listen_thread_ok);
  8508. });
  8509. svr.wait_until_ready();
  8510. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8511. }
  8512. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8513. // A certain header line causes an exception if the header property is parsed
  8514. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8515. test_raw_request(
  8516. "GET /hi HTTP/1.1\r\n"
  8517. " : "
  8518. " "
  8519. " ");
  8520. }
  8521. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8522. // A certain header line causes an exception if the header property *name* is
  8523. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8524. // greedy matcher and requires backtracking when there are a lot of ":"
  8525. // characters.
  8526. // This occurs with libc++ but not libstdc++.
  8527. test_raw_request(
  8528. "GET /hi HTTP/1.1\r\n"
  8529. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8530. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8531. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8532. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8533. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8534. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8535. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8536. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8537. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8538. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8539. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8540. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8541. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8542. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8543. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8544. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8545. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8546. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8547. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8548. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8549. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8550. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8551. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8552. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8553. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8554. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8555. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8556. "&&&%%%");
  8557. }
  8558. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8559. // Make sure this doesn't crash the server.
  8560. // In a previous version of the header line regex, the "\r" rendered the line
  8561. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8562. // a new position where the leading white space ended and the field value
  8563. // began.
  8564. // The crash occurs with libc++ but not libstdc++.
  8565. test_raw_request("GET /hi HTTP/1.1\r\n"
  8566. "a:" +
  8567. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8568. "\r\n"
  8569. "\r\n");
  8570. }
  8571. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8572. std::string out;
  8573. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8574. "Content-Type: text/plain\r\n"
  8575. "Transfer-Encoding: chunked\r\n"
  8576. "\r\n"
  8577. "nothex\r\n",
  8578. &out);
  8579. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8580. }
  8581. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8582. std::string out;
  8583. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8584. "Content-Type: text/plain\r\n"
  8585. "Transfer-Encoding: chunked\r\n"
  8586. "\r\n"
  8587. "3\r\n"
  8588. "xyz\r\n"
  8589. "NaN\r\n",
  8590. &out);
  8591. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8592. }
  8593. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8594. std::string out;
  8595. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8596. "Content-Type: text/plain\r\n"
  8597. "Transfer-Encoding: chunked\r\n"
  8598. "\r\n"
  8599. // Length is too large for 64 bits.
  8600. "1ffffffffffffffff\r\n"
  8601. "xyz\r\n",
  8602. &out);
  8603. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8604. }
  8605. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8606. test_raw_request("GET /hi HTTP/1.1\r\n"
  8607. "Content-Type: text/plain\r\n\r");
  8608. }
  8609. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8610. std::string out;
  8611. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8612. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8613. }
  8614. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8615. Server svr;
  8616. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8617. EXPECT_TRUE(!req.remote_addr.empty());
  8618. });
  8619. thread t = thread([&] { svr.listen(HOST, PORT); });
  8620. auto se = detail::scope_exit([&] {
  8621. svr.stop();
  8622. t.join();
  8623. ASSERT_FALSE(svr.is_running());
  8624. });
  8625. svr.wait_until_ready();
  8626. // Send an invalid request line to trigger Bad Request
  8627. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8628. std::string out;
  8629. ASSERT_TRUE(send_request(5, bad_req, &out));
  8630. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8631. }
  8632. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8633. // answered right away rather than blocking on a read that waits for EOF.
  8634. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8635. std::string out;
  8636. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8637. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8638. }
  8639. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8640. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8641. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8642. for (const auto *method : methods) {
  8643. Server svr;
  8644. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8645. EXPECT_FALSE(svr.is_valid()) << method;
  8646. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8647. }
  8648. }
  8649. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8650. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8651. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8652. for (const auto *method : methods) {
  8653. Server svr;
  8654. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8655. EXPECT_FALSE(svr.is_valid()) << method;
  8656. }
  8657. }
  8658. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8659. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8660. "COPY", "MOVE", "LOCK",
  8661. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8662. Server svr;
  8663. for (const auto *method : methods) {
  8664. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8665. }
  8666. EXPECT_TRUE(svr.is_valid());
  8667. }
  8668. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8669. Server svr;
  8670. svr.CustomRoute("POST", "/x",
  8671. [](const Request &, Response &, const ContentReader &) {});
  8672. EXPECT_FALSE(svr.is_valid());
  8673. }
  8674. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8675. Server svr;
  8676. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8677. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8678. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8679. EXPECT_FALSE(svr.is_valid());
  8680. }
  8681. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8682. Server svr;
  8683. auto captured = Error::Success;
  8684. svr.set_error_logger(
  8685. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8686. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8687. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8688. }
  8689. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8690. std::string out;
  8691. std::string request(
  8692. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8693. test_raw_request(request, &out);
  8694. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8695. }
  8696. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8697. std::string out;
  8698. std::string request(
  8699. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8700. test_raw_request(request, &out);
  8701. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8702. }
  8703. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8704. std::string out;
  8705. std::string request(
  8706. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8707. test_raw_request(request, &out);
  8708. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8709. }
  8710. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8711. std::string out;
  8712. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8713. "Test: \r\n\r\n",
  8714. &out);
  8715. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8716. }
  8717. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8718. Server svr;
  8719. std::string x_custom;
  8720. std::string cookie;
  8721. std::string xff;
  8722. std::string x_unicode;
  8723. std::string x_iis;
  8724. svr.Get("/check", [&](const Request &req, Response &res) {
  8725. x_custom = req.get_header_value("X-Custom");
  8726. cookie = req.get_header_value("Cookie");
  8727. xff = req.get_header_value("X-Forwarded-For");
  8728. x_unicode = req.get_header_value("X-Unicode");
  8729. x_iis = req.get_header_value("X-IIS");
  8730. res.set_content("ok", "text/plain");
  8731. });
  8732. thread t = thread([&] { svr.listen(HOST, PORT); });
  8733. auto se = detail::scope_exit([&] {
  8734. svr.stop();
  8735. t.join();
  8736. ASSERT_FALSE(svr.is_running());
  8737. });
  8738. svr.wait_until_ready();
  8739. const std::string req = "GET /check HTTP/1.1\r\n"
  8740. "Host: localhost\r\n"
  8741. "X-Custom: a%0D%0AInjected: b\r\n"
  8742. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8743. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8744. "X-Unicode: %E3%81%82\r\n"
  8745. "X-IIS: %u00E9\r\n"
  8746. "Connection: close\r\n"
  8747. "\r\n";
  8748. std::string res;
  8749. ASSERT_TRUE(send_request(5, req, &res));
  8750. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8751. // Every value must be returned verbatim (wire form), with no decoding.
  8752. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8753. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8754. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8755. EXPECT_EQ("%E3%81%82", x_unicode);
  8756. EXPECT_EQ("%u00E9", x_iis);
  8757. }
  8758. // Applications that previously relied on automatic percent-decoding can
  8759. // reproduce the old behavior by explicitly calling decode_path_component()
  8760. // or, for RFC 3986 conformance, decode_uri_component().
  8761. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8762. Server svr;
  8763. std::string decoded;
  8764. svr.Get("/check", [&](const Request &req, Response &res) {
  8765. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8766. res.set_content("ok", "text/plain");
  8767. });
  8768. thread t = thread([&] { svr.listen(HOST, PORT); });
  8769. auto se = detail::scope_exit([&] {
  8770. svr.stop();
  8771. t.join();
  8772. ASSERT_FALSE(svr.is_running());
  8773. });
  8774. svr.wait_until_ready();
  8775. const std::string req = "GET /check HTTP/1.1\r\n"
  8776. "Host: localhost\r\n"
  8777. "X-Custom: hello%20world\r\n"
  8778. "Connection: close\r\n"
  8779. "\r\n";
  8780. std::string res;
  8781. ASSERT_TRUE(send_request(5, req, &res));
  8782. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8783. EXPECT_EQ("hello world", decoded);
  8784. }
  8785. // Regression test for #2033. Browsers send Referer values that include
  8786. // percent-encoded characters such as %0A inside the URL. Decoding the
  8787. // header value would either trip the post-decode CR/LF/NUL guard (the
  8788. // original bug, returning 400) or, after that guard was relaxed, silently
  8789. // store a literal LF — both unacceptable. The wire form must round-trip.
  8790. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8791. Server svr;
  8792. std::string referer;
  8793. svr.Get("/check", [&](const Request &req, Response &res) {
  8794. referer = req.get_header_value("Referer");
  8795. res.set_content("ok", "text/plain");
  8796. });
  8797. thread t = thread([&] { svr.listen(HOST, PORT); });
  8798. auto se = detail::scope_exit([&] {
  8799. svr.stop();
  8800. t.join();
  8801. ASSERT_FALSE(svr.is_running());
  8802. });
  8803. svr.wait_until_ready();
  8804. const std::string req = "GET /check HTTP/1.1\r\n"
  8805. "Host: localhost\r\n"
  8806. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8807. "Connection: close\r\n"
  8808. "\r\n";
  8809. std::string res;
  8810. ASSERT_TRUE(send_request(5, req, &res));
  8811. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8812. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8813. }
  8814. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8815. Server svr;
  8816. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8817. res.set_header("Cache-Control", "no-cache");
  8818. res.set_chunked_content_provider(
  8819. "text/event-stream", [](size_t offset, DataSink &sink) {
  8820. std::string s = "data:";
  8821. s += std::to_string(offset);
  8822. s += "\n\n";
  8823. auto ret = sink.write(s.data(), s.size());
  8824. EXPECT_TRUE(ret);
  8825. std::this_thread::sleep_for(std::chrono::seconds(1));
  8826. return true;
  8827. });
  8828. });
  8829. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8830. svr.wait_until_ready();
  8831. Client client(HOST, PORT);
  8832. const Headers headers = {{"Accept", "text/event-stream"}};
  8833. auto get_thread = std::thread([&client, &headers]() {
  8834. auto res = client.Get(
  8835. "/events", headers,
  8836. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8837. });
  8838. auto se = detail::scope_exit([&] {
  8839. svr.stop();
  8840. get_thread.join();
  8841. listen_thread.join();
  8842. ASSERT_FALSE(svr.is_running());
  8843. });
  8844. // Give GET time to get a few messages.
  8845. std::this_thread::sleep_for(std::chrono::seconds(2));
  8846. }
  8847. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8848. httplib::Server svr;
  8849. svr.Post("/hi",
  8850. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8851. res.status = StatusCode::OK_200;
  8852. });
  8853. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8854. svr.wait_until_ready();
  8855. Client cli(HOST, PORT);
  8856. auto res = cli.Post("/hi", "data", "text/plain");
  8857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8858. EXPECT_EQ(StatusCode::OK_200, res->status);
  8859. svr.stop();
  8860. thread.join();
  8861. ASSERT_FALSE(svr.is_running());
  8862. res = cli.Post("/hi", "data", "text/plain");
  8863. ASSERT_FALSE(res);
  8864. }
  8865. TEST(ServerStopTest, ListenFailure) {
  8866. Server svr;
  8867. auto t = thread([&]() {
  8868. auto ret = svr.listen("????", PORT);
  8869. EXPECT_FALSE(ret);
  8870. });
  8871. svr.wait_until_ready();
  8872. svr.stop();
  8873. t.join();
  8874. }
  8875. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8876. TEST(ServerStopTest, Decommision) {
  8877. Server svr;
  8878. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8879. for (int i = 0; i < 4; i++) {
  8880. auto is_even = !(i % 2);
  8881. std::thread t{[&] {
  8882. try {
  8883. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8884. if (is_even) {
  8885. throw std::runtime_error("Some thing that happens to go wrong.");
  8886. }
  8887. svr.listen(HOST, PORT);
  8888. } catch (...) { svr.decommission(); }
  8889. }};
  8890. svr.wait_until_ready();
  8891. // Server is up
  8892. {
  8893. Client cli(HOST, PORT);
  8894. auto res = cli.Get("/hi");
  8895. if (is_even) {
  8896. EXPECT_FALSE(res);
  8897. } else {
  8898. EXPECT_TRUE(res);
  8899. EXPECT_EQ("hi...", res->body);
  8900. }
  8901. }
  8902. svr.stop();
  8903. t.join();
  8904. // Server is down...
  8905. {
  8906. Client cli(HOST, PORT);
  8907. auto res = cli.Get("/hi");
  8908. EXPECT_FALSE(res);
  8909. }
  8910. }
  8911. }
  8912. #endif
  8913. // Helper function for string body upload progress tests
  8914. template <typename SetupHandler, typename ClientCall>
  8915. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  8916. ClientCall &&client_call,
  8917. const string &body) {
  8918. Server svr;
  8919. setup_handler(svr);
  8920. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8921. auto se = detail::scope_exit([&] {
  8922. svr.stop();
  8923. t.join();
  8924. });
  8925. svr.wait_until_ready();
  8926. Client cli(HOST, PORT);
  8927. vector<uint64_t> progress_values;
  8928. bool progress_called = false;
  8929. auto res =
  8930. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8931. progress_values.push_back(current);
  8932. progress_called = true;
  8933. return true;
  8934. });
  8935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8936. EXPECT_EQ(200, res->status);
  8937. EXPECT_TRUE(progress_called);
  8938. }
  8939. TEST(UploadProgressTest, PostStringBodyBasic) {
  8940. TestStringBodyUploadProgress(
  8941. [](Server &svr) {
  8942. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8943. res.set_content("received", "text/plain");
  8944. });
  8945. },
  8946. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8947. return cli.Post("/test", body, "text/plain", progress_callback);
  8948. },
  8949. "test data for upload progress");
  8950. }
  8951. TEST(UploadProgressTest, PutStringBodyBasic) {
  8952. TestStringBodyUploadProgress(
  8953. [](Server &svr) {
  8954. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  8955. res.set_content("put received", "text/plain");
  8956. });
  8957. },
  8958. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8959. return cli.Put("/test", body, "text/plain", progress_callback);
  8960. },
  8961. "put test data for upload progress");
  8962. }
  8963. TEST(UploadProgressTest, PatchStringBodyBasic) {
  8964. TestStringBodyUploadProgress(
  8965. [](Server &svr) {
  8966. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  8967. res.set_content("patch received", "text/plain");
  8968. });
  8969. },
  8970. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8971. return cli.Patch("/test", body, "text/plain", progress_callback);
  8972. },
  8973. "patch test data for upload progress");
  8974. }
  8975. // Helper function for content provider upload progress tests
  8976. template <typename SetupHandler, typename ClientCall>
  8977. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  8978. ClientCall &&client_call) {
  8979. Server svr;
  8980. setup_handler(svr);
  8981. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8982. auto se = detail::scope_exit([&] {
  8983. svr.stop();
  8984. t.join();
  8985. });
  8986. svr.wait_until_ready();
  8987. Client cli(HOST, PORT);
  8988. vector<uint64_t> progress_values;
  8989. auto res =
  8990. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8991. progress_values.push_back(current);
  8992. return true;
  8993. });
  8994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8995. EXPECT_EQ(200, res->status);
  8996. EXPECT_FALSE(progress_values.empty());
  8997. }
  8998. TEST(UploadProgressTest, PostContentProviderProgress) {
  8999. TestContentProviderUploadProgress(
  9000. [](Server &svr) {
  9001. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9002. res.set_content("provider received", "text/plain");
  9003. });
  9004. },
  9005. [](Client &cli, UploadProgress progress_callback) {
  9006. return cli.Post(
  9007. "/test", 10,
  9008. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9009. sink.os << "test data";
  9010. return true;
  9011. },
  9012. "text/plain", progress_callback);
  9013. });
  9014. }
  9015. // Helper function for multipart upload progress tests
  9016. template <typename SetupHandler, typename ClientCall>
  9017. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9018. ClientCall &&client_call,
  9019. const string &endpoint) {
  9020. Server svr;
  9021. setup_handler(svr);
  9022. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9023. auto se = detail::scope_exit([&] {
  9024. svr.stop();
  9025. t.join();
  9026. });
  9027. svr.wait_until_ready();
  9028. Client cli(HOST, PORT);
  9029. vector<uint64_t> progress_values;
  9030. UploadFormDataItems items = {
  9031. {"field1", "value1", "", ""},
  9032. {"field2", "longer value for progress tracking test", "", ""},
  9033. {"file1", "file content data for upload progress", "test.txt",
  9034. "text/plain"}};
  9035. auto res = client_call(cli, endpoint, items,
  9036. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9037. progress_values.push_back(current);
  9038. return true;
  9039. });
  9040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9041. EXPECT_EQ(200, res->status);
  9042. EXPECT_FALSE(progress_values.empty());
  9043. }
  9044. TEST(UploadProgressTest, PostMultipartProgress) {
  9045. TestMultipartUploadProgress(
  9046. [](Server &svr) {
  9047. svr.Post("/multipart", [](const Request &req, Response &res) {
  9048. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9049. res.set_content("multipart received", "text/plain");
  9050. });
  9051. },
  9052. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9053. UploadProgress progress_callback) {
  9054. return cli.Post(endpoint, items, progress_callback);
  9055. },
  9056. "/multipart");
  9057. }
  9058. // Helper function for basic download progress tests
  9059. template <typename SetupHandler, typename ClientCall>
  9060. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9061. ClientCall &&client_call, const string &endpoint,
  9062. size_t expected_content_size) {
  9063. Server svr;
  9064. setup_handler(svr);
  9065. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9066. auto se = detail::scope_exit([&] {
  9067. svr.stop();
  9068. t.join();
  9069. });
  9070. svr.wait_until_ready();
  9071. Client cli(HOST, PORT);
  9072. vector<uint64_t> progress_values;
  9073. auto res = client_call(cli, endpoint,
  9074. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9075. progress_values.push_back(current);
  9076. return true;
  9077. });
  9078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9079. EXPECT_EQ(200, res->status);
  9080. EXPECT_FALSE(progress_values.empty());
  9081. EXPECT_EQ(expected_content_size, res->body.size());
  9082. }
  9083. TEST(DownloadProgressTest, GetBasic) {
  9084. TestBasicDownloadProgress(
  9085. [](Server &svr) {
  9086. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9087. string content(1000, 'D');
  9088. res.set_content(content, "text/plain");
  9089. });
  9090. },
  9091. [](Client &cli, const string &endpoint,
  9092. DownloadProgress progress_callback) {
  9093. return cli.Get(endpoint, progress_callback);
  9094. },
  9095. "/download", 1000u);
  9096. }
  9097. // Helper function for content receiver download progress tests
  9098. template <typename SetupHandler, typename ClientCall>
  9099. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9100. ClientCall &&client_call,
  9101. const string &endpoint,
  9102. size_t expected_content_size) {
  9103. Server svr;
  9104. setup_handler(svr);
  9105. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9106. auto se = detail::scope_exit([&] {
  9107. svr.stop();
  9108. t.join();
  9109. });
  9110. svr.wait_until_ready();
  9111. Client cli(HOST, PORT);
  9112. vector<uint64_t> progress_values;
  9113. string received_body;
  9114. auto res = client_call(
  9115. cli, endpoint,
  9116. [&](const char *data, size_t data_length) -> bool {
  9117. received_body.append(data, data_length);
  9118. return true;
  9119. },
  9120. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9121. progress_values.push_back(current);
  9122. return true;
  9123. });
  9124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9125. EXPECT_EQ(200, res->status);
  9126. EXPECT_FALSE(progress_values.empty());
  9127. EXPECT_EQ(expected_content_size, received_body.size());
  9128. EXPECT_TRUE(res->body.empty());
  9129. }
  9130. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9131. TestContentReceiverDownloadProgress(
  9132. [](Server &svr) {
  9133. svr.Get("/download-receiver",
  9134. [](const Request & /*req*/, Response &res) {
  9135. string content(2000, 'R');
  9136. res.set_content(content, "text/plain");
  9137. });
  9138. },
  9139. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9140. DownloadProgress progress_callback) {
  9141. return cli.Get(endpoint, content_receiver, progress_callback);
  9142. },
  9143. "/download-receiver", 2000u);
  9144. }
  9145. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9146. // A provider reaching a pass with nothing to hand over - an empty buffer
  9147. // popped off a queue, say - must not be taken to mean the body is finished.
  9148. // It used to end the loop with the terminating chunk unwritten while the
  9149. // server still considered the response complete, so the peer waited for an
  9150. // end that never arrived.
  9151. Server svr;
  9152. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9153. auto step = std::make_shared<int>(0);
  9154. res.set_chunked_content_provider("text/plain",
  9155. [step](size_t /*offset*/, DataSink &sink) {
  9156. switch ((*step)++) {
  9157. case 0: sink.write("", 0); break;
  9158. case 1: sink.write("hello", 5); break;
  9159. default: sink.done(); break;
  9160. }
  9161. return true;
  9162. });
  9163. });
  9164. auto port = svr.bind_to_any_port(HOST);
  9165. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9166. auto listen_se = detail::scope_exit([&] {
  9167. svr.stop();
  9168. listen_thread.join();
  9169. ASSERT_FALSE(svr.is_running());
  9170. });
  9171. svr.wait_until_ready();
  9172. Client cli(HOST, port);
  9173. // Without the fix the body is never terminated, so bound the wait rather
  9174. // than letting the test hang on the default read timeout.
  9175. cli.set_read_timeout(5, 0);
  9176. auto res = cli.Get("/stream");
  9177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9178. EXPECT_EQ(StatusCode::OK_200, res->status);
  9179. EXPECT_EQ("hello", res->body);
  9180. }
  9181. TEST(StreamingTest, NoContentLengthStreaming) {
  9182. Server svr;
  9183. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9184. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9185. if (offset < 6) {
  9186. sink.os << (offset < 3 ? "a" : "b");
  9187. } else {
  9188. sink.done();
  9189. }
  9190. return true;
  9191. });
  9192. });
  9193. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9194. auto listen_se = detail::scope_exit([&] {
  9195. svr.stop();
  9196. listen_thread.join();
  9197. ASSERT_FALSE(svr.is_running());
  9198. });
  9199. svr.wait_until_ready();
  9200. Client client(HOST, PORT);
  9201. auto get_thread = std::thread([&client]() {
  9202. std::string s;
  9203. auto res =
  9204. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9205. s += std::string(data, len);
  9206. return true;
  9207. });
  9208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9209. EXPECT_EQ(StatusCode::OK_200, res->status);
  9210. EXPECT_EQ("aaabbb", s);
  9211. });
  9212. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9213. // Give GET time to get a few messages.
  9214. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9215. }
  9216. TEST(MountTest, Unmount) {
  9217. Server svr;
  9218. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9219. auto se = detail::scope_exit([&] {
  9220. svr.stop();
  9221. listen_thread.join();
  9222. ASSERT_FALSE(svr.is_running());
  9223. });
  9224. svr.wait_until_ready();
  9225. Client cli("localhost", PORT);
  9226. svr.set_mount_point("/mount2", "./www2");
  9227. auto res = cli.Get("/");
  9228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9229. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9230. res = cli.Get("/mount2/dir/test.html");
  9231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9232. EXPECT_EQ(StatusCode::OK_200, res->status);
  9233. svr.set_mount_point("/", "./www");
  9234. res = cli.Get("/dir/");
  9235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9236. EXPECT_EQ(StatusCode::OK_200, res->status);
  9237. svr.remove_mount_point("/");
  9238. res = cli.Get("/dir/");
  9239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9240. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9241. svr.remove_mount_point("/mount2");
  9242. res = cli.Get("/mount2/dir/test.html");
  9243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9245. }
  9246. TEST(MountTest, PathSegmentBoundary) {
  9247. Server svr;
  9248. svr.set_mount_point("/mount2", "./www2");
  9249. svr.set_mount_point("/", "./www");
  9250. auto port = svr.bind_to_any_port(HOST);
  9251. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9252. auto se = detail::scope_exit([&] {
  9253. svr.stop();
  9254. listen_thread.join();
  9255. ASSERT_FALSE(svr.is_running());
  9256. });
  9257. svr.wait_until_ready();
  9258. Client cli(HOST, port);
  9259. auto res = cli.Get("/mount2/dir/test.html");
  9260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9261. EXPECT_EQ(StatusCode::OK_200, res->status);
  9262. // "/mount2" must not match part-way through a path segment.
  9263. res = cli.Get("/mount2dir/test.html");
  9264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9265. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9266. // A mount point ending in '/' keeps matching every path below it.
  9267. res = cli.Get("/dir/test.html");
  9268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9269. EXPECT_EQ(StatusCode::OK_200, res->status);
  9270. }
  9271. TEST(MountTest, Redicect) {
  9272. Server svr;
  9273. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9274. auto se = detail::scope_exit([&] {
  9275. svr.stop();
  9276. listen_thread.join();
  9277. ASSERT_FALSE(svr.is_running());
  9278. });
  9279. svr.set_mount_point("/", "./www");
  9280. svr.wait_until_ready();
  9281. Client cli("localhost", PORT);
  9282. auto res = cli.Get("/dir/");
  9283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9284. EXPECT_EQ(StatusCode::OK_200, res->status);
  9285. res = cli.Get("/dir");
  9286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9287. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9288. res = cli.Get("/file");
  9289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9290. EXPECT_EQ(StatusCode::OK_200, res->status);
  9291. res = cli.Get("/file/");
  9292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9294. cli.set_follow_location(true);
  9295. res = cli.Get("/dir");
  9296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9297. EXPECT_EQ(StatusCode::OK_200, res->status);
  9298. }
  9299. TEST(MountTest, MultibytesPathName) {
  9300. Server svr;
  9301. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9302. auto se = detail::scope_exit([&] {
  9303. svr.stop();
  9304. listen_thread.join();
  9305. ASSERT_FALSE(svr.is_running());
  9306. });
  9307. svr.set_mount_point("/", "./www");
  9308. svr.wait_until_ready();
  9309. Client cli("localhost", PORT);
  9310. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9312. EXPECT_EQ(StatusCode::OK_200, res->status);
  9313. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9314. }
  9315. #ifdef _WIN32
  9316. // Issue #2435: mmap::open() must succeed even when another handle holds
  9317. // the file open for writing (e.g. an active log file).
  9318. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9319. const char *path = "mmap_concurrent_writer_test.txt";
  9320. const char *content = "hello";
  9321. {
  9322. std::ofstream f(path, std::ios::binary);
  9323. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9324. }
  9325. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9326. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9327. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9328. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9329. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9330. detail::mmap m(path);
  9331. ASSERT_TRUE(m.is_open());
  9332. EXPECT_EQ(strlen(content), m.size());
  9333. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9334. }
  9335. #endif
  9336. #ifndef _WIN32
  9337. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9338. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9339. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9340. TEST(MmapTest, FailedMappingIsNotOpen) {
  9341. const char *path = "./mmap_failed_mapping_test_dir";
  9342. ASSERT_EQ(0, ::mkdir(path, 0755));
  9343. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9344. detail::mmap m(path);
  9345. EXPECT_FALSE(m.is_open());
  9346. EXPECT_EQ(0U, m.size());
  9347. EXPECT_NE(static_cast<const void *>(m.data()),
  9348. static_cast<const void *>(MAP_FAILED));
  9349. }
  9350. #endif
  9351. TEST(KeepAliveTest, ReadTimeout) {
  9352. Server svr;
  9353. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9354. std::this_thread::sleep_for(std::chrono::seconds(2));
  9355. res.set_content("a", "text/plain");
  9356. });
  9357. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9358. res.set_content("b", "text/plain");
  9359. });
  9360. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9361. auto se = detail::scope_exit([&] {
  9362. svr.stop();
  9363. listen_thread.join();
  9364. ASSERT_FALSE(svr.is_running());
  9365. });
  9366. svr.wait_until_ready();
  9367. Client cli("localhost", PORT);
  9368. cli.set_keep_alive(true);
  9369. cli.set_read_timeout(std::chrono::seconds(1));
  9370. auto resa = cli.Get("/a");
  9371. ASSERT_FALSE(resa);
  9372. EXPECT_EQ(Error::Read, resa.error());
  9373. auto resb = cli.Get("/b");
  9374. ASSERT_TRUE(resb);
  9375. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9376. EXPECT_EQ("b", resb->body);
  9377. }
  9378. TEST(KeepAliveTest, MaxCount) {
  9379. size_t keep_alive_max_count = 3;
  9380. Server svr;
  9381. svr.set_keep_alive_max_count(keep_alive_max_count);
  9382. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9383. res.set_content("Hello World!", "text/plain");
  9384. });
  9385. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9386. auto se = detail::scope_exit([&] {
  9387. svr.stop();
  9388. listen_thread.join();
  9389. ASSERT_FALSE(svr.is_running());
  9390. });
  9391. svr.wait_until_ready();
  9392. Client cli(HOST, PORT);
  9393. cli.set_keep_alive(true);
  9394. for (size_t i = 0; i < 5; i++) {
  9395. auto result = cli.Get("/hi");
  9396. ASSERT_TRUE(result);
  9397. EXPECT_EQ(StatusCode::OK_200, result->status);
  9398. if (i == keep_alive_max_count - 1) {
  9399. EXPECT_EQ("close", result->get_header_value("Connection"));
  9400. } else {
  9401. EXPECT_FALSE(result->has_header("Connection"));
  9402. }
  9403. }
  9404. }
  9405. TEST(KeepAliveTest, Issue1041) {
  9406. Server svr;
  9407. svr.set_keep_alive_timeout(3);
  9408. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9409. res.set_content("Hello World!", "text/plain");
  9410. });
  9411. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9412. auto se = detail::scope_exit([&] {
  9413. svr.stop();
  9414. listen_thread.join();
  9415. ASSERT_FALSE(svr.is_running());
  9416. });
  9417. svr.wait_until_ready();
  9418. Client cli(HOST, PORT);
  9419. cli.set_keep_alive(true);
  9420. auto result = cli.Get("/hi");
  9421. ASSERT_TRUE(result);
  9422. EXPECT_EQ(StatusCode::OK_200, result->status);
  9423. std::this_thread::sleep_for(std::chrono::seconds(5));
  9424. result = cli.Get("/hi");
  9425. ASSERT_TRUE(result);
  9426. EXPECT_EQ(StatusCode::OK_200, result->status);
  9427. }
  9428. TEST(KeepAliveTest, Issue1959) {
  9429. Server svr;
  9430. svr.set_keep_alive_timeout(5);
  9431. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9432. res.set_content("a", "text/plain");
  9433. });
  9434. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9435. auto se = detail::scope_exit([&] {
  9436. if (!svr.is_running()) return;
  9437. svr.stop();
  9438. listen_thread.join();
  9439. ASSERT_FALSE(svr.is_running());
  9440. });
  9441. svr.wait_until_ready();
  9442. Client cli("localhost", PORT);
  9443. cli.set_keep_alive(true);
  9444. using namespace std::chrono;
  9445. auto start = steady_clock::now();
  9446. cli.Get("/a");
  9447. svr.stop();
  9448. listen_thread.join();
  9449. auto end = steady_clock::now();
  9450. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9451. EXPECT_LT(elapsed, 5000);
  9452. }
  9453. #ifdef CPPHTTPLIB_SSL_ENABLED
  9454. TEST(KeepAliveTest, SSLClientReconnection) {
  9455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9456. ASSERT_TRUE(svr.is_valid());
  9457. svr.set_keep_alive_timeout(1);
  9458. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9459. res.set_content("Hello World!", "text/plain");
  9460. });
  9461. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9462. auto se = detail::scope_exit([&] {
  9463. svr.stop();
  9464. listen_thread.join();
  9465. ASSERT_FALSE(svr.is_running());
  9466. });
  9467. svr.wait_until_ready();
  9468. SSLClient cli(HOST, PORT);
  9469. cli.enable_server_certificate_verification(false);
  9470. cli.set_keep_alive(true);
  9471. auto result = cli.Get("/hi");
  9472. ASSERT_TRUE(result);
  9473. EXPECT_EQ(StatusCode::OK_200, result->status);
  9474. result = cli.Get("/hi");
  9475. ASSERT_TRUE(result);
  9476. EXPECT_EQ(StatusCode::OK_200, result->status);
  9477. std::this_thread::sleep_for(std::chrono::seconds(2));
  9478. // Recoonect
  9479. result = cli.Get("/hi");
  9480. ASSERT_TRUE(result);
  9481. EXPECT_EQ(StatusCode::OK_200, result->status);
  9482. result = cli.Get("/hi");
  9483. ASSERT_TRUE(result);
  9484. EXPECT_EQ(StatusCode::OK_200, result->status);
  9485. }
  9486. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9487. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9488. ASSERT_TRUE(svr.is_valid());
  9489. svr.set_keep_alive_timeout(1);
  9490. std::string content = "reconnect";
  9491. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9492. res.set_content("Hello World!", "text/plain");
  9493. });
  9494. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9495. auto se = detail::scope_exit([&] {
  9496. svr.stop();
  9497. listen_thread.join();
  9498. ASSERT_FALSE(svr.is_running());
  9499. });
  9500. svr.wait_until_ready();
  9501. SSLClient cli(HOST, PORT);
  9502. cli.enable_server_certificate_verification(false);
  9503. cli.set_keep_alive(true);
  9504. auto result = cli.Post(
  9505. "/hi", content.size(),
  9506. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9507. sink.write(content.c_str(), content.size());
  9508. return true;
  9509. },
  9510. "text/plain");
  9511. ASSERT_TRUE(result);
  9512. EXPECT_EQ(200, result->status);
  9513. std::this_thread::sleep_for(std::chrono::seconds(2));
  9514. // Recoonect
  9515. result = cli.Post(
  9516. "/hi", content.size(),
  9517. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9518. sink.write(content.c_str(), content.size());
  9519. return true;
  9520. },
  9521. "text/plain");
  9522. ASSERT_TRUE(result);
  9523. EXPECT_EQ(200, result->status);
  9524. result = cli.Post(
  9525. "/hi", content.size(),
  9526. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9527. sink.write(content.c_str(), content.size());
  9528. return true;
  9529. },
  9530. "text/plain");
  9531. ASSERT_TRUE(result);
  9532. EXPECT_EQ(200, result->status);
  9533. }
  9534. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9535. using namespace httplib::tls;
  9536. {
  9537. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9538. ASSERT_TRUE(svr.is_valid());
  9539. svr.Get("/sni", [&](const Request &req, Response &res) {
  9540. std::string expected = req.sni();
  9541. EXPECT_EQ(expected, req.get_param_value("expected"));
  9542. res.set_content("ok", "text/plain");
  9543. });
  9544. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9545. auto se = detail::scope_exit([&] {
  9546. svr.stop();
  9547. listen_thread.join();
  9548. ASSERT_FALSE(svr.is_running());
  9549. });
  9550. svr.wait_until_ready();
  9551. {
  9552. SSLClient cli("localhost", PORT);
  9553. cli.enable_server_certificate_verification(false);
  9554. auto res = cli.Get("/sni?expected=localhost");
  9555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9556. }
  9557. {
  9558. SSLClient cli("::1", PORT);
  9559. cli.enable_server_certificate_verification(false);
  9560. auto res = cli.Get("/sni?expected=");
  9561. // NOTE: This may fail if the server is listening on IPv4 only
  9562. // (e.g., when localhost resolves to 127.0.0.1 only)
  9563. if (res) {
  9564. EXPECT_EQ(StatusCode::OK_200, res->status);
  9565. } else {
  9566. EXPECT_EQ(Error::Connection, res.error());
  9567. }
  9568. }
  9569. }
  9570. }
  9571. #endif
  9572. TEST(ClientProblemDetectionTest, ContentProvider) {
  9573. Server svr;
  9574. size_t content_length = 1024 * 1024;
  9575. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9576. res.set_content_provider(
  9577. content_length, "text/plain",
  9578. [&](size_t offset, size_t length, DataSink &sink) {
  9579. auto out_len = std::min(length, static_cast<size_t>(1024));
  9580. std::string out(out_len, '@');
  9581. sink.write(out.data(), out_len);
  9582. return offset < 4096;
  9583. },
  9584. [](bool success) { ASSERT_FALSE(success); });
  9585. });
  9586. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9587. res.set_content_provider(
  9588. 0, "text/plain",
  9589. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9590. EXPECT_TRUE(false);
  9591. return true;
  9592. },
  9593. [](bool success) { ASSERT_FALSE(success); });
  9594. });
  9595. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9596. auto se = detail::scope_exit([&] {
  9597. svr.stop();
  9598. listen_thread.join();
  9599. ASSERT_FALSE(svr.is_running());
  9600. });
  9601. svr.wait_until_ready();
  9602. Client cli("localhost", PORT);
  9603. {
  9604. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9605. size_t /*data_length*/) { return false; });
  9606. ASSERT_FALSE(res);
  9607. }
  9608. {
  9609. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9610. size_t /*data_length*/) { return false; });
  9611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9612. }
  9613. }
  9614. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9615. // A provider that reports success without writing anything and without
  9616. // calling done() used to be handed the same offset and length again on every
  9617. // pass, so it spun for as long as the peer stayed connected.
  9618. Server svr;
  9619. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9620. res.set_content("ok", "text/plain");
  9621. });
  9622. auto port = svr.bind_to_any_port(HOST);
  9623. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  9624. auto se = detail::scope_exit([&] {
  9625. svr.stop();
  9626. listen_thread.join();
  9627. ASSERT_FALSE(svr.is_running());
  9628. });
  9629. svr.wait_until_ready();
  9630. std::atomic<int> call_count{0};
  9631. Client cli(HOST, port);
  9632. auto res = cli.Post(
  9633. "/", 1024,
  9634. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9635. // Give up after enough passes to show the spin, so that losing the
  9636. // check below fails this test instead of hanging it.
  9637. return ++call_count < 100;
  9638. },
  9639. "text/plain");
  9640. ASSERT_FALSE(res);
  9641. EXPECT_EQ(Error::Write, res.error());
  9642. EXPECT_EQ(1, call_count.load());
  9643. }
  9644. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9645. // A writer only has to assign `write`. The other three used to be left as
  9646. // empty std::functions, so a provider calling one threw
  9647. // std::bad_function_call out of the thread running it and took the whole
  9648. // process down.
  9649. DataSink sink;
  9650. std::string written;
  9651. sink.write = [&](const char *data, size_t data_len) {
  9652. written.append(data, data_len);
  9653. return true;
  9654. };
  9655. EXPECT_TRUE(sink.is_writable());
  9656. sink.done();
  9657. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9658. EXPECT_TRUE(written.empty());
  9659. }
  9660. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9661. // A sink that cannot carry trailers still has to finish.
  9662. DataSink sink;
  9663. auto done_count = 0;
  9664. sink.done = [&]() { done_count++; };
  9665. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9666. EXPECT_EQ(1, done_count);
  9667. }
  9668. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9669. Server svr;
  9670. const std::string body(4096, 'x');
  9671. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9672. res.set_content_provider(body.size(), "text/plain",
  9673. [&](size_t offset, size_t length, DataSink &sink) {
  9674. sink.write(body.data() + offset, length);
  9675. sink.done();
  9676. return true;
  9677. });
  9678. });
  9679. auto port = svr.bind_to_any_port(HOST);
  9680. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9681. auto se = detail::scope_exit([&] {
  9682. svr.stop();
  9683. listen_thread.join();
  9684. ASSERT_FALSE(svr.is_running());
  9685. });
  9686. svr.wait_until_ready();
  9687. Client cli(HOST, port);
  9688. auto res = cli.Get("/");
  9689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9690. EXPECT_EQ(StatusCode::OK_200, res->status);
  9691. EXPECT_EQ(body, res->body);
  9692. }
  9693. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9694. Server svr;
  9695. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9696. res.set_content_provider(
  9697. 1024, "text/plain",
  9698. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9699. sink.write("hello", 5);
  9700. sink.done(); // short of the 1024 bytes the response promised
  9701. return true;
  9702. });
  9703. });
  9704. auto port = svr.bind_to_any_port(HOST);
  9705. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9706. auto se = detail::scope_exit([&] {
  9707. svr.stop();
  9708. listen_thread.join();
  9709. ASSERT_FALSE(svr.is_running());
  9710. });
  9711. svr.wait_until_ready();
  9712. Client cli(HOST, port);
  9713. cli.set_read_timeout(5, 0);
  9714. // The response is short of its Content-Length, so the client cannot read a
  9715. // complete body. What matters is that this returns at all: a no-op done()
  9716. // would leave the writer looping over a provider that never makes progress.
  9717. auto res = cli.Get("/");
  9718. EXPECT_FALSE(res);
  9719. }
  9720. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9721. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9722. // The compressed path builds the whole body before connecting, so this
  9723. // fails client-side and never reaches a server.
  9724. Client cli(HOST, PORT);
  9725. cli.set_compress(true);
  9726. auto res = cli.Post(
  9727. "/", 1024,
  9728. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9729. sink.write("hello", 5);
  9730. sink.done(); // short of the 1024 bytes the request announced
  9731. return true;
  9732. },
  9733. "text/plain");
  9734. ASSERT_FALSE(res);
  9735. EXPECT_EQ(Error::Write, res.error());
  9736. }
  9737. #endif
  9738. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9739. Server svr;
  9740. svr.set_error_handler([](Request const &, Response &res) -> void {
  9741. res.set_chunked_content_provider(
  9742. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9743. sink.os << "hello";
  9744. sink.os << "world";
  9745. sink.done();
  9746. return true;
  9747. });
  9748. });
  9749. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9750. auto se = detail::scope_exit([&] {
  9751. svr.stop();
  9752. listen_thread.join();
  9753. ASSERT_FALSE(svr.is_running());
  9754. });
  9755. svr.wait_until_ready();
  9756. Client cli("localhost", PORT);
  9757. auto res = cli.Get("/");
  9758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9759. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9760. EXPECT_EQ("helloworld", res->body);
  9761. }
  9762. TEST(LongPollingTest, ClientCloseDetection) {
  9763. Server svr;
  9764. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9765. res.set_chunked_content_provider(
  9766. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9767. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9768. sink.os << "hello";
  9769. auto count = 10;
  9770. while (count > 0 && sink.is_writable()) {
  9771. this_thread::sleep_for(chrono::milliseconds(10));
  9772. count--;
  9773. }
  9774. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9775. return true;
  9776. });
  9777. });
  9778. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9779. auto se = detail::scope_exit([&] {
  9780. svr.stop();
  9781. listen_thread.join();
  9782. ASSERT_FALSE(svr.is_running());
  9783. });
  9784. svr.wait_until_ready();
  9785. Client cli("localhost", PORT);
  9786. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9787. EXPECT_EQ("hello", string(data, data_length));
  9788. return false; // close the socket immediately.
  9789. });
  9790. ASSERT_FALSE(res);
  9791. }
  9792. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9793. Server svr;
  9794. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9795. res.set_chunked_content_provider(
  9796. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9797. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9798. sink.os << "hello";
  9799. EXPECT_TRUE(sink.os.good());
  9800. // Wait for the client to close the connection
  9801. auto count = 10;
  9802. while (count > 0 && sink.is_writable()) {
  9803. this_thread::sleep_for(chrono::milliseconds(10));
  9804. count--;
  9805. }
  9806. // After client disconnect, write repeatedly until the socket
  9807. // write actually fails (small writes may be absorbed by the
  9808. // kernel buffer)
  9809. std::string chunk(1024, 'x');
  9810. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9811. sink.os << chunk;
  9812. }
  9813. EXPECT_TRUE(sink.os.fail());
  9814. return true;
  9815. });
  9816. });
  9817. auto port = svr.bind_to_any_port("localhost");
  9818. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9819. auto se = detail::scope_exit([&] {
  9820. svr.stop();
  9821. listen_thread.join();
  9822. ASSERT_FALSE(svr.is_running());
  9823. });
  9824. svr.wait_until_ready();
  9825. Client cli("localhost", port);
  9826. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9827. EXPECT_EQ("hello", string(data, data_length));
  9828. return false; // close the socket immediately.
  9829. });
  9830. ASSERT_FALSE(res);
  9831. }
  9832. TEST(GetWithParametersTest, GetWithParameters) {
  9833. Server svr;
  9834. svr.Get("/", [&](const Request &req, Response &) {
  9835. EXPECT_EQ("world", req.get_param_value("hello"));
  9836. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9837. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9838. });
  9839. svr.Get("/params", [&](const Request &req, Response &) {
  9840. EXPECT_EQ("world", req.get_param_value("hello"));
  9841. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9842. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9843. });
  9844. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  9845. EXPECT_EQ("resource-id", req.matches[1]);
  9846. EXPECT_EQ("foo", req.get_param_value("param1"));
  9847. EXPECT_EQ("bar", req.get_param_value("param2"));
  9848. });
  9849. svr.Get("/users/:id", [&](const Request &req, Response &) {
  9850. EXPECT_EQ("user-id", req.path_params.at("id"));
  9851. EXPECT_EQ("foo", req.get_param_value("param1"));
  9852. EXPECT_EQ("bar", req.get_param_value("param2"));
  9853. });
  9854. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9855. auto se = detail::scope_exit([&] {
  9856. svr.stop();
  9857. listen_thread.join();
  9858. ASSERT_FALSE(svr.is_running());
  9859. });
  9860. svr.wait_until_ready();
  9861. {
  9862. Client cli(HOST, PORT);
  9863. Params params;
  9864. params.emplace("hello", "world");
  9865. params.emplace("hello2", "world2");
  9866. params.emplace("hello3", "world3");
  9867. auto res = cli.Get("/", params, Headers{});
  9868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9869. EXPECT_EQ(StatusCode::OK_200, res->status);
  9870. }
  9871. {
  9872. Client cli(HOST, PORT);
  9873. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9875. EXPECT_EQ(StatusCode::OK_200, res->status);
  9876. }
  9877. {
  9878. Client cli(HOST, PORT);
  9879. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9881. EXPECT_EQ(StatusCode::OK_200, res->status);
  9882. }
  9883. {
  9884. Client cli(HOST, PORT);
  9885. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9887. EXPECT_EQ(StatusCode::OK_200, res->status);
  9888. }
  9889. }
  9890. TEST(GetWithParametersTest, GetWithParameters2) {
  9891. Server svr;
  9892. svr.Get("/", [&](const Request &req, Response &res) {
  9893. auto text = req.get_param_value("hello");
  9894. res.set_content(text, "text/plain");
  9895. });
  9896. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9897. auto se = detail::scope_exit([&] {
  9898. svr.stop();
  9899. listen_thread.join();
  9900. ASSERT_FALSE(svr.is_running());
  9901. });
  9902. svr.wait_until_ready();
  9903. Client cli("localhost", PORT);
  9904. Params params;
  9905. params.emplace("hello", "world");
  9906. std::string body;
  9907. auto res = cli.Get("/", params, Headers{},
  9908. [&](const char *data, size_t data_length) {
  9909. body.append(data, data_length);
  9910. return true;
  9911. });
  9912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9913. EXPECT_EQ(StatusCode::OK_200, res->status);
  9914. EXPECT_EQ("world", body);
  9915. }
  9916. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9917. Server svr;
  9918. svr.Get("/search", [&](const Request &req, Response &res) {
  9919. auto q = req.get_param_value("q");
  9920. res.set_content(q, "text/plain");
  9921. });
  9922. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9923. auto se = detail::scope_exit([&] {
  9924. svr.stop();
  9925. listen_thread.join();
  9926. ASSERT_FALSE(svr.is_running());
  9927. });
  9928. svr.wait_until_ready();
  9929. Client cli("localhost", PORT);
  9930. // Verify that Get(path, params) works without requiring Headers argument
  9931. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9933. EXPECT_EQ(StatusCode::OK_200, res->status);
  9934. EXPECT_EQ("cpp-httplib", res->body);
  9935. }
  9936. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9937. auto host = "httpbingo.org";
  9938. auto path = std::string{"/range/32"};
  9939. #ifdef CPPHTTPLIB_SSL_ENABLED
  9940. SSLClient cli(host);
  9941. #else
  9942. Client cli(host);
  9943. #endif
  9944. cli.set_default_headers({make_range_header({{1, 10}})});
  9945. cli.set_connection_timeout(5);
  9946. {
  9947. auto res = cli.Get(path);
  9948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9949. EXPECT_EQ("bcdefghijk", res->body);
  9950. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9951. }
  9952. {
  9953. auto res = cli.Get(path);
  9954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9955. EXPECT_EQ("bcdefghijk", res->body);
  9956. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9957. }
  9958. }
  9959. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  9960. Server svr;
  9961. svr.set_default_headers({{"Hello", "World"}});
  9962. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9963. res.set_content("ok", "text/plain");
  9964. });
  9965. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9966. auto se = detail::scope_exit([&] {
  9967. svr.stop();
  9968. listen_thread.join();
  9969. ASSERT_FALSE(svr.is_running());
  9970. });
  9971. svr.wait_until_ready();
  9972. Client cli("localhost", PORT);
  9973. auto res = cli.Get("/");
  9974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9975. EXPECT_EQ(StatusCode::OK_200, res->status);
  9976. EXPECT_EQ("ok", res->body);
  9977. EXPECT_EQ("World", res->get_header_value("Hello"));
  9978. }
  9979. #ifdef CPPHTTPLIB_SSL_ENABLED
  9980. TEST(KeepAliveTest, ReadTimeoutSSL) {
  9981. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9982. ASSERT_TRUE(svr.is_valid());
  9983. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9984. std::this_thread::sleep_for(std::chrono::seconds(2));
  9985. res.set_content("a", "text/plain");
  9986. });
  9987. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9988. res.set_content("b", "text/plain");
  9989. });
  9990. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9991. auto se = detail::scope_exit([&] {
  9992. svr.stop();
  9993. listen_thread.join();
  9994. ASSERT_FALSE(svr.is_running());
  9995. });
  9996. svr.wait_until_ready();
  9997. SSLClient cli("localhost", PORT);
  9998. cli.enable_server_certificate_verification(false);
  9999. cli.set_keep_alive(true);
  10000. cli.set_read_timeout(std::chrono::seconds(1));
  10001. auto resa = cli.Get("/a");
  10002. ASSERT_TRUE(!resa);
  10003. EXPECT_EQ(Error::Read, resa.error());
  10004. auto resb = cli.Get("/b");
  10005. ASSERT_TRUE(resb);
  10006. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10007. EXPECT_EQ("b", resb->body);
  10008. }
  10009. #endif
  10010. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10011. protected:
  10012. ServerTestWithAI_PASSIVE()
  10013. : cli_(HOST, PORT)
  10014. #ifdef CPPHTTPLIB_SSL_ENABLED
  10015. ,
  10016. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10017. #endif
  10018. {
  10019. #ifdef CPPHTTPLIB_SSL_ENABLED
  10020. cli_.enable_server_certificate_verification(false);
  10021. #endif
  10022. }
  10023. virtual void SetUp() {
  10024. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10025. res.set_content("Hello World!", "text/plain");
  10026. });
  10027. t_ = thread(
  10028. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10029. svr_.wait_until_ready();
  10030. }
  10031. virtual void TearDown() {
  10032. svr_.stop();
  10033. t_.join();
  10034. }
  10035. #ifdef CPPHTTPLIB_SSL_ENABLED
  10036. SSLClient cli_;
  10037. SSLServer svr_;
  10038. #else
  10039. Client cli_;
  10040. Server svr_;
  10041. #endif
  10042. thread t_;
  10043. };
  10044. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10045. auto res = cli_.Get("/hi");
  10046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10047. EXPECT_EQ(StatusCode::OK_200, res->status);
  10048. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10049. EXPECT_EQ("Hello World!", res->body);
  10050. }
  10051. class ServerUpDownTest : public ::testing::Test {
  10052. protected:
  10053. ServerUpDownTest() : cli_(HOST, PORT) {}
  10054. virtual void SetUp() {
  10055. t_ = thread([&]() {
  10056. svr_.bind_to_any_port(HOST);
  10057. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10058. ASSERT_TRUE(svr_.listen_after_bind());
  10059. });
  10060. svr_.wait_until_ready();
  10061. }
  10062. virtual void TearDown() {
  10063. svr_.stop();
  10064. t_.join();
  10065. }
  10066. Client cli_;
  10067. Server svr_;
  10068. thread t_;
  10069. };
  10070. TEST_F(ServerUpDownTest, QuickStartStop) {
  10071. // Should not crash, especially when run with
  10072. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10073. }
  10074. class PayloadMaxLengthTest : public ::testing::Test {
  10075. protected:
  10076. PayloadMaxLengthTest()
  10077. : cli_(HOST, PORT)
  10078. #ifdef CPPHTTPLIB_SSL_ENABLED
  10079. ,
  10080. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10081. #endif
  10082. {
  10083. #ifdef CPPHTTPLIB_SSL_ENABLED
  10084. cli_.enable_server_certificate_verification(false);
  10085. #endif
  10086. }
  10087. virtual void SetUp() {
  10088. svr_.set_payload_max_length(8);
  10089. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10090. res.set_content("test", "text/plain");
  10091. });
  10092. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10093. svr_.wait_until_ready();
  10094. }
  10095. virtual void TearDown() {
  10096. svr_.stop();
  10097. t_.join();
  10098. }
  10099. #ifdef CPPHTTPLIB_SSL_ENABLED
  10100. SSLClient cli_;
  10101. SSLServer svr_;
  10102. #else
  10103. Client cli_;
  10104. Server svr_;
  10105. #endif
  10106. thread t_;
  10107. };
  10108. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10109. auto res = cli_.Post("/test", "123456789", "text/plain");
  10110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10111. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10112. res = cli_.Post("/test", "12345678", "text/plain");
  10113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10114. EXPECT_EQ(StatusCode::OK_200, res->status);
  10115. }
  10116. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10117. // Test chunked encoding with payload exceeding the 8-byte limit
  10118. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10119. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10121. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10122. }
  10123. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10124. // Test chunked encoding with payload within the 8-byte limit
  10125. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10126. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10128. EXPECT_EQ(StatusCode::OK_200, res->status);
  10129. }
  10130. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10131. // Test using send_request to send chunked data exceeding payload limit
  10132. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10133. "Host: " +
  10134. std::string(HOST) + ":" + std::to_string(PORT) +
  10135. "\r\n"
  10136. "Transfer-Encoding: chunked\r\n"
  10137. "Connection: close\r\n"
  10138. "\r\n"
  10139. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10140. "0123456789\r\n"
  10141. "0\r\n" // End chunk
  10142. "\r\n";
  10143. std::string response;
  10144. bool result = send_request(1, chunked_request, &response);
  10145. if (!result) {
  10146. // If send_request fails, it might be because the server closed the
  10147. // connection due to payload limit enforcement, which is acceptable
  10148. SUCCEED()
  10149. << "Server rejected oversized chunked request (connection closed)";
  10150. } else {
  10151. // If we got a response, check if it's an error response or connection was
  10152. // closed early Short response length indicates connection was closed due to
  10153. // payload limit
  10154. if (response.length() <= 10) {
  10155. SUCCEED() << "Server closed connection for oversized chunked request";
  10156. } else {
  10157. // Check for error status codes
  10158. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10159. response.find("Payload Too Large") != std::string::npos ||
  10160. response.find("400") != std::string::npos);
  10161. }
  10162. }
  10163. }
  10164. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10165. // Test request without Content-Length header exceeding payload limit
  10166. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10167. "Host: " +
  10168. std::string(HOST) + ":" +
  10169. std::to_string(PORT) +
  10170. "\r\n"
  10171. "Connection: close\r\n"
  10172. "\r\n";
  10173. // Add payload exceeding the 8-byte limit
  10174. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10175. request_without_content_length += large_payload;
  10176. std::string response;
  10177. bool result = send_request(1, request_without_content_length, &response);
  10178. if (!result) {
  10179. // If send_request fails, server likely closed connection due to payload
  10180. // limit
  10181. SUCCEED() << "Server rejected oversized request without Content-Length "
  10182. "(connection closed)";
  10183. } else {
  10184. // Check if server responded with error or closed connection early
  10185. if (response.length() <= 10) {
  10186. SUCCEED() << "Server closed connection for oversized request without "
  10187. "Content-Length";
  10188. } else {
  10189. // Check for error status codes
  10190. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10191. response.find("Payload Too Large") != std::string::npos ||
  10192. response.find("400") != std::string::npos);
  10193. }
  10194. }
  10195. }
  10196. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10197. // Test request without Content-Length header within payload limit
  10198. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10199. "Host: " +
  10200. std::string(HOST) + ":" +
  10201. std::to_string(PORT) +
  10202. "\r\n"
  10203. "Connection: close\r\n"
  10204. "\r\n";
  10205. // Add payload within the 8-byte limit
  10206. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10207. request_without_content_length += small_payload;
  10208. std::string response;
  10209. bool result = send_request(1, request_without_content_length, &response);
  10210. // For requests without Content-Length, the server may have different behavior
  10211. // The key is that it should not reject due to payload limit for small
  10212. // payloads
  10213. if (result) {
  10214. // Check for any HTTP response (success or error, but not connection closed)
  10215. if (response.length() > 10) {
  10216. SUCCEED()
  10217. << "Server processed request without Content-Length within limit";
  10218. } else {
  10219. // Short response might indicate connection closed, which is acceptable
  10220. SUCCEED() << "Server closed connection for request without "
  10221. "Content-Length (acceptable behavior)";
  10222. }
  10223. } else {
  10224. // Connection failure might be due to protocol requirements
  10225. SUCCEED() << "Connection issue with request without Content-Length "
  10226. "(environment-specific)";
  10227. }
  10228. }
  10229. class LargePayloadMaxLengthTest : public ::testing::Test {
  10230. protected:
  10231. LargePayloadMaxLengthTest()
  10232. : cli_(HOST, PORT)
  10233. #ifdef CPPHTTPLIB_SSL_ENABLED
  10234. ,
  10235. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10236. #endif
  10237. {
  10238. #ifdef CPPHTTPLIB_SSL_ENABLED
  10239. cli_.enable_server_certificate_verification(false);
  10240. #endif
  10241. }
  10242. virtual void SetUp() {
  10243. // Set 10MB payload limit
  10244. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10245. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10246. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10247. res.set_content("Large payload test", "text/plain");
  10248. });
  10249. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10250. svr_.wait_until_ready();
  10251. }
  10252. virtual void TearDown() {
  10253. svr_.stop();
  10254. t_.join();
  10255. }
  10256. #ifdef CPPHTTPLIB_SSL_ENABLED
  10257. SSLClient cli_;
  10258. SSLServer svr_;
  10259. #else
  10260. Client cli_;
  10261. Server svr_;
  10262. #endif
  10263. thread t_;
  10264. };
  10265. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10266. // Test chunked encoding with payload within 10MB limit
  10267. std::string medium_payload(5 * 1024 * 1024,
  10268. 'A'); // 5MB payload, within 10MB limit
  10269. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10271. EXPECT_EQ(StatusCode::OK_200, res->status);
  10272. }
  10273. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10274. // Test chunked encoding with payload exceeding 10MB limit
  10275. std::string large_payload(12 * 1024 * 1024,
  10276. 'B'); // 12MB payload, exceeds 10MB limit
  10277. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10278. // Server may either return 413 or close the connection
  10279. if (res) {
  10280. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10281. } else {
  10282. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10283. }
  10284. }
  10285. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10286. // Test request without Content-Length header within 10MB limit
  10287. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10288. "Host: " +
  10289. std::string(HOST) + ":" +
  10290. std::to_string(PORT) +
  10291. "\r\n"
  10292. "Connection: close\r\n"
  10293. "\r\n";
  10294. // Add 1MB payload (within 10MB limit)
  10295. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10296. request_without_content_length += medium_payload;
  10297. std::string response;
  10298. bool result = send_request(5, request_without_content_length, &response);
  10299. if (result) {
  10300. // Should get a proper HTTP response for payloads within limit
  10301. if (response.length() > 10) {
  10302. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10303. "10MB limit";
  10304. } else {
  10305. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10306. "Content-Length)";
  10307. }
  10308. } else {
  10309. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10310. }
  10311. }
  10312. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10313. // Test request without Content-Length header exceeding 10MB limit
  10314. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10315. "Host: " +
  10316. std::string(HOST) + ":" +
  10317. std::to_string(PORT) +
  10318. "\r\n"
  10319. "Connection: close\r\n"
  10320. "\r\n";
  10321. // Add 12MB payload (exceeds 10MB limit)
  10322. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10323. request_without_content_length += large_payload;
  10324. std::string response;
  10325. bool result = send_request(10, request_without_content_length, &response);
  10326. if (!result) {
  10327. // Server should close connection due to payload limit
  10328. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10329. "(connection closed)";
  10330. } else {
  10331. // Check for error response
  10332. if (response.length() <= 10) {
  10333. SUCCEED()
  10334. << "Server closed connection for 12MB request exceeding 10MB limit";
  10335. } else {
  10336. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10337. response.find("Payload Too Large") != std::string::npos ||
  10338. response.find("400") != std::string::npos);
  10339. }
  10340. }
  10341. }
  10342. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10343. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10344. // path.
  10345. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10346. Server svr;
  10347. const size_t LIMIT = 64 * 1024; // 64KB
  10348. svr.set_payload_max_length(LIMIT);
  10349. size_t total = 0;
  10350. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10351. const ContentReader &content_reader) {
  10352. content_reader([&](const char * /*data*/, size_t len) {
  10353. total += len;
  10354. return true;
  10355. });
  10356. res.status = 200;
  10357. res.set_content("stream_ok", "text/plain");
  10358. });
  10359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10360. auto se = detail::scope_exit([&] {
  10361. svr.stop();
  10362. thread.join();
  10363. ASSERT_FALSE(svr.is_running());
  10364. });
  10365. svr.wait_until_ready();
  10366. // Prepare 256KB raw data and gzip-compress it
  10367. std::string raw(256 * 1024, 'A');
  10368. std::string gz;
  10369. {
  10370. z_stream zs{};
  10371. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10372. Z_DEFAULT_STRATEGY);
  10373. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10374. zs.avail_in = static_cast<uInt>(raw.size());
  10375. char outbuf[4096];
  10376. int ret;
  10377. do {
  10378. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10379. zs.avail_out = sizeof(outbuf);
  10380. ret = deflate(&zs, Z_FINISH);
  10381. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10382. } while (ret != Z_STREAM_END);
  10383. deflateEnd(&zs);
  10384. }
  10385. Client cli(HOST, PORT);
  10386. cli.set_connection_timeout(std::chrono::seconds(5));
  10387. Headers headers = {{"Content-Encoding", "gzip"}};
  10388. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10389. "application/octet-stream");
  10390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10391. // Server must reject oversized decompressed payloads with 413.
  10392. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10393. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10394. EXPECT_LE(total, LIMIT);
  10395. }
  10396. #ifndef CPPHTTPLIB_SSL_ENABLED
  10397. // For a request with neither Content-Length nor Transfer-Encoding, the
  10398. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10399. // compressed wire bytes straight to the ContentReader without ever routing
  10400. // them through the decompressor, so payload_max_length_ only bounded the
  10401. // compressed size on the wire, not the decompressed size.
  10402. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10403. Server svr;
  10404. const size_t LIMIT = 64 * 1024; // 64KB
  10405. svr.set_payload_max_length(LIMIT);
  10406. size_t total = 0;
  10407. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10408. const ContentReader &content_reader) {
  10409. content_reader([&](const char * /*data*/, size_t len) {
  10410. total += len;
  10411. return true;
  10412. });
  10413. res.status = 200;
  10414. res.set_content("stream_ok", "text/plain");
  10415. });
  10416. auto port = svr.bind_to_any_port(HOST);
  10417. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10418. auto se = detail::scope_exit([&] {
  10419. svr.stop();
  10420. thread.join();
  10421. ASSERT_FALSE(svr.is_running());
  10422. });
  10423. svr.wait_until_ready();
  10424. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10425. // StreamingGzipDecompression test above.
  10426. std::string raw(256 * 1024, 'A');
  10427. std::string gz;
  10428. {
  10429. httplib::detail::gzip_compressor compressor;
  10430. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10431. [&](const char *chunk, size_t len) {
  10432. gz.append(chunk, len);
  10433. return true;
  10434. });
  10435. ASSERT_TRUE(result);
  10436. }
  10437. // Send the gzip body over raw TCP with neither Content-Length nor
  10438. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10439. // kicks in.
  10440. std::string req = "POST /stream HTTP/1.1\r\n"
  10441. "Host: " +
  10442. std::string(HOST) + ":" + std::to_string(port) +
  10443. "\r\n"
  10444. "Content-Encoding: gzip\r\n"
  10445. "Connection: close\r\n"
  10446. "\r\n" +
  10447. gz;
  10448. std::string response;
  10449. ASSERT_TRUE(send_request(5, req, &response, port));
  10450. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10451. EXPECT_LE(total, LIMIT);
  10452. }
  10453. #endif
  10454. #endif
  10455. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10456. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10457. // the payload must be passed through untouched instead of being rejected.
  10458. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10459. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10460. Server svr;
  10461. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10462. res.set_content(body, "image/jpeg");
  10463. res.set_header("Content-Encoding", "UTF-8");
  10464. });
  10465. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10466. res.set_content(body, "image/jpeg");
  10467. res.set_header("Content-Encoding", "identity");
  10468. });
  10469. svr.Post("/echo", [](const Request &req, Response &res) {
  10470. res.set_content(req.body, "image/jpeg");
  10471. });
  10472. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10473. auto se = detail::scope_exit([&] {
  10474. svr.stop();
  10475. t.join();
  10476. ASSERT_FALSE(svr.is_running());
  10477. });
  10478. svr.wait_until_ready();
  10479. Client cli(HOST, PORT);
  10480. {
  10481. auto res = cli.Get("/image");
  10482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10483. EXPECT_EQ(StatusCode::OK_200, res->status);
  10484. EXPECT_EQ(body, res->body);
  10485. }
  10486. {
  10487. auto res = cli.Get("/identity");
  10488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10489. EXPECT_EQ(StatusCode::OK_200, res->status);
  10490. EXPECT_EQ(body, res->body);
  10491. }
  10492. {
  10493. // The same applies to a request body reaching the server.
  10494. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10495. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10497. EXPECT_EQ(StatusCode::OK_200, res->status);
  10498. EXPECT_EQ(body, res->body);
  10499. }
  10500. }
  10501. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10502. // gzip-encoded response even when the build has no zlib support.
  10503. static const char GZIPPED_HELLO_WORLD[] = {
  10504. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10505. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10506. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10507. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10508. // A content coding is a whole token, not something the field value merely
  10509. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10510. // as "fibre" look like Brotli, and turned a multi-coding value like
  10511. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10512. // it was never meant to see.
  10513. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10514. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10515. Server svr;
  10516. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10517. res.set_content(body, "image/jpeg");
  10518. res.set_header("Content-Encoding", "fibre");
  10519. });
  10520. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10521. res.set_content(body, "image/jpeg");
  10522. res.set_header("Content-Encoding", "gzip, br");
  10523. });
  10524. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10525. res.set_content(body, "image/jpeg");
  10526. res.set_header("Content-Encoding", "x-zstd-ish");
  10527. });
  10528. auto port = svr.bind_to_any_port(HOST);
  10529. thread t = thread([&]() { svr.listen_after_bind(); });
  10530. auto se = detail::scope_exit([&] {
  10531. svr.stop();
  10532. t.join();
  10533. ASSERT_FALSE(svr.is_running());
  10534. });
  10535. svr.wait_until_ready();
  10536. Client cli(HOST, port);
  10537. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10538. auto res = cli.Get(path);
  10539. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10540. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10541. // Not a coding we recognize, so the payload comes back untouched
  10542. EXPECT_EQ(body, res->body) << path;
  10543. }
  10544. }
  10545. // A content coding cpp-httplib recognizes but was not built with must be
  10546. // reported as such. Handing the still-compressed payload back to the caller
  10547. // would silently corrupt it.
  10548. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10549. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10550. Server svr;
  10551. // "image/jpeg" keeps the server from applying a content coding of its own,
  10552. // so the hand-crafted Content-Encoding below survives.
  10553. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10554. res.set_content(gzipped, "image/jpeg");
  10555. res.set_header("Content-Encoding", "gzip");
  10556. });
  10557. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10558. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10559. res.set_content(gzipped, "image/jpeg");
  10560. res.set_header("Content-Encoding", "GZIP");
  10561. });
  10562. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10563. auto se = detail::scope_exit([&] {
  10564. svr.stop();
  10565. t.join();
  10566. ASSERT_FALSE(svr.is_running());
  10567. });
  10568. svr.wait_until_ready();
  10569. Client cli(HOST, PORT);
  10570. {
  10571. auto res = cli.Get("/gzipped");
  10572. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10574. EXPECT_EQ("Hello World!", res->body);
  10575. #else
  10576. ASSERT_FALSE(res);
  10577. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10578. #endif
  10579. }
  10580. {
  10581. // open_stream() must behave the same way.
  10582. auto handle = cli.open_stream("GET", "/gzipped");
  10583. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10584. ASSERT_TRUE(handle.is_valid());
  10585. std::string received;
  10586. char buf[256];
  10587. ssize_t n;
  10588. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10589. received.append(buf, static_cast<size_t>(n));
  10590. }
  10591. EXPECT_EQ("Hello World!", received);
  10592. #else
  10593. EXPECT_FALSE(handle.is_valid());
  10594. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10595. #endif
  10596. }
  10597. {
  10598. // A differently-cased coding must not be mistaken for an unknown one, or
  10599. // the body would be handed back still compressed.
  10600. auto res = cli.Get("/gzipped-uppercase");
  10601. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10603. EXPECT_EQ("Hello World!", res->body);
  10604. #else
  10605. ASSERT_FALSE(res);
  10606. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10607. #endif
  10608. }
  10609. }
  10610. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10611. // the same message as the comma-joined one, so both have to be read the same
  10612. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10613. // single gzip coding, and a body the sender says was encoded twice was handed
  10614. // back after one pass, still compressed but presented as decoded.
  10615. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10616. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10617. Server svr;
  10618. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10619. res.set_content(body, "image/jpeg");
  10620. res.headers.emplace("Content-Encoding", "gzip");
  10621. res.headers.emplace("Content-Encoding", "gzip");
  10622. });
  10623. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10624. res.set_content(body, "image/jpeg");
  10625. res.set_header("Content-Encoding", "gzip, gzip");
  10626. });
  10627. auto port = svr.bind_to_any_port(HOST);
  10628. thread t = thread([&]() { svr.listen_after_bind(); });
  10629. auto se = detail::scope_exit([&] {
  10630. svr.stop();
  10631. t.join();
  10632. ASSERT_FALSE(svr.is_running());
  10633. });
  10634. svr.wait_until_ready();
  10635. Client cli(HOST, port);
  10636. // Two codings is not something cpp-httplib decodes, so both representations
  10637. // take the pass-through path rather than one of them being gunzipped once.
  10638. for (const char *path : {"/split", "/joined"}) {
  10639. auto res = cli.Get(path);
  10640. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10641. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10642. EXPECT_EQ(body, res->body) << path;
  10643. }
  10644. }
  10645. // Regression test for DoS vulnerability: a malicious server sending a response
  10646. // without Content-Length header must not cause unbounded memory consumption on
  10647. // the client side. The client should stop reading after a reasonable limit,
  10648. // similar to the server-side set_payload_max_length protection.
  10649. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10650. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10651. #ifndef _WIN32
  10652. signal(SIGPIPE, SIG_IGN);
  10653. #endif
  10654. auto server_thread = std::thread([] {
  10655. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10656. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10657. default_socket_options(srv);
  10658. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10659. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10660. sockaddr_in addr{};
  10661. addr.sin_family = AF_INET;
  10662. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10663. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10664. int opt = 1;
  10665. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10666. #ifdef _WIN32
  10667. reinterpret_cast<const char *>(&opt),
  10668. #else
  10669. &opt,
  10670. #endif
  10671. sizeof(opt));
  10672. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10673. ::listen(srv, 1);
  10674. sockaddr_in cli_addr{};
  10675. socklen_t cli_len = sizeof(cli_addr);
  10676. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10677. if (cli != INVALID_SOCKET) {
  10678. char buf[4096];
  10679. ::recv(cli, buf, sizeof(buf), 0);
  10680. // Malicious response: no Content-Length, no chunked encoding
  10681. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10682. "Connection: close\r\n"
  10683. "\r\n";
  10684. ::send(cli,
  10685. #ifdef _WIN32
  10686. static_cast<const char *>(response_header.c_str()),
  10687. static_cast<int>(response_header.size()),
  10688. #else
  10689. response_header.c_str(), response_header.size(),
  10690. #endif
  10691. 0);
  10692. // Send 10MB of data
  10693. std::string chunk(64 * 1024, 'A');
  10694. size_t total_sent = 0;
  10695. while (total_sent < MALICIOUS_DATA_SIZE) {
  10696. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  10697. auto sent = ::send(cli,
  10698. #ifdef _WIN32
  10699. static_cast<const char *>(chunk.c_str()),
  10700. static_cast<int>(to_send),
  10701. #else
  10702. chunk.c_str(), to_send,
  10703. #endif
  10704. 0);
  10705. if (sent <= 0) break;
  10706. total_sent += static_cast<size_t>(sent);
  10707. }
  10708. detail::close_socket(cli);
  10709. }
  10710. detail::close_socket(srv);
  10711. });
  10712. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10713. size_t total_read = 0;
  10714. {
  10715. Client cli("127.0.0.1", PORT + 2);
  10716. cli.set_read_timeout(5, 0);
  10717. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10718. auto stream = cli.open_stream("GET", "/malicious");
  10719. ASSERT_TRUE(stream.is_valid());
  10720. char buffer[64 * 1024];
  10721. ssize_t n;
  10722. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10723. total_read += static_cast<size_t>(n);
  10724. }
  10725. } // StreamHandle and Client destroyed here, closing the socket
  10726. server_thread.join();
  10727. // With set_payload_max_length, the client must stop reading before consuming
  10728. // all 10MB. The read loop should be cut off at or near the configured limit.
  10729. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  10730. << "Client read " << total_read << " bytes, exceeding the configured "
  10731. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  10732. }
  10733. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  10734. // the entire response body without truncation.
  10735. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  10736. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  10737. #ifndef _WIN32
  10738. signal(SIGPIPE, SIG_IGN);
  10739. #endif
  10740. auto server_thread = std::thread([] {
  10741. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10742. default_socket_options(srv);
  10743. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10744. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10745. sockaddr_in addr{};
  10746. addr.sin_family = AF_INET;
  10747. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10748. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10749. int opt = 1;
  10750. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10751. #ifdef _WIN32
  10752. reinterpret_cast<const char *>(&opt),
  10753. #else
  10754. &opt,
  10755. #endif
  10756. sizeof(opt));
  10757. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10758. ::listen(srv, 1);
  10759. sockaddr_in cli_addr{};
  10760. socklen_t cli_len = sizeof(cli_addr);
  10761. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10762. if (cli != INVALID_SOCKET) {
  10763. char buf[4096];
  10764. ::recv(cli, buf, sizeof(buf), 0);
  10765. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10766. "Connection: close\r\n"
  10767. "\r\n";
  10768. ::send(cli,
  10769. #ifdef _WIN32
  10770. static_cast<const char *>(response_header.c_str()),
  10771. static_cast<int>(response_header.size()),
  10772. #else
  10773. response_header.c_str(), response_header.size(),
  10774. #endif
  10775. 0);
  10776. std::string chunk(64 * 1024, 'A');
  10777. size_t total_sent = 0;
  10778. while (total_sent < DATA_SIZE) {
  10779. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10780. auto sent = ::send(cli,
  10781. #ifdef _WIN32
  10782. static_cast<const char *>(chunk.c_str()),
  10783. static_cast<int>(to_send),
  10784. #else
  10785. chunk.c_str(), to_send,
  10786. #endif
  10787. 0);
  10788. if (sent <= 0) break;
  10789. total_sent += static_cast<size_t>(sent);
  10790. }
  10791. #ifdef _WIN32
  10792. ::shutdown(cli, SD_SEND);
  10793. #else
  10794. ::shutdown(cli, SHUT_WR);
  10795. #endif
  10796. // Drain until the client closes its end, ensuring all data is delivered
  10797. char drain[1024];
  10798. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10799. detail::close_socket(cli);
  10800. }
  10801. detail::close_socket(srv);
  10802. });
  10803. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10804. size_t total_read = 0;
  10805. {
  10806. Client cli("127.0.0.1", PORT + 2);
  10807. cli.set_read_timeout(5, 0);
  10808. cli.set_payload_max_length(0); // 0 means no limit
  10809. auto stream = cli.open_stream("GET", "/data");
  10810. ASSERT_TRUE(stream.is_valid());
  10811. char buffer[64 * 1024];
  10812. ssize_t n;
  10813. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10814. total_read += static_cast<size_t>(n);
  10815. }
  10816. }
  10817. server_thread.join();
  10818. EXPECT_EQ(total_read, DATA_SIZE)
  10819. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  10820. << " bytes without truncation, but only read " << total_read << " bytes.";
  10821. }
  10822. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  10823. // enormous Content-Length must not cause the client to pre-allocate a huge
  10824. // response body buffer. The reservation is capped at payload_max_length_, and
  10825. // the read itself fails when the body exceeds the limit.
  10826. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  10827. #ifndef _WIN32
  10828. signal(SIGPIPE, SIG_IGN);
  10829. #endif
  10830. auto server_thread = std::thread([] {
  10831. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10832. default_socket_options(srv);
  10833. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10834. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10835. sockaddr_in addr{};
  10836. addr.sin_family = AF_INET;
  10837. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10838. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10839. int opt = 1;
  10840. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10841. #ifdef _WIN32
  10842. reinterpret_cast<const char *>(&opt),
  10843. #else
  10844. &opt,
  10845. #endif
  10846. sizeof(opt));
  10847. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10848. ::listen(srv, 1);
  10849. sockaddr_in cli_addr{};
  10850. socklen_t cli_len = sizeof(cli_addr);
  10851. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10852. if (cli != INVALID_SOCKET) {
  10853. char buf[4096];
  10854. ::recv(cli, buf, sizeof(buf), 0);
  10855. // Malicious response: claim a 20GB body but send only a tiny payload.
  10856. std::string response = "HTTP/1.1 200 OK\r\n"
  10857. "Content-Length: 20000000000\r\n"
  10858. "\r\n"
  10859. "abc";
  10860. ::send(cli,
  10861. #ifdef _WIN32
  10862. static_cast<const char *>(response.c_str()),
  10863. static_cast<int>(response.size()),
  10864. #else
  10865. response.c_str(), response.size(),
  10866. #endif
  10867. 0);
  10868. detail::close_socket(cli);
  10869. }
  10870. detail::close_socket(srv);
  10871. });
  10872. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10873. {
  10874. Client cli("127.0.0.1", PORT + 2);
  10875. cli.set_read_timeout(5, 0);
  10876. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  10877. // result in a 20GB pre-allocation. The Get() call is expected to fail
  10878. // (server claims more bytes than payload_max_length permits), but it must
  10879. // not exhaust memory before getting there.
  10880. auto res = cli.Get("/malicious");
  10881. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  10882. }
  10883. server_thread.join();
  10884. }
  10885. // Verify that content_receiver bypasses the default payload_max_length,
  10886. // allowing streaming downloads larger than 100MB without requiring an explicit
  10887. // set_payload_max_length call.
  10888. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  10889. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10890. #ifndef _WIN32
  10891. signal(SIGPIPE, SIG_IGN);
  10892. #endif
  10893. auto server_thread = std::thread([] {
  10894. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10895. default_socket_options(srv);
  10896. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10897. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10898. sockaddr_in addr{};
  10899. addr.sin_family = AF_INET;
  10900. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10901. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10902. int opt = 1;
  10903. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10904. #ifdef _WIN32
  10905. reinterpret_cast<const char *>(&opt),
  10906. #else
  10907. &opt,
  10908. #endif
  10909. sizeof(opt));
  10910. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10911. ::listen(srv, 1);
  10912. sockaddr_in cli_addr{};
  10913. socklen_t cli_len = sizeof(cli_addr);
  10914. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10915. if (cli != INVALID_SOCKET) {
  10916. char buf[4096];
  10917. ::recv(cli, buf, sizeof(buf), 0);
  10918. // Response with Content-Length larger than default 100MB limit
  10919. auto content_length = std::to_string(DATA_SIZE);
  10920. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10921. "Content-Length: " +
  10922. content_length +
  10923. "\r\n"
  10924. "Connection: close\r\n"
  10925. "\r\n";
  10926. ::send(cli,
  10927. #ifdef _WIN32
  10928. static_cast<const char *>(response_header.c_str()),
  10929. static_cast<int>(response_header.size()),
  10930. #else
  10931. response_header.c_str(), response_header.size(),
  10932. #endif
  10933. 0);
  10934. std::string chunk(64 * 1024, 'A');
  10935. size_t total_sent = 0;
  10936. while (total_sent < DATA_SIZE) {
  10937. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10938. auto sent = ::send(cli,
  10939. #ifdef _WIN32
  10940. static_cast<const char *>(chunk.c_str()),
  10941. static_cast<int>(to_send),
  10942. #else
  10943. chunk.c_str(), to_send,
  10944. #endif
  10945. 0);
  10946. if (sent <= 0) break;
  10947. total_sent += static_cast<size_t>(sent);
  10948. }
  10949. detail::close_socket(cli);
  10950. }
  10951. detail::close_socket(srv);
  10952. });
  10953. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10954. size_t total_received = 0;
  10955. {
  10956. Client cli("127.0.0.1", PORT + 2);
  10957. cli.set_read_timeout(10, 0);
  10958. // Do NOT call set_payload_max_length — use the default 100MB limit
  10959. auto res =
  10960. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10961. total_received += data_length;
  10962. return true;
  10963. });
  10964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10965. EXPECT_EQ(StatusCode::OK_200, res->status);
  10966. }
  10967. server_thread.join();
  10968. EXPECT_EQ(total_received, DATA_SIZE)
  10969. << "With content_receiver, the client should read all " << DATA_SIZE
  10970. << " bytes despite the default 100MB payload_max_length, but only read "
  10971. << total_received << " bytes.";
  10972. }
  10973. // Verify that an explicit set_payload_max_length smaller than the response is
  10974. // enforced even when a content_receiver is used.
  10975. TEST(ClientVulnerabilityTest,
  10976. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  10977. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10978. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  10979. #ifndef _WIN32
  10980. signal(SIGPIPE, SIG_IGN);
  10981. #endif
  10982. auto server_thread = std::thread([] {
  10983. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10984. default_socket_options(srv);
  10985. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10986. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10987. sockaddr_in addr{};
  10988. addr.sin_family = AF_INET;
  10989. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10990. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10991. int opt = 1;
  10992. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10993. #ifdef _WIN32
  10994. reinterpret_cast<const char *>(&opt),
  10995. #else
  10996. &opt,
  10997. #endif
  10998. sizeof(opt));
  10999. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11000. ::listen(srv, 1);
  11001. sockaddr_in cli_addr{};
  11002. socklen_t cli_len = sizeof(cli_addr);
  11003. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11004. if (cli != INVALID_SOCKET) {
  11005. char buf[4096];
  11006. ::recv(cli, buf, sizeof(buf), 0);
  11007. auto content_length = std::to_string(DATA_SIZE);
  11008. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11009. "Content-Length: " +
  11010. content_length +
  11011. "\r\n"
  11012. "Connection: close\r\n"
  11013. "\r\n";
  11014. ::send(cli,
  11015. #ifdef _WIN32
  11016. static_cast<const char *>(response_header.c_str()),
  11017. static_cast<int>(response_header.size()),
  11018. #else
  11019. response_header.c_str(), response_header.size(),
  11020. #endif
  11021. 0);
  11022. std::string chunk(64 * 1024, 'A');
  11023. size_t total_sent = 0;
  11024. while (total_sent < DATA_SIZE) {
  11025. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11026. auto sent = ::send(cli,
  11027. #ifdef _WIN32
  11028. static_cast<const char *>(chunk.c_str()),
  11029. static_cast<int>(to_send),
  11030. #else
  11031. chunk.c_str(), to_send,
  11032. #endif
  11033. 0);
  11034. if (sent <= 0) break;
  11035. total_sent += static_cast<size_t>(sent);
  11036. }
  11037. detail::close_socket(cli);
  11038. }
  11039. detail::close_socket(srv);
  11040. });
  11041. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11042. size_t total_received = 0;
  11043. {
  11044. Client cli("127.0.0.1", PORT + 2);
  11045. cli.set_read_timeout(10, 0);
  11046. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11047. auto res =
  11048. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11049. total_received += data_length;
  11050. return true;
  11051. });
  11052. // Should fail because 200MB exceeds the explicit 150MB limit
  11053. EXPECT_FALSE(res);
  11054. }
  11055. server_thread.join();
  11056. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11057. << "Client with content_receiver should respect the explicit "
  11058. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11059. << total_received << " bytes.";
  11060. }
  11061. // Verify that an explicit set_payload_max_length larger than the response
  11062. // allows the content_receiver to read all data successfully.
  11063. TEST(ClientVulnerabilityTest,
  11064. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11065. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11066. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11067. #ifndef _WIN32
  11068. signal(SIGPIPE, SIG_IGN);
  11069. #endif
  11070. auto server_thread = std::thread([] {
  11071. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11072. default_socket_options(srv);
  11073. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11074. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11075. sockaddr_in addr{};
  11076. addr.sin_family = AF_INET;
  11077. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11078. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11079. int opt = 1;
  11080. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11081. #ifdef _WIN32
  11082. reinterpret_cast<const char *>(&opt),
  11083. #else
  11084. &opt,
  11085. #endif
  11086. sizeof(opt));
  11087. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11088. ::listen(srv, 1);
  11089. sockaddr_in cli_addr{};
  11090. socklen_t cli_len = sizeof(cli_addr);
  11091. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11092. if (cli != INVALID_SOCKET) {
  11093. char buf[4096];
  11094. ::recv(cli, buf, sizeof(buf), 0);
  11095. auto content_length = std::to_string(DATA_SIZE);
  11096. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11097. "Content-Length: " +
  11098. content_length +
  11099. "\r\n"
  11100. "Connection: close\r\n"
  11101. "\r\n";
  11102. ::send(cli,
  11103. #ifdef _WIN32
  11104. static_cast<const char *>(response_header.c_str()),
  11105. static_cast<int>(response_header.size()),
  11106. #else
  11107. response_header.c_str(), response_header.size(),
  11108. #endif
  11109. 0);
  11110. std::string chunk(64 * 1024, 'A');
  11111. size_t total_sent = 0;
  11112. while (total_sent < DATA_SIZE) {
  11113. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11114. auto sent = ::send(cli,
  11115. #ifdef _WIN32
  11116. static_cast<const char *>(chunk.c_str()),
  11117. static_cast<int>(to_send),
  11118. #else
  11119. chunk.c_str(), to_send,
  11120. #endif
  11121. 0);
  11122. if (sent <= 0) break;
  11123. total_sent += static_cast<size_t>(sent);
  11124. }
  11125. #ifdef _WIN32
  11126. ::shutdown(cli, SD_SEND);
  11127. #else
  11128. ::shutdown(cli, SHUT_WR);
  11129. #endif
  11130. char drain[1024];
  11131. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11132. detail::close_socket(cli);
  11133. }
  11134. detail::close_socket(srv);
  11135. });
  11136. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11137. size_t total_received = 0;
  11138. {
  11139. Client cli("127.0.0.1", PORT + 2);
  11140. cli.set_read_timeout(10, 0);
  11141. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11142. auto res =
  11143. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11144. total_received += data_length;
  11145. return true;
  11146. });
  11147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11148. EXPECT_EQ(StatusCode::OK_200, res->status);
  11149. }
  11150. server_thread.join();
  11151. EXPECT_EQ(total_received, DATA_SIZE)
  11152. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11153. << " bytes (larger than " << DATA_SIZE
  11154. << " bytes response), content_receiver should read all data, but only "
  11155. "read "
  11156. << total_received << " bytes.";
  11157. }
  11158. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11159. // Regression test for "zip bomb" attack on the client side: a malicious server
  11160. // sends a small gzip-compressed response that decompresses to a huge payload.
  11161. // The client must enforce payload_max_length on the decompressed size.
  11162. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11163. constexpr size_t DECOMPRESSED_SIZE =
  11164. 10 * 1024 * 1024; // 10MB after decompression
  11165. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11166. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11167. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11168. std::string compressed;
  11169. {
  11170. httplib::detail::gzip_compressor compressor;
  11171. bool ok =
  11172. compressor.compress(uncompressed.data(), uncompressed.size(),
  11173. /*last=*/true, [&](const char *buf, size_t len) {
  11174. compressed.append(buf, len);
  11175. return true;
  11176. });
  11177. ASSERT_TRUE(ok);
  11178. }
  11179. // Sanity: compressed data should be much smaller than the decompressed size
  11180. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11181. #ifndef _WIN32
  11182. signal(SIGPIPE, SIG_IGN);
  11183. #endif
  11184. // Set up the listening socket in the main thread so the server is guaranteed
  11185. // to be ready before the client connects (eliminates race condition).
  11186. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11187. default_socket_options(srv);
  11188. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11189. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11190. sockaddr_in addr{};
  11191. addr.sin_family = AF_INET;
  11192. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11193. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11194. int opt = 1;
  11195. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11196. #ifdef _WIN32
  11197. reinterpret_cast<const char *>(&opt),
  11198. #else
  11199. &opt,
  11200. #endif
  11201. sizeof(opt));
  11202. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11203. ASSERT_EQ(0, ::listen(srv, 1));
  11204. auto server_thread = std::thread([&compressed, srv] {
  11205. sockaddr_in cli_addr{};
  11206. socklen_t cli_len = sizeof(cli_addr);
  11207. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11208. if (cli != INVALID_SOCKET) {
  11209. // Read the full HTTP request (until \r\n\r\n)
  11210. char buf[4096];
  11211. size_t total = 0;
  11212. while (total < sizeof(buf)) {
  11213. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11214. if (n <= 0) break;
  11215. total += static_cast<size_t>(n);
  11216. // Check for end of headers
  11217. if (total >= 4) {
  11218. std::string req(buf, total);
  11219. if (req.find("\r\n\r\n") != std::string::npos) break;
  11220. }
  11221. }
  11222. // Malicious response: gzip-compressed body, no Content-Length
  11223. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11224. "Content-Encoding: gzip\r\n"
  11225. "Connection: close\r\n"
  11226. "\r\n";
  11227. ::send(cli,
  11228. #ifdef _WIN32
  11229. static_cast<const char *>(response_header.c_str()),
  11230. static_cast<int>(response_header.size()),
  11231. #else
  11232. response_header.c_str(), response_header.size(),
  11233. #endif
  11234. 0);
  11235. // Send the compressed payload (small on the wire, huge when decompressed)
  11236. size_t total_sent = 0;
  11237. while (total_sent < compressed.size()) {
  11238. auto to_send = std::min(compressed.size() - total_sent,
  11239. static_cast<size_t>(64 * 1024));
  11240. auto sent =
  11241. ::send(cli,
  11242. #ifdef _WIN32
  11243. static_cast<const char *>(compressed.c_str() + total_sent),
  11244. static_cast<int>(to_send),
  11245. #else
  11246. compressed.c_str() + total_sent, to_send,
  11247. #endif
  11248. 0);
  11249. if (sent <= 0) break;
  11250. total_sent += static_cast<size_t>(sent);
  11251. }
  11252. detail::close_socket(cli);
  11253. }
  11254. });
  11255. auto se = detail::scope_exit([&] {
  11256. detail::close_socket(srv);
  11257. server_thread.join();
  11258. });
  11259. size_t total_decompressed = 0;
  11260. {
  11261. Client cli("127.0.0.1", PORT + 3);
  11262. cli.set_read_timeout(5, 0);
  11263. cli.set_decompress(true);
  11264. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11265. auto stream = cli.open_stream("GET", "/zipbomb");
  11266. ASSERT_TRUE(stream.is_valid());
  11267. char buffer[64 * 1024];
  11268. ssize_t n;
  11269. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11270. total_decompressed += static_cast<size_t>(n);
  11271. }
  11272. }
  11273. // The decompressed size must be capped by payload_max_length. Without
  11274. // protection, the client would decompress the full 10MB from a tiny
  11275. // compressed payload, enabling a zip bomb DoS attack.
  11276. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11277. << "Client decompressed " << total_decompressed
  11278. << " bytes from a gzip response. The decompressed size should be "
  11279. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11280. }
  11281. #endif
  11282. TEST(HostAndPortPropertiesTest, NoSSL) {
  11283. httplib::Client cli("www.google.com", 1234);
  11284. ASSERT_EQ("www.google.com", cli.host());
  11285. ASSERT_EQ(1234, cli.port());
  11286. }
  11287. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11288. httplib::Client cli("www.google.com:1234");
  11289. ASSERT_EQ("www.google.com", cli.host());
  11290. ASSERT_EQ(1234, cli.port());
  11291. }
  11292. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11293. // Port number that overflows int — should not crash, client becomes invalid
  11294. httplib::Client cli("http://www.google.com:99999999999999999999");
  11295. ASSERT_FALSE(cli.is_valid());
  11296. }
  11297. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11298. // Port 99999 exceeds valid range (1-65535) — should not crash
  11299. httplib::Client cli("http://www.google.com:99999");
  11300. ASSERT_FALSE(cli.is_valid());
  11301. }
  11302. #ifdef CPPHTTPLIB_SSL_ENABLED
  11303. TEST(HostAndPortPropertiesTest, SSL) {
  11304. httplib::SSLClient cli("www.google.com");
  11305. ASSERT_EQ("www.google.com", cli.host());
  11306. ASSERT_EQ(443, cli.port());
  11307. }
  11308. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11309. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11310. std::string cert;
  11311. read_file(CA_CERT_FILE, cert);
  11312. httplib::SSLClient httplib_client("www.google.com");
  11313. // Load CA store first time
  11314. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11315. // Load CA store second time (update)
  11316. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11317. // Verify client is still valid and can make connections
  11318. httplib_client.enable_server_certificate_verification(true);
  11319. auto res = httplib_client.Get("/");
  11320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11321. // Google may return 200 or 301 depending on various factors
  11322. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11323. res->status == StatusCode::MovedPermanently_301);
  11324. }
  11325. TEST(SSLClientTest, ServerNameIndication_Online) {
  11326. auto host = "httpbingo.org";
  11327. auto path = std::string{"/get"};
  11328. SSLClient cli(host, 443);
  11329. auto res = cli.Get(path);
  11330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11331. ASSERT_EQ(StatusCode::OK_200, res->status);
  11332. }
  11333. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11334. // Use a site that will cause SSL verification failure due to self-signed cert
  11335. SSLClient cli("self-signed.badssl.com", 443);
  11336. cli.enable_server_certificate_verification(true);
  11337. auto res = cli.Get("/");
  11338. ASSERT_TRUE(!res);
  11339. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11340. // Verify backend error is captured for SSLServerVerification
  11341. // This occurs when certificate verification fails
  11342. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11343. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11344. EXPECT_NE(0UL, res.ssl_backend_error());
  11345. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11346. // For OpenSSL, ssl_error is 0 for verification errors
  11347. EXPECT_EQ(0, res.ssl_error());
  11348. #if !defined(_WIN32) || \
  11349. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11350. // On non-Windows or when Windows Schannel is disabled, the error comes
  11351. // from OpenSSL's verification
  11352. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11353. res.ssl_backend_error());
  11354. #endif
  11355. #endif
  11356. }
  11357. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11358. // Use a site where hostname doesn't match the certificate
  11359. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11360. SSLClient cli("wrong.host.badssl.com", 443);
  11361. cli.enable_server_certificate_verification(true);
  11362. cli.enable_server_hostname_verification(true);
  11363. auto res = cli.Get("/");
  11364. ASSERT_TRUE(!res);
  11365. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11366. // Verify backend error is captured for hostname verification failure
  11367. EXPECT_NE(0UL, res.ssl_backend_error());
  11368. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11369. // For OpenSSL, ssl_error is 0 for verification errors
  11370. EXPECT_EQ(0, res.ssl_error());
  11371. #if !defined(_WIN32) || \
  11372. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11373. // On non-Windows or when Windows Schannel is disabled, the error comes
  11374. // from OpenSSL's hostname verification
  11375. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11376. res.ssl_backend_error());
  11377. #endif
  11378. #endif
  11379. }
  11380. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11381. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11382. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11383. SSLClient cli("www.google.com", 443);
  11384. cli.enable_server_certificate_verification(true);
  11385. auto res = cli.Get("/");
  11386. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11387. }
  11388. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11389. SSLClient cli("www.google.com", 443);
  11390. cli.enable_server_certificate_verification(true);
  11391. cli.enable_windows_certificate_verification(false);
  11392. auto res = cli.Get("/");
  11393. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11394. }
  11395. #endif
  11396. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11397. Client cli("https://google.com");
  11398. auto res = cli.Get("/");
  11399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11400. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11401. }
  11402. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11403. SSLClient cli("google.com");
  11404. cli.set_ca_cert_path(CA_CERT_FILE);
  11405. auto res = cli.Get("/");
  11406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11407. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11408. }
  11409. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11410. SSLClient cli("google.com");
  11411. cli.enable_server_certificate_verification(true);
  11412. cli.set_ca_cert_path("hello");
  11413. auto res = cli.Get("/");
  11414. ASSERT_TRUE(!res);
  11415. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11416. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11417. // should be set
  11418. EXPECT_EQ(0, res.ssl_error());
  11419. // Verify backend error is captured for SSLLoadingCerts
  11420. // This error occurs when loading CA certificates fails
  11421. EXPECT_NE(0UL, res.ssl_backend_error());
  11422. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11423. // OpenSSL specific error codes:
  11424. // > openssl errstr 0x80000002
  11425. // error:80000002:system library::No such file or directory
  11426. // > openssl errstr 0xA000126
  11427. // error:0A000126:SSL routines::unexpected eof while reading
  11428. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11429. res.ssl_backend_error() == 0xA000126);
  11430. #endif
  11431. }
  11432. TEST(SSLClientTest, ServerCertificateVerification4) {
  11433. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11434. ASSERT_TRUE(svr.is_valid());
  11435. svr.Get("/test", [&](const Request &, Response &res) {
  11436. res.set_content("test", "text/plain");
  11437. svr.stop();
  11438. ASSERT_TRUE(true);
  11439. });
  11440. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11441. auto se = detail::scope_exit([&] {
  11442. t.join();
  11443. ASSERT_FALSE(svr.is_running());
  11444. });
  11445. svr.wait_until_ready();
  11446. SSLClient cli("127.0.0.1", PORT);
  11447. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11448. cli.enable_server_certificate_verification(true);
  11449. cli.set_connection_timeout(30);
  11450. auto res = cli.Get("/test");
  11451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11452. ASSERT_EQ(StatusCode::OK_200, res->status);
  11453. }
  11454. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11455. std::string cert;
  11456. read_file(CA_CERT_FILE, cert);
  11457. SSLClient cli("google.com");
  11458. cli.load_ca_cert_store(cert.data(), cert.size());
  11459. const auto res = cli.Get("/");
  11460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11461. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11462. }
  11463. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11464. // clang-format off
  11465. static constexpr char cert[] =
  11466. "GlobalSign Root CA\n"
  11467. "==================\n"
  11468. "-----BEGIN CERTIFICATE-----\n"
  11469. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11470. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11471. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11472. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11473. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11474. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11475. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11476. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11477. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11478. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11479. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11480. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11481. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11482. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11483. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11484. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11485. "-----END CERTIFICATE-----\n";
  11486. // clang-format on
  11487. SSLClient cli("google.com");
  11488. cli.load_ca_cert_store(cert, sizeof(cert));
  11489. const auto res = cli.Get("/");
  11490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11491. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11492. }
  11493. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11494. SSLClient cli("www.youtube.com");
  11495. cli.set_ca_cert_path(CA_CERT_FILE);
  11496. cli.enable_server_certificate_verification(true);
  11497. cli.set_follow_location(true);
  11498. auto res = cli.Get("/");
  11499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11500. ASSERT_EQ(StatusCode::OK_200, res->status);
  11501. }
  11502. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11503. SSLClient cli("wWw.YouTube.Com");
  11504. cli.set_ca_cert_path(CA_CERT_FILE);
  11505. cli.enable_server_certificate_verification(true);
  11506. cli.enable_server_hostname_verification(true);
  11507. cli.set_follow_location(true);
  11508. auto res = cli.Get("/");
  11509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11510. ASSERT_EQ(StatusCode::OK_200, res->status);
  11511. }
  11512. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11513. SSLClient cli("gOoGlE.COm");
  11514. cli.enable_server_certificate_verification(true);
  11515. cli.enable_server_hostname_verification(true);
  11516. cli.set_follow_location(true);
  11517. auto res = cli.Get("/");
  11518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11519. ASSERT_EQ(StatusCode::OK_200, res->status);
  11520. }
  11521. TEST(SSLClientTest, Issue2004_Online) {
  11522. Client client("https://google.com");
  11523. client.set_follow_location(true);
  11524. auto res = client.Get("/");
  11525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11526. ASSERT_EQ(StatusCode::OK_200, res->status);
  11527. auto body = res->body;
  11528. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11529. }
  11530. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11531. // Create SSLClient with invalid cert/key to make is_valid() return false
  11532. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11533. "nonexistent_key.pem");
  11534. // is_valid() should be false due to cert loading failure
  11535. ASSERT_FALSE(cli.is_valid());
  11536. auto res = cli.Get("/");
  11537. ASSERT_FALSE(res);
  11538. EXPECT_EQ(Error::SSLConnection, res.error());
  11539. }
  11540. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11541. // Test for Issue #2251: SSL error not properly reported when client cert
  11542. // and key paths are swapped or mismatched
  11543. // This simulates the scenario where user accidentally swaps the cert and key
  11544. // files
  11545. // Using client cert file as private key and vice versa (completely wrong)
  11546. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11547. // Should fail validation due to cert/key mismatch
  11548. ASSERT_FALSE(cli.is_valid());
  11549. // Attempt to make a request should fail with proper error
  11550. auto res = cli.Get("/");
  11551. ASSERT_FALSE(res);
  11552. EXPECT_EQ(Error::SSLConnection, res.error());
  11553. // SSL error should be recorded in the Result object (this is the key fix for
  11554. // Issue #2251)
  11555. auto backend_error = res.ssl_backend_error();
  11556. EXPECT_NE(0u, backend_error);
  11557. }
  11558. // Tests cert/key mismatch detection at the TLS context level
  11559. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11560. // Test that using mismatched cert/key causes connection failure.
  11561. // We verify this at the SSLClient level rather than through internal
  11562. // TLS API functions.
  11563. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11564. cli.enable_server_certificate_verification(false);
  11565. cli.set_connection_timeout(2);
  11566. // The mismatch should cause a connection or handshake error
  11567. auto res = cli.Get("/test");
  11568. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11569. // Either way, the request should fail
  11570. EXPECT_FALSE(res);
  11571. }
  11572. #endif
  11573. #if 0
  11574. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11575. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11576. ASSERT_TRUE(cli != nullptr);
  11577. cli->set_address_family(AF_INET6);
  11578. cli->set_interface("en0");
  11579. auto res = cli->Get("/get");
  11580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11581. ASSERT_EQ(StatusCode::OK_200, res->status);
  11582. }
  11583. #endif
  11584. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11585. #ifdef CPPHTTPLIB_SSL_ENABLED
  11586. void ClientCertPresent(
  11587. const std::string &client_cert_file,
  11588. const std::string &client_private_key_file,
  11589. const std::string &client_encrypted_private_key_pass = std::string()) {
  11590. using namespace httplib::tls;
  11591. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11592. CLIENT_CA_CERT_DIR);
  11593. ASSERT_TRUE(svr.is_valid());
  11594. svr.Get("/test", [&](const Request &req, Response &res) {
  11595. res.set_content("test", "text/plain");
  11596. auto cert = req.peer_cert();
  11597. ASSERT_TRUE(static_cast<bool>(cert));
  11598. std::string common_name = cert.subject_cn();
  11599. EXPECT_EQ("Common Name", common_name);
  11600. });
  11601. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11602. auto se = detail::scope_exit([&] {
  11603. svr.stop();
  11604. t.join();
  11605. ASSERT_FALSE(svr.is_running());
  11606. });
  11607. svr.wait_until_ready();
  11608. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11609. client_encrypted_private_key_pass);
  11610. cli.enable_server_certificate_verification(false);
  11611. cli.set_connection_timeout(30);
  11612. auto res = cli.Get("/test");
  11613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11614. ASSERT_EQ(StatusCode::OK_200, res->status);
  11615. }
  11616. TEST(SSLClientServerTest, ClientCertPresent) {
  11617. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11618. }
  11619. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11620. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11621. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11622. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11623. }
  11624. // PEM memory-based constructor tests (works with all TLS backends)
  11625. void PemMemoryClientCertPresent(
  11626. const std::string &client_cert_file,
  11627. const std::string &client_private_key_file,
  11628. const std::string &client_encrypted_private_key_pass = std::string()) {
  11629. // Read PEM files into memory
  11630. std::string server_cert_pem, server_key_pem;
  11631. std::string client_ca_pem;
  11632. std::string client_cert_pem, client_key_pem;
  11633. read_file(SERVER_CERT_FILE, server_cert_pem);
  11634. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11635. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11636. read_file(client_cert_file, client_cert_pem);
  11637. read_file(client_private_key_file, client_key_pem);
  11638. // Create server with PEM memory
  11639. SSLServer::PemMemory server_pem = {
  11640. server_cert_pem.c_str(),
  11641. server_cert_pem.size(),
  11642. server_key_pem.c_str(),
  11643. server_key_pem.size(),
  11644. client_ca_pem.c_str(),
  11645. client_ca_pem.size(),
  11646. nullptr // no password for server key
  11647. };
  11648. SSLServer svr(server_pem);
  11649. ASSERT_TRUE(svr.is_valid());
  11650. svr.Get("/test", [&](const Request &, Response &res) {
  11651. res.set_content("test", "text/plain");
  11652. });
  11653. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11654. auto se = detail::scope_exit([&] {
  11655. svr.stop();
  11656. t.join();
  11657. ASSERT_FALSE(svr.is_running());
  11658. });
  11659. svr.wait_until_ready();
  11660. // Create client with PEM memory
  11661. const char *password = client_encrypted_private_key_pass.empty()
  11662. ? nullptr
  11663. : client_encrypted_private_key_pass.c_str();
  11664. SSLClient::PemMemory client_pem = {
  11665. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  11666. client_key_pem.size(), password};
  11667. SSLClient cli(HOST, PORT, client_pem);
  11668. cli.enable_server_certificate_verification(false);
  11669. cli.set_connection_timeout(30);
  11670. auto res = cli.Get("/test");
  11671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11672. ASSERT_EQ(StatusCode::OK_200, res->status);
  11673. }
  11674. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  11675. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11676. }
  11677. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  11678. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11679. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11680. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11681. }
  11682. TEST(SSLClientServerTest, ClientCertMissing) {
  11683. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11684. CLIENT_CA_CERT_DIR);
  11685. ASSERT_TRUE(svr.is_valid());
  11686. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  11687. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11688. auto se = detail::scope_exit([&] {
  11689. svr.stop();
  11690. t.join();
  11691. ASSERT_FALSE(svr.is_running());
  11692. });
  11693. svr.wait_until_ready();
  11694. SSLClient cli(HOST, PORT);
  11695. cli.set_connection_timeout(30);
  11696. auto res = cli.Get("/test");
  11697. ASSERT_TRUE(!res);
  11698. // When client cert is missing and server requires it, connection fails
  11699. // Error type depends on backend implementation
  11700. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11701. res.error() == Error::SSLConnection);
  11702. // Verify backend error is captured
  11703. // Note: This test may have different error codes depending on the exact
  11704. // verification failure
  11705. EXPECT_NE(0UL, res.ssl_backend_error());
  11706. }
  11707. TEST(SSLClientServerTest, TrustDirOptional) {
  11708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11709. ASSERT_TRUE(svr.is_valid());
  11710. svr.Get("/test", [&](const Request &, Response &res) {
  11711. res.set_content("test", "text/plain");
  11712. });
  11713. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11714. auto se = detail::scope_exit([&] {
  11715. svr.stop();
  11716. t.join();
  11717. ASSERT_FALSE(svr.is_running());
  11718. });
  11719. svr.wait_until_ready();
  11720. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11721. cli.enable_server_certificate_verification(false);
  11722. cli.set_connection_timeout(30);
  11723. auto res = cli.Get("/test");
  11724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11725. ASSERT_EQ(StatusCode::OK_200, res->status);
  11726. }
  11727. TEST(SSLClientServerTest, SSLConnectTimeout) {
  11728. class NoListenSSLServer : public SSLServer {
  11729. public:
  11730. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  11731. const char *client_ca_cert_file_path,
  11732. const char *client_ca_cert_dir_path = nullptr)
  11733. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  11734. client_ca_cert_dir_path),
  11735. stop_(false) {}
  11736. std::atomic_bool stop_;
  11737. private:
  11738. bool process_and_close_socket(socket_t /*sock*/) override {
  11739. // Don't create SSL context
  11740. while (!stop_.load()) {
  11741. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11742. }
  11743. return true;
  11744. }
  11745. };
  11746. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11747. CLIENT_CA_CERT_FILE);
  11748. ASSERT_TRUE(svr.is_valid());
  11749. svr.Get("/test", [&](const Request &, Response &res) {
  11750. res.set_content("test", "text/plain");
  11751. });
  11752. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11753. auto se = detail::scope_exit([&] {
  11754. svr.stop_ = true;
  11755. svr.stop();
  11756. t.join();
  11757. ASSERT_FALSE(svr.is_running());
  11758. });
  11759. svr.wait_until_ready();
  11760. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11761. cli.enable_server_certificate_verification(false);
  11762. cli.set_connection_timeout(1);
  11763. auto res = cli.Get("/test");
  11764. ASSERT_TRUE(!res);
  11765. EXPECT_EQ(Error::SSLConnection, res.error());
  11766. // Timeout results in WantRead error code (maps to backend-specific value)
  11767. EXPECT_NE(0, res.ssl_error());
  11768. }
  11769. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  11770. // Test SSLServer with client certificate verification using the standard
  11771. // constructor (ContextSetupCallback is tested by backend-specific tests)
  11772. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11773. CLIENT_CA_CERT_DIR);
  11774. ASSERT_TRUE(svr.is_valid());
  11775. svr.Get("/test", [&](const Request &req, Response &res) {
  11776. res.set_content("test", "text/plain");
  11777. auto cert = req.peer_cert();
  11778. ASSERT_TRUE(static_cast<bool>(cert));
  11779. auto common_name = cert.subject_cn();
  11780. EXPECT_EQ("Common Name", common_name);
  11781. });
  11782. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11783. auto se = detail::scope_exit([&] {
  11784. svr.stop();
  11785. t.join();
  11786. ASSERT_FALSE(svr.is_running());
  11787. });
  11788. svr.wait_until_ready();
  11789. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11790. cli.enable_server_certificate_verification(false);
  11791. cli.set_connection_timeout(30);
  11792. auto res = cli.Get("/test");
  11793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11794. ASSERT_EQ(StatusCode::OK_200, res->status);
  11795. }
  11796. // Test verify_hostname for both OpenSSL and MbedTLS backends
  11797. // Verifies that wildcard matching and exact matching work consistently
  11798. TEST(SSLClientServerTest, TlsVerifyHostname) {
  11799. using namespace httplib::tls;
  11800. // We need a running server to test against
  11801. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11802. ASSERT_TRUE(svr.is_valid());
  11803. svr.Get("/test", [](const Request &, Response &res) {
  11804. res.set_content("ok", "text/plain");
  11805. });
  11806. thread t([&]() { svr.listen(HOST, PORT); });
  11807. auto se = detail::scope_exit([&] {
  11808. svr.stop();
  11809. t.join();
  11810. });
  11811. svr.wait_until_ready();
  11812. bool verify_callback_called = false;
  11813. bool verify_result_wrong = false;
  11814. SSLClient cli(HOST, PORT);
  11815. cli.enable_server_certificate_verification(true);
  11816. cli.set_ca_cert_path(CA_CERT_FILE);
  11817. cli.set_connection_timeout(5);
  11818. // Note: Test certificate has CN="Common Name", not "localhost"
  11819. bool verify_result_cn = false;
  11820. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11821. verify_callback_called = true;
  11822. if (!ctx.cert) return false;
  11823. // Test 1: "Common Name" should match (our test server cert CN)
  11824. verify_result_cn = ctx.check_hostname("Common Name");
  11825. // Test 2: wrong hostname should not match
  11826. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  11827. return true; // Accept for the purpose of this test
  11828. });
  11829. auto res = cli.Get("/test");
  11830. // The request may succeed or fail depending on cert configuration
  11831. // but the callback should have been called
  11832. ASSERT_TRUE(verify_callback_called)
  11833. << "Verify callback should have been called";
  11834. // CN="Common Name" should match our test certificate
  11835. //
  11836. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  11837. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  11838. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  11839. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  11840. // <openssl/base.h>, which is included transitively when
  11841. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  11842. #if defined(OPENSSL_IS_BORINGSSL)
  11843. EXPECT_FALSE(verify_result_cn)
  11844. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  11845. #else
  11846. EXPECT_TRUE(verify_result_cn)
  11847. << "verify_hostname should match 'Common Name' (certificate CN)";
  11848. #endif
  11849. // Wrong hostname should not match
  11850. EXPECT_FALSE(verify_result_wrong)
  11851. << "verify_hostname should not match 'wronghost.example.com'";
  11852. }
  11853. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  11854. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  11855. // X509_check_ip behavior and must hold for every backend.
  11856. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  11857. using namespace httplib::tls;
  11858. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  11859. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  11860. ASSERT_TRUE(svr.is_valid());
  11861. svr.Get("/test", [](const Request &, Response &res) {
  11862. res.set_content("ok", "text/plain");
  11863. });
  11864. thread t([&]() { svr.listen(HOST, PORT); });
  11865. auto se = detail::scope_exit([&] {
  11866. svr.stop();
  11867. t.join();
  11868. });
  11869. svr.wait_until_ready();
  11870. bool verify_callback_called = false;
  11871. bool ip_matched_via_cn = true;
  11872. SSLClient cli(HOST, PORT);
  11873. cli.enable_server_certificate_verification(true);
  11874. cli.set_ca_cert_path(CA_CERT_FILE);
  11875. cli.set_connection_timeout(5);
  11876. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11877. verify_callback_called = true;
  11878. if (!ctx.cert) return false;
  11879. // The IP appears only in the CN, so it must NOT be accepted.
  11880. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  11881. return true; // Accept for the purpose of this test
  11882. });
  11883. cli.Get("/test");
  11884. ASSERT_TRUE(verify_callback_called)
  11885. << "Verify callback should have been called";
  11886. EXPECT_FALSE(ip_matched_via_cn)
  11887. << "An IP host must not be authenticated via the certificate CN";
  11888. }
  11889. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  11890. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  11891. using namespace httplib::tls;
  11892. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  11893. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  11894. ASSERT_TRUE(svr.is_valid());
  11895. svr.Get("/test", [](const Request &, Response &res) {
  11896. res.set_content("ok", "text/plain");
  11897. });
  11898. thread t([&]() { svr.listen(HOST, PORT); });
  11899. auto se = detail::scope_exit([&] {
  11900. svr.stop();
  11901. t.join();
  11902. });
  11903. svr.wait_until_ready();
  11904. bool verify_callback_called = false;
  11905. bool san_matched = false;
  11906. bool wrong_ipv6_matched = true;
  11907. bool cn_ipv6_matched = true;
  11908. SSLClient cli(HOST, PORT);
  11909. cli.enable_server_certificate_verification(true);
  11910. cli.set_ca_cert_path(CA_CERT_FILE);
  11911. cli.set_connection_timeout(5);
  11912. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11913. verify_callback_called = true;
  11914. if (!ctx.cert) return false;
  11915. // Matches the IPv6 iPAddress SAN.
  11916. san_matched = ctx.check_hostname("2001:db8::1");
  11917. // A different IPv6 address must not match.
  11918. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  11919. // "::1" lives only in the CN, so it must not be accepted.
  11920. cn_ipv6_matched = ctx.check_hostname("::1");
  11921. return true; // Accept for the purpose of this test
  11922. });
  11923. cli.Get("/test");
  11924. ASSERT_TRUE(verify_callback_called)
  11925. << "Verify callback should have been called";
  11926. EXPECT_TRUE(san_matched)
  11927. << "verify_hostname should match an IPv6 iPAddress SAN";
  11928. EXPECT_FALSE(wrong_ipv6_matched)
  11929. << "verify_hostname should not match a non-matching IPv6 address";
  11930. EXPECT_FALSE(cn_ipv6_matched)
  11931. << "An IPv6 host must not be authenticated via the certificate CN";
  11932. }
  11933. #endif
  11934. // mbedTLS-specific callback constructor test
  11935. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  11936. #ifdef CPPHTTPLIB_SSL_ENABLED
  11937. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  11938. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11939. ASSERT_TRUE(svr.is_valid());
  11940. // Set up a handler to verify client certificate is present
  11941. bool client_cert_verified = false;
  11942. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11943. // Verify that client certificate was provided
  11944. client_cert_verified = true;
  11945. res.set_content("success", "text/plain");
  11946. });
  11947. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11948. auto se = detail::scope_exit([&] {
  11949. svr.stop();
  11950. t.join();
  11951. ASSERT_FALSE(svr.is_running());
  11952. });
  11953. svr.wait_until_ready();
  11954. // Client with certificate
  11955. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11956. cli.enable_server_certificate_verification(false);
  11957. cli.set_connection_timeout(30);
  11958. auto res = cli.Get("/test");
  11959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11960. ASSERT_EQ(StatusCode::OK_200, res->status);
  11961. ASSERT_TRUE(client_cert_verified);
  11962. EXPECT_EQ("success", res->body);
  11963. }
  11964. #endif
  11965. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  11966. // backends
  11967. #ifdef CPPHTTPLIB_SSL_ENABLED
  11968. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  11969. using namespace httplib::tls;
  11970. // Test that when client CA cert file is provided,
  11971. // the server properly requests and validates client certificates
  11972. // Create a server with client authentication
  11973. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11974. ASSERT_TRUE(svr.is_valid());
  11975. bool handler_called = false;
  11976. svr.Get("/test", [&](const Request &req, Response &res) {
  11977. handler_called = true;
  11978. // Verify that a client certificate was provided
  11979. auto cert = req.peer_cert();
  11980. ASSERT_TRUE(static_cast<bool>(cert));
  11981. // Get the issuer name
  11982. std::string issuer_str = cert.issuer_name();
  11983. ASSERT_FALSE(issuer_str.empty());
  11984. // The client certificate should be issued by our test CA
  11985. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  11986. res.set_content("authenticated", "text/plain");
  11987. });
  11988. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11989. auto se = detail::scope_exit([&] {
  11990. svr.stop();
  11991. t.join();
  11992. ASSERT_FALSE(svr.is_running());
  11993. });
  11994. svr.wait_until_ready();
  11995. // Connect with a client certificate issued by the CA
  11996. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11997. cli.enable_server_certificate_verification(false);
  11998. cli.set_connection_timeout(30);
  11999. auto res = cli.Get("/test");
  12000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12001. ASSERT_EQ(StatusCode::OK_200, res->status);
  12002. ASSERT_TRUE(handler_called);
  12003. EXPECT_EQ("authenticated", res->body);
  12004. }
  12005. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12006. using namespace httplib::tls;
  12007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12008. ASSERT_TRUE(svr.is_valid());
  12009. svr.Get("/test", [](const Request &, Response &res) {
  12010. res.set_content("ok", "text/plain");
  12011. });
  12012. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12013. auto se = detail::scope_exit([&] {
  12014. svr.stop();
  12015. t.join();
  12016. });
  12017. svr.wait_until_ready();
  12018. SSLClient cli(HOST, PORT);
  12019. cli.enable_server_certificate_verification(false);
  12020. cli.set_connection_timeout(30);
  12021. bool cert_checked = false;
  12022. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12023. if (ctx.cert) {
  12024. auto sans = ctx.sans();
  12025. // Test certificate may or may not have SANs - just verify the API
  12026. // works If SANs exist, verify the types are valid
  12027. for (const auto &san : sans) {
  12028. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12029. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12030. san.type == SanType::OTHER);
  12031. EXPECT_FALSE(san.value.empty());
  12032. }
  12033. cert_checked = true;
  12034. }
  12035. return true;
  12036. });
  12037. auto res = cli.Get("/test");
  12038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12039. EXPECT_TRUE(cert_checked);
  12040. }
  12041. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12042. using namespace httplib::tls;
  12043. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12044. ASSERT_TRUE(svr.is_valid());
  12045. svr.Get("/test", [](const Request &, Response &res) {
  12046. res.set_content("ok", "text/plain");
  12047. });
  12048. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12049. auto se = detail::scope_exit([&] {
  12050. svr.stop();
  12051. t.join();
  12052. });
  12053. svr.wait_until_ready();
  12054. SSLClient cli(HOST, PORT);
  12055. cli.enable_server_certificate_verification(false);
  12056. cli.set_connection_timeout(30);
  12057. bool validity_checked = false;
  12058. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12059. if (ctx.cert) {
  12060. time_t not_before = 0, not_after = 0;
  12061. bool result = ctx.validity(not_before, not_after);
  12062. EXPECT_TRUE(result);
  12063. // Verify that not_before < now < not_after for a valid cert
  12064. time_t now = time(nullptr);
  12065. EXPECT_LT(not_before, now);
  12066. EXPECT_GT(not_after, now);
  12067. validity_checked = true;
  12068. }
  12069. return true;
  12070. });
  12071. auto res = cli.Get("/test");
  12072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12073. EXPECT_TRUE(validity_checked);
  12074. }
  12075. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12076. using namespace httplib::tls;
  12077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12078. ASSERT_TRUE(svr.is_valid());
  12079. svr.Get("/test", [](const Request &, Response &res) {
  12080. res.set_content("ok", "text/plain");
  12081. });
  12082. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12083. auto se = detail::scope_exit([&] {
  12084. svr.stop();
  12085. t.join();
  12086. });
  12087. svr.wait_until_ready();
  12088. SSLClient cli(HOST, PORT);
  12089. cli.enable_server_certificate_verification(false);
  12090. cli.set_connection_timeout(30);
  12091. bool serial_checked = false;
  12092. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12093. if (ctx.cert) {
  12094. std::string serial = ctx.serial();
  12095. EXPECT_FALSE(serial.empty());
  12096. // Serial should be a hex string
  12097. for (char c : serial) {
  12098. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12099. (c >= 'a' && c <= 'f'));
  12100. }
  12101. serial_checked = true;
  12102. }
  12103. return true;
  12104. });
  12105. auto res = cli.Get("/test");
  12106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12107. EXPECT_TRUE(serial_checked);
  12108. }
  12109. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12110. // Test 1: Valid CA file - no error should be recorded
  12111. {
  12112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12113. CLIENT_CA_CERT_FILE);
  12114. ASSERT_TRUE(svr.is_valid());
  12115. // With valid setup, last_ssl_error should be 0
  12116. EXPECT_EQ(0, svr.ssl_last_error());
  12117. }
  12118. // Test 2: Invalid CA file content
  12119. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12120. {
  12121. // Create a temporary file with completely invalid content
  12122. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12123. {
  12124. std::ofstream ofs(temp_invalid_ca);
  12125. ofs << "This is not a certificate file at all\n";
  12126. ofs << "Just plain text content\n";
  12127. }
  12128. // Create server with invalid CA file
  12129. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12130. // Clean up temporary file
  12131. std::remove(temp_invalid_ca);
  12132. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12133. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12134. // Note: SSL_CTX_load_verify_locations typically fails first,
  12135. // but our error handling code path is still exercised
  12136. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12137. }
  12138. }
  12139. TEST(VerifyCallbackTest, VerifyContextFields) {
  12140. using namespace httplib::tls;
  12141. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12142. ASSERT_TRUE(svr.is_valid());
  12143. svr.Get("/test", [](const Request &, Response &res) {
  12144. res.set_content("ok", "text/plain");
  12145. });
  12146. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12147. auto se = detail::scope_exit([&] {
  12148. svr.stop();
  12149. t.join();
  12150. });
  12151. svr.wait_until_ready();
  12152. SSLClient cli(HOST, PORT);
  12153. cli.enable_server_certificate_verification(false);
  12154. cli.set_connection_timeout(30);
  12155. int callback_count = 0;
  12156. bool saw_leaf_cert = false;
  12157. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12158. if (ctx.cert) {
  12159. callback_count++;
  12160. // We should see at least one certificate (the leaf)
  12161. std::string cn = ctx.subject_cn();
  12162. if (!cn.empty()) { saw_leaf_cert = true; }
  12163. // Verify context fields are populated
  12164. EXPECT_NE(ctx.session, nullptr);
  12165. EXPECT_GE(ctx.depth, 0);
  12166. }
  12167. return true;
  12168. });
  12169. auto res = cli.Get("/test");
  12170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12171. EXPECT_GT(callback_count, 0);
  12172. EXPECT_TRUE(saw_leaf_cert);
  12173. }
  12174. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12175. using httplib::tls::TlsError;
  12176. // Test that verify_error_to_string returns empty for success
  12177. std::string success_str = TlsError::verify_error_to_string(0);
  12178. EXPECT_TRUE(success_str.empty());
  12179. // Test that verify_error_to_string returns non-empty for error codes
  12180. // Using a common error code (certificate expired)
  12181. std::string error_str =
  12182. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12183. EXPECT_FALSE(error_str.empty());
  12184. }
  12185. TEST(SessionVerifierTest, CertificateAccepted) {
  12186. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12187. ASSERT_TRUE(svr.is_valid());
  12188. svr.Get("/test", [](const Request &, Response &res) {
  12189. res.set_content("ok", "text/plain");
  12190. });
  12191. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12192. auto se = detail::scope_exit([&] {
  12193. svr.stop();
  12194. t.join();
  12195. });
  12196. svr.wait_until_ready();
  12197. SSLClient cli(HOST, PORT);
  12198. cli.enable_server_certificate_verification(false);
  12199. cli.set_connection_timeout(30);
  12200. bool callback_called = false;
  12201. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12202. EXPECT_NE(session, nullptr);
  12203. callback_called = true;
  12204. return SSLVerifierResponse::CertificateAccepted;
  12205. });
  12206. auto res = cli.Get("/test");
  12207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12208. EXPECT_EQ(200, res->status);
  12209. EXPECT_TRUE(callback_called);
  12210. }
  12211. TEST(SessionVerifierTest, CertificateRejected) {
  12212. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12213. ASSERT_TRUE(svr.is_valid());
  12214. svr.Get("/test", [](const Request &, Response &res) {
  12215. res.set_content("ok", "text/plain");
  12216. });
  12217. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12218. auto se = detail::scope_exit([&] {
  12219. svr.stop();
  12220. t.join();
  12221. });
  12222. svr.wait_until_ready();
  12223. SSLClient cli(HOST, PORT);
  12224. cli.enable_server_certificate_verification(false);
  12225. cli.set_connection_timeout(30);
  12226. bool callback_called = false;
  12227. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12228. EXPECT_NE(session, nullptr);
  12229. callback_called = true;
  12230. return SSLVerifierResponse::CertificateRejected;
  12231. });
  12232. auto res = cli.Get("/test");
  12233. EXPECT_FALSE(res);
  12234. EXPECT_TRUE(callback_called);
  12235. }
  12236. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12237. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12238. ASSERT_TRUE(svr.is_valid());
  12239. svr.Get("/test", [](const Request &, Response &res) {
  12240. res.set_content("ok", "text/plain");
  12241. });
  12242. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12243. auto se = detail::scope_exit([&] {
  12244. svr.stop();
  12245. t.join();
  12246. });
  12247. svr.wait_until_ready();
  12248. // NoDecisionMade with verification disabled should succeed (no default check)
  12249. SSLClient cli(HOST, PORT);
  12250. cli.enable_server_certificate_verification(false);
  12251. cli.set_connection_timeout(30);
  12252. bool callback_called = false;
  12253. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12254. EXPECT_NE(session, nullptr);
  12255. callback_called = true;
  12256. return SSLVerifierResponse::NoDecisionMade;
  12257. });
  12258. auto res = cli.Get("/test");
  12259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12260. EXPECT_EQ(200, res->status);
  12261. EXPECT_TRUE(callback_called);
  12262. }
  12263. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12264. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12265. ASSERT_TRUE(svr.is_valid());
  12266. svr.Get("/test", [](const Request &, Response &res) {
  12267. res.set_content("ok", "text/plain");
  12268. });
  12269. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12270. auto se = detail::scope_exit([&] {
  12271. svr.stop();
  12272. t.join();
  12273. });
  12274. svr.wait_until_ready();
  12275. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12276. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12277. // so we only check that the request fails, not whether the callback was
  12278. // called.
  12279. SSLClient cli(HOST, PORT);
  12280. cli.enable_server_certificate_verification(true);
  12281. cli.set_connection_timeout(30);
  12282. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12283. EXPECT_NE(session, nullptr);
  12284. return SSLVerifierResponse::NoDecisionMade;
  12285. });
  12286. auto res = cli.Get("/test");
  12287. EXPECT_FALSE(res);
  12288. }
  12289. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12290. // Test SSL server using PemMemory constructor with client CA certificates
  12291. // Read PEM files
  12292. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12293. read_file(SERVER_CERT_FILE, server_cert_pem);
  12294. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12295. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12296. // Create SSLServer with PemMemory constructor including client CA
  12297. SSLServer::PemMemory server_pem = {
  12298. server_cert_pem.c_str(),
  12299. server_cert_pem.size(),
  12300. server_key_pem.c_str(),
  12301. server_key_pem.size(),
  12302. client_ca_pem.c_str(),
  12303. client_ca_pem.size(),
  12304. nullptr // no password for server key
  12305. };
  12306. SSLServer svr(server_pem);
  12307. ASSERT_TRUE(svr.is_valid());
  12308. // No SSL error should be recorded for valid setup
  12309. EXPECT_EQ(0, svr.ssl_last_error());
  12310. // Set up server endpoints
  12311. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12312. res.set_content("ok", "text/plain");
  12313. });
  12314. // Start server in a thread
  12315. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12316. svr.wait_until_ready();
  12317. // Connect with client certificate (using constructor with paths)
  12318. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12319. cli.enable_server_certificate_verification(false);
  12320. auto res = cli.Get("/test-pem-ca");
  12321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12322. EXPECT_EQ(200, res->status);
  12323. EXPECT_EQ("ok", res->body);
  12324. svr.stop();
  12325. server_thread.join();
  12326. }
  12327. #endif
  12328. #ifdef _WIN32
  12329. TEST(CleanupTest, WSACleanup) {
  12330. int ret = WSACleanup();
  12331. ASSERT_EQ(0, ret);
  12332. }
  12333. #endif
  12334. #ifndef CPPHTTPLIB_SSL_ENABLED
  12335. TEST(NoSSLSupport, SimpleInterface) {
  12336. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12337. }
  12338. #endif
  12339. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12340. TEST(InvalidScheme, SimpleInterface) {
  12341. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12342. }
  12343. #endif
  12344. TEST(NoScheme, SimpleInterface) {
  12345. Client cli("yahoo.com:80");
  12346. ASSERT_TRUE(cli.is_valid());
  12347. }
  12348. TEST(SendAPI, SimpleInterface_Online) {
  12349. Client cli("http://yahoo.com");
  12350. Request req;
  12351. req.method = "GET";
  12352. req.path = "/";
  12353. auto res = cli.send(req);
  12354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12355. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12356. }
  12357. TEST(SendAPI, WithParamsInRequest) {
  12358. Server svr;
  12359. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12360. EXPECT_TRUE(req.has_param("test"));
  12361. EXPECT_EQ("test_value", req.get_param_value("test"));
  12362. });
  12363. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12364. auto se = detail::scope_exit([&] {
  12365. svr.stop();
  12366. t.join();
  12367. ASSERT_FALSE(svr.is_running());
  12368. });
  12369. svr.wait_until_ready();
  12370. Client cli(HOST, PORT);
  12371. {
  12372. Request req;
  12373. req.method = "GET";
  12374. req.path = "/";
  12375. req.params.emplace("test", "test_value");
  12376. auto res = cli.send(req);
  12377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12378. }
  12379. {
  12380. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12382. }
  12383. }
  12384. TEST(ClientImplMethods, GetSocketTest) {
  12385. httplib::Server svr;
  12386. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12387. res.status = StatusCode::OK_200;
  12388. });
  12389. auto port = svr.bind_to_any_port("127.0.0.1");
  12390. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12391. auto se = detail::scope_exit([&] {
  12392. svr.stop();
  12393. thread.join();
  12394. ASSERT_FALSE(svr.is_running());
  12395. });
  12396. svr.wait_until_ready();
  12397. {
  12398. httplib::Client cli("127.0.0.1", port);
  12399. cli.set_keep_alive(true);
  12400. // Use the behavior of cpp-httplib of opening the connection
  12401. // only when the first request happens. If that changes,
  12402. // this test would be obsolete.
  12403. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12404. // This also implicitly tests the server. But other tests would fail much
  12405. // earlier than this one to be considered.
  12406. auto res = cli.Get("/");
  12407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12408. EXPECT_EQ(StatusCode::OK_200, res->status);
  12409. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12410. }
  12411. }
  12412. #ifdef CPPHTTPLIB_SSL_ENABLED
  12413. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12414. Client cli("http://yahoo.com");
  12415. auto res = cli.Get("/");
  12416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12417. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12418. cli.set_follow_location(true);
  12419. res = cli.Get("/");
  12420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12421. EXPECT_EQ(StatusCode::OK_200, res->status);
  12422. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12423. }
  12424. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12425. Client cli("https://yahoo.com");
  12426. auto res = cli.Get("/");
  12427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12428. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12429. cli.set_follow_location(true);
  12430. res = cli.Get("/");
  12431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12432. EXPECT_EQ(StatusCode::OK_200, res->status);
  12433. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12434. }
  12435. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12436. Client cli("https://yahoo.com");
  12437. auto res = cli.Get("/");
  12438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12439. ASSERT_FALSE(!res);
  12440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12441. ASSERT_FALSE(res == nullptr);
  12442. ASSERT_TRUE(res != nullptr);
  12443. EXPECT_EQ(Error::Success, res.error());
  12444. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12445. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12446. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12447. cli.set_follow_location(true);
  12448. res = cli.Get("/");
  12449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12450. EXPECT_EQ(Error::Success, res.error());
  12451. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12452. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12453. EXPECT_EQ(StatusCode::OK_200, res->status);
  12454. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12455. }
  12456. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12457. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12458. Client cli("https://cdnjs.cloudflare.com");
  12459. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12460. Headers{{"Accept-Encoding", "br"}});
  12461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12462. EXPECT_EQ(StatusCode::OK_200, res->status);
  12463. EXPECT_EQ(287630U, res->body.size());
  12464. EXPECT_EQ("application/javascript; charset=utf-8",
  12465. res->get_header_value("Content-Type"));
  12466. }
  12467. #endif
  12468. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12469. #undef REDIR_HOST // Silence compiler warning
  12470. #define REDIR_HOST "https://httpbingo.org"
  12471. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12472. Client cli(REDIR_HOST);
  12473. cli.set_follow_location(true);
  12474. auto res =
  12475. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12477. EXPECT_EQ(StatusCode::OK_200, res->status);
  12478. }
  12479. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12480. Client cli(REDIR_HOST);
  12481. cli.set_follow_location(true);
  12482. Params params;
  12483. params.emplace("url", "http://example.com");
  12484. params.emplace("status_code", "302");
  12485. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12487. EXPECT_EQ(StatusCode::OK_200, res->status);
  12488. }
  12489. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12490. Client cli(REDIR_HOST);
  12491. cli.set_follow_location(true);
  12492. Params params;
  12493. params.emplace("url", "http://example.com");
  12494. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12496. EXPECT_EQ(StatusCode::OK_200, res->status);
  12497. }
  12498. TEST(HttpToHttpsRedirectTest, CertFile) {
  12499. auto ssl_port = PORT + 1;
  12500. Server svr;
  12501. ASSERT_TRUE(svr.is_valid());
  12502. svr.Get("/index", [&](const Request &, Response &res) {
  12503. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12504. "/index");
  12505. svr.stop();
  12506. });
  12507. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12508. ASSERT_TRUE(ssl_svr.is_valid());
  12509. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12510. res.set_content("test", "text/plain");
  12511. ssl_svr.stop();
  12512. });
  12513. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12514. thread t2 =
  12515. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12516. auto se = detail::scope_exit([&] {
  12517. t2.join();
  12518. t.join();
  12519. ASSERT_FALSE(svr.is_running());
  12520. });
  12521. svr.wait_until_ready();
  12522. ssl_svr.wait_until_ready();
  12523. Client cli("127.0.0.1", PORT);
  12524. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12525. cli.enable_server_certificate_verification(true);
  12526. cli.set_follow_location(true);
  12527. cli.set_connection_timeout(30);
  12528. auto res = cli.Get("/index");
  12529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12530. ASSERT_EQ(StatusCode::OK_200, res->status);
  12531. }
  12532. TEST(SSLClientRedirectTest, CertFile) {
  12533. auto ssl_port = PORT + 1;
  12534. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12535. ASSERT_TRUE(ssl_svr1.is_valid());
  12536. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12537. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12538. "/index");
  12539. ssl_svr1.stop();
  12540. });
  12541. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12542. ASSERT_TRUE(ssl_svr2.is_valid());
  12543. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12544. res.set_content("test", "text/plain");
  12545. ssl_svr2.stop();
  12546. });
  12547. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12548. thread t2 =
  12549. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12550. auto se = detail::scope_exit([&] {
  12551. t2.join();
  12552. t.join();
  12553. ASSERT_FALSE(ssl_svr1.is_running());
  12554. });
  12555. ssl_svr1.wait_until_ready();
  12556. ssl_svr2.wait_until_ready();
  12557. SSLClient cli("127.0.0.1", PORT);
  12558. std::string cert;
  12559. read_file(SERVER_CERT2_FILE, cert);
  12560. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12561. cli.enable_server_certificate_verification(true);
  12562. cli.set_follow_location(true);
  12563. cli.set_connection_timeout(30);
  12564. auto res = cli.Get("/index");
  12565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12566. ASSERT_EQ(StatusCode::OK_200, res->status);
  12567. }
  12568. #endif
  12569. #ifdef CPPHTTPLIB_SSL_ENABLED
  12570. // Test that set_ca_cert_store() skips system certs (consistent with
  12571. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12572. // should be trusted - system certs should NOT be loaded.
  12573. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12574. // Load a specific cert that is NOT a system CA cert
  12575. std::string cert;
  12576. read_file(SERVER_CERT2_FILE, cert);
  12577. SSLClient cli("google.com");
  12578. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12579. cli.enable_server_certificate_verification(true);
  12580. // This should FAIL because:
  12581. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12582. // 2. System certs should NOT be loaded when custom store is set
  12583. // If system certs WERE loaded, this would succeed
  12584. auto res = cli.Get("/");
  12585. ASSERT_FALSE(res);
  12586. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12587. }
  12588. // Same as above, but through the native store handle path. Regression test:
  12589. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12590. // merged system certs into the user-provided store.
  12591. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12592. std::string cert;
  12593. read_file(SERVER_CERT2_FILE, cert);
  12594. SSLClient cli("google.com");
  12595. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12596. cli.enable_server_certificate_verification(true);
  12597. auto res = cli.Get("/");
  12598. ASSERT_FALSE(res);
  12599. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12600. }
  12601. // A custom store set via the native handle must still verify a server whose
  12602. // cert it does contain.
  12603. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12604. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12605. ASSERT_TRUE(svr.is_valid());
  12606. svr.Get("/test", [&](const Request &, Response &res) {
  12607. res.set_content("test", "text/plain");
  12608. });
  12609. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12610. auto se = detail::scope_exit([&] {
  12611. svr.stop();
  12612. t.join();
  12613. ASSERT_FALSE(svr.is_running());
  12614. });
  12615. svr.wait_until_ready();
  12616. SSLClient cli("127.0.0.1", PORT);
  12617. std::string cert;
  12618. read_file(SERVER_CERT2_FILE, cert);
  12619. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12620. cli.enable_server_certificate_verification(true);
  12621. cli.set_connection_timeout(30);
  12622. auto res = cli.Get("/test");
  12623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12624. ASSERT_EQ(StatusCode::OK_200, res->status);
  12625. }
  12626. // CA certs loaded through the universal Client must be transferred to the
  12627. // client created internally for following an HTTPS redirect. Regression test:
  12628. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12629. // the CA data for redirect transfer.
  12630. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12631. auto ssl_port = PORT + 1;
  12632. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12633. ASSERT_TRUE(ssl_svr1.is_valid());
  12634. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12635. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12636. "/index");
  12637. });
  12638. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12639. ASSERT_TRUE(ssl_svr2.is_valid());
  12640. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12641. res.set_content("test", "text/plain");
  12642. });
  12643. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12644. thread t2 =
  12645. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12646. auto se = detail::scope_exit([&] {
  12647. ssl_svr2.stop();
  12648. ssl_svr1.stop();
  12649. t2.join();
  12650. t.join();
  12651. ASSERT_FALSE(ssl_svr1.is_running());
  12652. });
  12653. ssl_svr1.wait_until_ready();
  12654. ssl_svr2.wait_until_ready();
  12655. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12656. std::string cert;
  12657. read_file(SERVER_CERT2_FILE, cert);
  12658. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12659. cli.enable_server_certificate_verification(true);
  12660. cli.set_follow_location(true);
  12661. cli.set_connection_timeout(30);
  12662. auto res = cli.Get("/index");
  12663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12664. ASSERT_EQ(StatusCode::OK_200, res->status);
  12665. }
  12666. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  12667. // so a host signed by a system CA verifies even though a custom CA is set
  12668. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  12669. std::string cert;
  12670. read_file(SERVER_CERT2_FILE, cert);
  12671. SSLClient cli("google.com");
  12672. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12673. cli.enable_system_ca(true);
  12674. cli.enable_server_certificate_verification(true);
  12675. auto res = cli.Get("/");
  12676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12677. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12678. }
  12679. // The custom CA remains effective when combined with the system CA
  12680. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  12681. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12682. ASSERT_TRUE(svr.is_valid());
  12683. svr.Get("/test", [&](const Request &, Response &res) {
  12684. res.set_content("test", "text/plain");
  12685. });
  12686. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12687. auto se = detail::scope_exit([&] {
  12688. svr.stop();
  12689. t.join();
  12690. ASSERT_FALSE(svr.is_running());
  12691. });
  12692. svr.wait_until_ready();
  12693. SSLClient cli("127.0.0.1", PORT);
  12694. std::string cert;
  12695. read_file(SERVER_CERT2_FILE, cert);
  12696. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12697. cli.enable_system_ca(true);
  12698. cli.enable_server_certificate_verification(true);
  12699. cli.set_connection_timeout(30);
  12700. auto res = cli.Get("/test");
  12701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12702. ASSERT_EQ(StatusCode::OK_200, res->status);
  12703. }
  12704. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  12705. // skip chain verification entirely (only the certificate identity was
  12706. // checked), so a server presenting an untrusted certificate with a matching
  12707. // IP SAN was accepted. The chain must be validated for IP hosts too.
  12708. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  12709. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12710. ASSERT_TRUE(svr.is_valid());
  12711. svr.Get("/test", [&](const Request &, Response &res) {
  12712. res.set_content("test", "text/plain");
  12713. });
  12714. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12715. auto se = detail::scope_exit([&] {
  12716. svr.stop();
  12717. t.join();
  12718. ASSERT_FALSE(svr.is_running());
  12719. });
  12720. svr.wait_until_ready();
  12721. SSLClient cli("127.0.0.1", PORT);
  12722. std::string cert;
  12723. // A trusted CA that did not sign the server certificate. The server cert
  12724. // (cert2) carries the matching IP SAN, so only chain validation can reject
  12725. // this connection.
  12726. read_file(CLIENT_CA_CERT_FILE, cert);
  12727. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12728. cli.enable_server_certificate_verification(true);
  12729. cli.set_connection_timeout(30);
  12730. auto res = cli.Get("/test");
  12731. ASSERT_FALSE(res);
  12732. }
  12733. // enable_system_ca(false) prevents system CA loading entirely
  12734. TEST(SSLClientTest, DisableSystemCa_Online) {
  12735. SSLClient cli("google.com");
  12736. cli.enable_system_ca(false);
  12737. cli.enable_server_certificate_verification(true);
  12738. auto res = cli.Get("/");
  12739. ASSERT_FALSE(res);
  12740. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  12741. // itself when the CA chain is empty
  12742. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12743. res.error() == Error::SSLConnection);
  12744. }
  12745. // The universal Client forwards enable_system_ca()
  12746. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  12747. std::string cert;
  12748. read_file(SERVER_CERT2_FILE, cert);
  12749. Client cli("https://google.com");
  12750. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12751. cli.enable_system_ca(true);
  12752. cli.enable_server_certificate_verification(true);
  12753. auto res = cli.Get("/");
  12754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12755. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12756. }
  12757. // The system CA policy must carry over to the client created internally for
  12758. // following a cross-host HTTPS redirect
  12759. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  12760. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12761. ASSERT_TRUE(svr.is_valid());
  12762. svr.Get("/index", [&](const Request &, Response &res) {
  12763. res.set_redirect("https://www.google.com/");
  12764. });
  12765. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12766. auto se = detail::scope_exit([&] {
  12767. svr.stop();
  12768. t.join();
  12769. ASSERT_FALSE(svr.is_running());
  12770. });
  12771. svr.wait_until_ready();
  12772. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12773. std::string cert;
  12774. read_file(SERVER_CERT2_FILE, cert);
  12775. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12776. cli.enable_system_ca(true);
  12777. cli.enable_server_certificate_verification(true);
  12778. cli.set_follow_location(true);
  12779. cli.set_connection_timeout(30);
  12780. // Receiving any response proves the redirect client completed the TLS
  12781. // handshake with a system-CA-signed host
  12782. auto res = cli.Get("/index");
  12783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12784. }
  12785. TEST(MultipartFormDataTest, LargeData) {
  12786. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12787. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  12788. const ContentReader &content_reader) {
  12789. if (req.is_multipart_form_data()) {
  12790. std::vector<FormData> items;
  12791. content_reader(
  12792. [&](const FormData &file) {
  12793. items.push_back(file);
  12794. return true;
  12795. },
  12796. [&](const char *data, size_t data_length) {
  12797. items.back().content.append(data, data_length);
  12798. return true;
  12799. });
  12800. EXPECT_TRUE(std::string(items[0].name) == "document");
  12801. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12802. EXPECT_TRUE(items[0].filename == "2MB_data");
  12803. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12804. EXPECT_TRUE(items[1].name == "hello");
  12805. EXPECT_TRUE(items[1].content == "world");
  12806. EXPECT_TRUE(items[1].filename == "");
  12807. EXPECT_TRUE(items[1].content_type == "");
  12808. } else {
  12809. std::string body;
  12810. content_reader([&](const char *data, size_t data_length) {
  12811. body.append(data, data_length);
  12812. return true;
  12813. });
  12814. }
  12815. });
  12816. auto port = svr.bind_to_any_port(HOST);
  12817. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12818. auto se = detail::scope_exit([&] {
  12819. svr.stop();
  12820. t.join();
  12821. ASSERT_FALSE(svr.is_running());
  12822. });
  12823. svr.wait_until_ready();
  12824. {
  12825. std::string data(1024 * 1024 * 2, '.');
  12826. std::stringstream buffer;
  12827. buffer << data;
  12828. SSLClient cli(HOST, port);
  12829. cli.enable_server_certificate_verification(false);
  12830. UploadFormDataItems items{
  12831. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12832. {"hello", "world", "", ""},
  12833. };
  12834. auto res = cli.Post("/post", items);
  12835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12836. ASSERT_EQ(StatusCode::OK_200, res->status);
  12837. }
  12838. }
  12839. TEST(MultipartFormDataTest, DataProviderItems) {
  12840. std::random_device seed_gen;
  12841. std::mt19937 random(seed_gen());
  12842. std::string rand1;
  12843. rand1.resize(1000);
  12844. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  12845. std::string rand2;
  12846. rand2.resize(3000);
  12847. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  12848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12849. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  12850. const ContentReader &content_reader) {
  12851. ASSERT_FALSE(req.is_multipart_form_data());
  12852. std::string body;
  12853. content_reader([&](const char *data, size_t data_length) {
  12854. body.append(data, data_length);
  12855. return true;
  12856. });
  12857. EXPECT_EQ(body, "");
  12858. });
  12859. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  12860. const ContentReader &content_reader) {
  12861. ASSERT_TRUE(req.is_multipart_form_data());
  12862. std::vector<FormData> items;
  12863. content_reader(
  12864. [&](const FormData &file) {
  12865. items.push_back(file);
  12866. return true;
  12867. },
  12868. [&](const char *data, size_t data_length) {
  12869. items.back().content.append(data, data_length);
  12870. return true;
  12871. });
  12872. ASSERT_TRUE(items.size() == 2);
  12873. EXPECT_EQ(std::string(items[0].name), "name1");
  12874. EXPECT_EQ(items[0].content, "Testing123");
  12875. EXPECT_EQ(items[0].filename, "filename1");
  12876. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12877. EXPECT_EQ(items[1].name, "name2");
  12878. EXPECT_EQ(items[1].content, "Testing456");
  12879. EXPECT_EQ(items[1].filename, "");
  12880. EXPECT_EQ(items[1].content_type, "");
  12881. });
  12882. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  12883. const ContentReader &content_reader) {
  12884. ASSERT_TRUE(req.is_multipart_form_data());
  12885. std::vector<FormData> items;
  12886. content_reader(
  12887. [&](const FormData &file) {
  12888. items.push_back(file);
  12889. return true;
  12890. },
  12891. [&](const char *data, size_t data_length) {
  12892. items.back().content.append(data, data_length);
  12893. return true;
  12894. });
  12895. ASSERT_TRUE(items.size() == 2);
  12896. EXPECT_EQ(items[0].name, "name3");
  12897. EXPECT_EQ(items[0].content, rand1);
  12898. EXPECT_EQ(items[0].filename, "filename3");
  12899. EXPECT_EQ(items[0].content_type, "");
  12900. EXPECT_EQ(items[1].name, "name4");
  12901. EXPECT_EQ(items[1].content, rand2);
  12902. EXPECT_EQ(items[1].filename, "filename4");
  12903. EXPECT_EQ(items[1].content_type, "");
  12904. });
  12905. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  12906. const ContentReader &content_reader) {
  12907. ASSERT_TRUE(req.is_multipart_form_data());
  12908. std::vector<FormData> items;
  12909. content_reader(
  12910. [&](const FormData &file) {
  12911. items.push_back(file);
  12912. return true;
  12913. },
  12914. [&](const char *data, size_t data_length) {
  12915. items.back().content.append(data, data_length);
  12916. return true;
  12917. });
  12918. ASSERT_TRUE(items.size() == 4);
  12919. EXPECT_EQ(std::string(items[0].name), "name1");
  12920. EXPECT_EQ(items[0].content, "Testing123");
  12921. EXPECT_EQ(items[0].filename, "filename1");
  12922. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12923. EXPECT_EQ(items[1].name, "name2");
  12924. EXPECT_EQ(items[1].content, "Testing456");
  12925. EXPECT_EQ(items[1].filename, "");
  12926. EXPECT_EQ(items[1].content_type, "");
  12927. EXPECT_EQ(items[2].name, "name3");
  12928. EXPECT_EQ(items[2].content, rand1);
  12929. EXPECT_EQ(items[2].filename, "filename3");
  12930. EXPECT_EQ(items[2].content_type, "");
  12931. EXPECT_EQ(items[3].name, "name4");
  12932. EXPECT_EQ(items[3].content, rand2);
  12933. EXPECT_EQ(items[3].filename, "filename4");
  12934. EXPECT_EQ(items[3].content_type, "");
  12935. });
  12936. auto port = svr.bind_to_any_port("localhost");
  12937. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12938. auto se = detail::scope_exit([&] {
  12939. svr.stop();
  12940. t.join();
  12941. ASSERT_FALSE(svr.is_running());
  12942. });
  12943. svr.wait_until_ready();
  12944. {
  12945. SSLClient cli("localhost", port);
  12946. cli.enable_server_certificate_verification(false);
  12947. UploadFormDataItems items{
  12948. {"name1", "Testing123", "filename1", "application/octet-stream"},
  12949. {"name2", "Testing456", "", ""}, // not a file
  12950. };
  12951. {
  12952. auto res = cli.Post("/post-none", {}, {}, {});
  12953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12954. ASSERT_EQ(StatusCode::OK_200, res->status);
  12955. }
  12956. FormDataProviderItems providers;
  12957. {
  12958. auto res =
  12959. cli.Post("/post-items", {}, items, providers); // empty providers
  12960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12961. ASSERT_EQ(StatusCode::OK_200, res->status);
  12962. }
  12963. providers.push_back({"name3",
  12964. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12965. // test the offset is given correctly at each step
  12966. if (!offset)
  12967. sink.os.write(rand1.data(), 30);
  12968. else if (offset == 30)
  12969. sink.os.write(rand1.data() + 30, 300);
  12970. else if (offset == 330)
  12971. sink.os.write(rand1.data() + 330, 670);
  12972. else if (offset == rand1.size())
  12973. sink.done();
  12974. return true;
  12975. },
  12976. "filename3",
  12977. {}});
  12978. providers.push_back({"name4",
  12979. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12980. // test the offset is given correctly at each step
  12981. if (!offset)
  12982. sink.os.write(rand2.data(), 2000);
  12983. else if (offset == 2000)
  12984. sink.os.write(rand2.data() + 2000, 1);
  12985. else if (offset == 2001)
  12986. sink.os.write(rand2.data() + 2001, 999);
  12987. else if (offset == rand2.size())
  12988. sink.done();
  12989. return true;
  12990. },
  12991. "filename4",
  12992. {}});
  12993. {
  12994. auto res = cli.Post("/post-providers", {}, {}, providers);
  12995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12996. ASSERT_EQ(StatusCode::OK_200, res->status);
  12997. }
  12998. {
  12999. auto res = cli.Post("/post-both", {}, items, providers);
  13000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13001. ASSERT_EQ(StatusCode::OK_200, res->status);
  13002. }
  13003. }
  13004. }
  13005. TEST(MultipartFormDataTest, BadHeader) {
  13006. Server svr;
  13007. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13008. res.set_content("ok", "text/plain");
  13009. });
  13010. thread t = thread([&] { svr.listen(HOST, PORT); });
  13011. auto se = detail::scope_exit([&] {
  13012. svr.stop();
  13013. t.join();
  13014. ASSERT_FALSE(svr.is_running());
  13015. });
  13016. svr.wait_until_ready();
  13017. const std::string body =
  13018. "This is the preamble. It is to be ignored, though it\r\n"
  13019. "is a handy place for composition agents to include an\r\n"
  13020. "explanatory note to non-MIME conformant readers.\r\n"
  13021. "\r\n"
  13022. "\r\n"
  13023. "--simple boundary\r\n"
  13024. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13025. ": BAD...\r\n"
  13026. "\r\n"
  13027. "value1\r\n"
  13028. "--simple boundary\r\n"
  13029. "Content-Disposition: form-data; name=\"field2\"; "
  13030. "filename=\"example.txt\"\r\n"
  13031. "\r\n"
  13032. "value2\r\n"
  13033. "--simple boundary--\r\n"
  13034. "This is the epilogue. It is also to be ignored.\r\n";
  13035. std::string content_type =
  13036. R"(multipart/form-data; boundary="simple boundary")";
  13037. Client cli(HOST, PORT);
  13038. auto res = cli.Post("/post", body, content_type.c_str());
  13039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13040. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13041. }
  13042. TEST(MultipartFormDataTest, WithPreamble) {
  13043. Server svr;
  13044. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13045. res.set_content("ok", "text/plain");
  13046. });
  13047. thread t = thread([&] { svr.listen(HOST, PORT); });
  13048. auto se = detail::scope_exit([&] {
  13049. svr.stop();
  13050. t.join();
  13051. ASSERT_FALSE(svr.is_running());
  13052. });
  13053. svr.wait_until_ready();
  13054. const std::string body =
  13055. "This is the preamble. It is to be ignored, though it\r\n"
  13056. "is a handy place for composition agents to include an\r\n"
  13057. "explanatory note to non-MIME conformant readers.\r\n"
  13058. "\r\n"
  13059. "\r\n"
  13060. "--simple boundary\r\n"
  13061. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13062. "\r\n"
  13063. "value1\r\n"
  13064. "--simple boundary\r\n"
  13065. "Content-Disposition: form-data; name=\"field2\"; "
  13066. "filename=\"example.txt\"\r\n"
  13067. "\r\n"
  13068. "value2\r\n"
  13069. "--simple boundary--\r\n"
  13070. "This is the epilogue. It is also to be ignored.\r\n";
  13071. std::string content_type =
  13072. R"(multipart/form-data; boundary="simple boundary")";
  13073. Client cli(HOST, PORT);
  13074. auto res = cli.Post("/post", body, content_type.c_str());
  13075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13076. EXPECT_EQ(StatusCode::OK_200, res->status);
  13077. }
  13078. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13079. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13080. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13081. const ContentReader &content_reader) {
  13082. if (req.is_multipart_form_data()) {
  13083. std::vector<FormData> items;
  13084. content_reader(
  13085. [&](const FormData &file) {
  13086. items.push_back(file);
  13087. return true;
  13088. },
  13089. [&](const char *data, size_t data_length) {
  13090. items.back().content.append(data, data_length);
  13091. return true;
  13092. });
  13093. EXPECT_TRUE(std::string(items[0].name) == "document");
  13094. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13095. EXPECT_TRUE(items[0].filename == "2MB_data");
  13096. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13097. EXPECT_TRUE(items[1].name == "hello");
  13098. EXPECT_TRUE(items[1].content == "world");
  13099. EXPECT_TRUE(items[1].filename == "");
  13100. EXPECT_TRUE(items[1].content_type == "");
  13101. } else {
  13102. std::string body;
  13103. content_reader([&](const char *data, size_t data_length) {
  13104. body.append(data, data_length);
  13105. return true;
  13106. });
  13107. }
  13108. });
  13109. auto port = svr.bind_to_any_port("localhost");
  13110. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13111. auto se = detail::scope_exit([&] {
  13112. svr.stop();
  13113. t.join();
  13114. ASSERT_FALSE(svr.is_running());
  13115. });
  13116. svr.wait_until_ready();
  13117. {
  13118. std::string data(1024 * 1024 * 2, '.');
  13119. std::stringstream buffer;
  13120. buffer << data;
  13121. SSLClient cli("localhost", port);
  13122. cli.enable_server_certificate_verification(false);
  13123. UploadFormDataItems items{
  13124. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13125. {"hello", "world", "", ""},
  13126. };
  13127. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13129. ASSERT_EQ(StatusCode::OK_200, res->status);
  13130. }
  13131. }
  13132. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13133. std::string data(1024 * 1024 * 2, '&');
  13134. std::stringstream buffer;
  13135. buffer << data;
  13136. Client cli("https://localhost:8080");
  13137. UploadFormDataItems items{
  13138. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13139. {"hello", "world", "", ""},
  13140. };
  13141. for (const char &c : " \t\r\n") {
  13142. auto res =
  13143. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13144. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13145. ASSERT_FALSE(res);
  13146. }
  13147. }
  13148. TEST(MultipartFormDataTest, PutFormData) {
  13149. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13150. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13151. const ContentReader &content_reader) {
  13152. if (req.is_multipart_form_data()) {
  13153. std::vector<FormData> items;
  13154. content_reader(
  13155. [&](const FormData &file) {
  13156. items.push_back(file);
  13157. return true;
  13158. },
  13159. [&](const char *data, size_t data_length) {
  13160. items.back().content.append(data, data_length);
  13161. return true;
  13162. });
  13163. EXPECT_TRUE(std::string(items[0].name) == "document");
  13164. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13165. EXPECT_TRUE(items[0].filename == "2MB_data");
  13166. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13167. EXPECT_TRUE(items[1].name == "hello");
  13168. EXPECT_TRUE(items[1].content == "world");
  13169. EXPECT_TRUE(items[1].filename == "");
  13170. EXPECT_TRUE(items[1].content_type == "");
  13171. } else {
  13172. std::string body;
  13173. content_reader([&](const char *data, size_t data_length) {
  13174. body.append(data, data_length);
  13175. return true;
  13176. });
  13177. }
  13178. });
  13179. auto port = svr.bind_to_any_port("localhost");
  13180. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13181. auto se = detail::scope_exit([&] {
  13182. svr.stop();
  13183. t.join();
  13184. ASSERT_FALSE(svr.is_running());
  13185. });
  13186. svr.wait_until_ready();
  13187. {
  13188. std::string data(1024 * 1024 * 2, '&');
  13189. std::stringstream buffer;
  13190. buffer << data;
  13191. SSLClient cli("localhost", port);
  13192. cli.enable_server_certificate_verification(false);
  13193. UploadFormDataItems items{
  13194. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13195. {"hello", "world", "", ""},
  13196. };
  13197. auto res = cli.Put("/put", items);
  13198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13199. ASSERT_EQ(StatusCode::OK_200, res->status);
  13200. }
  13201. }
  13202. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13203. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13204. svr.Put("/put_customboundary",
  13205. [&](const Request &req, const Response & /*res*/,
  13206. const ContentReader &content_reader) {
  13207. if (req.is_multipart_form_data()) {
  13208. std::vector<FormData> items;
  13209. content_reader(
  13210. [&](const FormData &file) {
  13211. items.push_back(file);
  13212. return true;
  13213. },
  13214. [&](const char *data, size_t data_length) {
  13215. items.back().content.append(data, data_length);
  13216. return true;
  13217. });
  13218. EXPECT_TRUE(std::string(items[0].name) == "document");
  13219. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13220. EXPECT_TRUE(items[0].filename == "2MB_data");
  13221. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13222. EXPECT_TRUE(items[1].name == "hello");
  13223. EXPECT_TRUE(items[1].content == "world");
  13224. EXPECT_TRUE(items[1].filename == "");
  13225. EXPECT_TRUE(items[1].content_type == "");
  13226. } else {
  13227. std::string body;
  13228. content_reader([&](const char *data, size_t data_length) {
  13229. body.append(data, data_length);
  13230. return true;
  13231. });
  13232. }
  13233. });
  13234. auto port = svr.bind_to_any_port("localhost");
  13235. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13236. auto se = detail::scope_exit([&] {
  13237. svr.stop();
  13238. t.join();
  13239. ASSERT_FALSE(svr.is_running());
  13240. });
  13241. svr.wait_until_ready();
  13242. {
  13243. std::string data(1024 * 1024 * 2, '&');
  13244. std::stringstream buffer;
  13245. buffer << data;
  13246. SSLClient cli("localhost", port);
  13247. cli.enable_server_certificate_verification(false);
  13248. UploadFormDataItems items{
  13249. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13250. {"hello", "world", "", ""},
  13251. };
  13252. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13254. ASSERT_EQ(StatusCode::OK_200, res->status);
  13255. }
  13256. }
  13257. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13258. std::string data(1024 * 1024 * 2, '&');
  13259. std::stringstream buffer;
  13260. buffer << data;
  13261. Client cli("https://localhost:8080");
  13262. cli.enable_server_certificate_verification(false);
  13263. UploadFormDataItems items{
  13264. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13265. {"hello", "world", "", ""},
  13266. };
  13267. for (const char &c : " \t\r\n") {
  13268. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13269. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13270. ASSERT_FALSE(res);
  13271. }
  13272. }
  13273. TEST(MultipartFormDataTest, AlternateFilename) {
  13274. auto handled = false;
  13275. Server svr;
  13276. svr.Post("/test", [&](const Request &req, Response &res) {
  13277. ASSERT_EQ(2u, req.form.files.size());
  13278. ASSERT_EQ(1u, req.form.fields.size());
  13279. // Test files
  13280. const auto &file1 = req.form.get_file("file1");
  13281. ASSERT_EQ("file1", file1.name);
  13282. ASSERT_EQ("A.txt", file1.filename);
  13283. ASSERT_EQ("text/plain", file1.content_type);
  13284. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13285. const auto &file2 = req.form.get_file("file2");
  13286. ASSERT_EQ("file2", file2.name);
  13287. ASSERT_EQ("a.html", file2.filename);
  13288. ASSERT_EQ("text/html", file2.content_type);
  13289. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13290. file2.content);
  13291. // Test text field
  13292. const auto &text = req.form.get_field("text");
  13293. ASSERT_EQ("text default", text);
  13294. res.set_content("ok", "text/plain");
  13295. handled = true;
  13296. });
  13297. thread t = thread([&] { svr.listen(HOST, PORT); });
  13298. auto se = detail::scope_exit([&] {
  13299. svr.stop();
  13300. t.join();
  13301. ASSERT_FALSE(svr.is_running());
  13302. ASSERT_TRUE(handled);
  13303. });
  13304. svr.wait_until_ready();
  13305. auto req = "POST /test HTTP/1.1\r\n"
  13306. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13307. "Content-Length: 399\r\n"
  13308. "\r\n"
  13309. "----------\r\n"
  13310. "Content-Disposition: form-data; name=\"text\"\r\n"
  13311. "\r\n"
  13312. "text default\r\n"
  13313. "----------\r\n"
  13314. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13315. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13316. "Content-Type: text/plain\r\n"
  13317. "\r\n"
  13318. "Content of a.txt.\r\n"
  13319. "\r\n"
  13320. "----------\r\n"
  13321. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13322. "\"a.html\"\r\n"
  13323. "Content-Type: text/html\r\n"
  13324. "\r\n"
  13325. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13326. "\r\n"
  13327. "------------\r\n";
  13328. ASSERT_TRUE(send_request(1, req));
  13329. }
  13330. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13331. auto handled = false;
  13332. Server svr;
  13333. svr.Post("/test", [&](const Request &req, Response &res) {
  13334. // Case-insensitive "utf-8''" prefix with a long value
  13335. const auto &file = req.form.get_file("file1");
  13336. ASSERT_EQ("file1", file.name);
  13337. // 8000 chars exercises both the Content-Disposition parser and the
  13338. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13339. // Prior to the fix, std::regex_match on this header would cause O(N)
  13340. // stack recursion in libstdc++, leading to SIGSEGV.
  13341. std::string expected_filename(8000, 'A');
  13342. ASSERT_EQ(expected_filename, file.filename);
  13343. res.set_content("ok", "text/plain");
  13344. handled = true;
  13345. });
  13346. thread t = thread([&] { svr.listen(HOST, PORT); });
  13347. auto se = detail::scope_exit([&] {
  13348. svr.stop();
  13349. t.join();
  13350. ASSERT_FALSE(svr.is_running());
  13351. ASSERT_TRUE(handled);
  13352. });
  13353. svr.wait_until_ready();
  13354. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13355. // Regression test for GHSA-qq6v-r583-3h69
  13356. std::string long_filename(8000, 'A');
  13357. std::string body = "----------\r\n"
  13358. "Content-Disposition: form-data; name=\"file1\"; "
  13359. "filename*=\"Utf-8''" +
  13360. long_filename +
  13361. "\"\r\n"
  13362. "\r\n"
  13363. "hello\r\n"
  13364. "------------\r\n";
  13365. auto req = "POST /test HTTP/1.1\r\n"
  13366. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13367. "Content-Length: " +
  13368. std::to_string(body.size()) + "\r\n\r\n" + body;
  13369. ASSERT_TRUE(send_request(1, req));
  13370. }
  13371. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13372. auto handled = false;
  13373. Server svr;
  13374. svr.Post("/test", [&](const Request &req, Response &) {
  13375. ASSERT_EQ(2u, req.form.fields.size());
  13376. const auto &text1 = req.form.get_field("text1");
  13377. ASSERT_EQ("text1", text1);
  13378. const auto &text2 = req.form.get_field("text2");
  13379. ASSERT_EQ("text2", text2);
  13380. handled = true;
  13381. });
  13382. thread t = thread([&] { svr.listen(HOST, PORT); });
  13383. auto se = detail::scope_exit([&] {
  13384. svr.stop();
  13385. t.join();
  13386. ASSERT_FALSE(svr.is_running());
  13387. ASSERT_TRUE(handled);
  13388. });
  13389. svr.wait_until_ready();
  13390. auto req = "POST /test HTTP/1.1\r\n"
  13391. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13392. "Content-Length: 146\r\n"
  13393. "\r\n----------\r\n"
  13394. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13395. "\r\n"
  13396. "text1"
  13397. "\r\n----------\r\n"
  13398. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13399. "\r\n"
  13400. "text2"
  13401. "\r\n------------";
  13402. std::string response;
  13403. ASSERT_TRUE(send_request(1, req, &response));
  13404. ASSERT_EQ("200", response.substr(9, 3));
  13405. }
  13406. TEST(MultipartFormDataTest, ContentLength) {
  13407. auto handled = false;
  13408. Server svr;
  13409. svr.Post("/test", [&](const Request &req, Response &) {
  13410. ASSERT_EQ(2u, req.form.fields.size());
  13411. const auto &text1 = req.form.get_field("text1");
  13412. ASSERT_EQ("text1", text1);
  13413. const auto &text2 = req.form.get_field("text2");
  13414. ASSERT_EQ("text2", text2);
  13415. handled = true;
  13416. });
  13417. thread t = thread([&] { svr.listen(HOST, PORT); });
  13418. auto se = detail::scope_exit([&] {
  13419. svr.stop();
  13420. t.join();
  13421. ASSERT_FALSE(svr.is_running());
  13422. ASSERT_TRUE(handled);
  13423. });
  13424. svr.wait_until_ready();
  13425. auto req = "POST /test HTTP/1.1\r\n"
  13426. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13427. "Content-Length: 167\r\n"
  13428. "\r\n----------\r\n"
  13429. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13430. "Content-Length: 5\r\n"
  13431. "\r\n"
  13432. "text1"
  13433. "\r\n----------\r\n"
  13434. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13435. "\r\n"
  13436. "text2"
  13437. "\r\n------------\r\n";
  13438. std::string response;
  13439. ASSERT_TRUE(send_request(1, req, &response));
  13440. ASSERT_EQ("200", response.substr(9, 3));
  13441. }
  13442. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13443. auto handled = false;
  13444. Server svr;
  13445. svr.Post("/test", [&](const Request &req, Response &) {
  13446. ASSERT_EQ(2u, req.form.fields.size());
  13447. const auto &text1 = req.form.get_field("text1");
  13448. ASSERT_EQ("text1", text1);
  13449. // TODO: Add header access for text fields if needed
  13450. const auto &text2 = req.form.get_field("text2");
  13451. ASSERT_EQ("text2", text2);
  13452. // TODO: Header access for text fields needs to be implemented
  13453. // auto &headers = it->second.headers;
  13454. // ASSERT_EQ(3U, headers.size());
  13455. // auto custom_header = headers.find("x-whatever");
  13456. // ASSERT_TRUE(custom_header != headers.end());
  13457. // ASSERT_NE("customvalue", custom_header->second);
  13458. // ASSERT_EQ("CustomValue", custom_header->second);
  13459. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13460. handled = true;
  13461. });
  13462. thread t = thread([&] { svr.listen(HOST, PORT); });
  13463. auto se = detail::scope_exit([&] {
  13464. svr.stop();
  13465. t.join();
  13466. ASSERT_FALSE(svr.is_running());
  13467. ASSERT_TRUE(handled);
  13468. });
  13469. svr.wait_until_ready();
  13470. auto req = "POST /test HTTP/1.1\r\n"
  13471. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13472. "Content-Length: 232\r\n"
  13473. "\r\n----------\r\n"
  13474. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13475. "Content-Length: 5\r\n"
  13476. "X-Test: 1\r\n"
  13477. "\r\n"
  13478. "text1"
  13479. "\r\n----------\r\n"
  13480. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13481. "Content-Type: text/plain\r\n"
  13482. "X-Whatever: CustomValue\r\n"
  13483. "\r\n"
  13484. "text2"
  13485. "\r\n------------\r\n"
  13486. "That should be disregarded. Not even read";
  13487. std::string response;
  13488. ASSERT_TRUE(send_request(1, req, &response));
  13489. ASSERT_EQ("200", response.substr(9, 3));
  13490. }
  13491. TEST(MultipartFormDataTest, LargeHeader) {
  13492. auto handled = false;
  13493. Server svr;
  13494. svr.Post("/test", [&](const Request &req, Response &) {
  13495. ASSERT_EQ(1u, req.form.fields.size());
  13496. const auto &text = req.form.get_field("name1");
  13497. ASSERT_EQ("text1", text);
  13498. handled = true;
  13499. });
  13500. thread t = thread([&] { svr.listen(HOST, PORT); });
  13501. auto se = detail::scope_exit([&] {
  13502. svr.stop();
  13503. t.join();
  13504. ASSERT_FALSE(svr.is_running());
  13505. ASSERT_TRUE(handled);
  13506. });
  13507. svr.wait_until_ready();
  13508. auto boundary = std::string("cpp-httplib-multipart-data");
  13509. std::string content = "--" + boundary +
  13510. "\r\n"
  13511. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13512. "\r\n"
  13513. "text1\r\n"
  13514. "--" +
  13515. boundary + "--\r\n";
  13516. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13517. "Content-Type: multipart/form-data;boundary=" +
  13518. boundary +
  13519. "\r\n"
  13520. "Content-Length: " +
  13521. std::to_string(content.size()) +
  13522. "\r\n"
  13523. "Dummy-Header: ";
  13524. std::string header_suffix = "\r\n"
  13525. "\r\n";
  13526. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13527. size_t header_dummy_size =
  13528. read_buff_size -
  13529. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13530. auto header_dummy = std::string(header_dummy_size, '@');
  13531. auto req = header_prefix + header_dummy + header_suffix + content;
  13532. std::string response;
  13533. ASSERT_TRUE(send_request(1, req, &response));
  13534. ASSERT_EQ("200", response.substr(9, 3));
  13535. }
  13536. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13537. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13538. // (not chunked Transfer-Encoding) after the streaming refactor.
  13539. auto handled = false;
  13540. Server svr;
  13541. svr.Post("/upload", [&](const Request &req, Response &res) {
  13542. auto cl_it = req.headers.find("Content-Length");
  13543. EXPECT_TRUE(cl_it != req.headers.end());
  13544. auto te_it = req.headers.find("Transfer-Encoding");
  13545. EXPECT_TRUE(te_it == req.headers.end());
  13546. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13547. res.set_content("ok", "text/plain");
  13548. handled = true;
  13549. });
  13550. auto port = svr.bind_to_any_port(HOST);
  13551. auto t = thread([&] { svr.listen_after_bind(); });
  13552. auto se = detail::scope_exit([&] {
  13553. svr.stop();
  13554. t.join();
  13555. ASSERT_FALSE(svr.is_running());
  13556. ASSERT_TRUE(handled);
  13557. });
  13558. svr.wait_until_ready();
  13559. UploadFormDataItems items = {
  13560. {"field1", "hello", "", "text/plain"},
  13561. {"file1", "world", "test.txt", "application/octet-stream"},
  13562. };
  13563. Client cli(HOST, port);
  13564. auto res = cli.Post("/upload", {}, items);
  13565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13566. EXPECT_EQ(StatusCode::OK_200, res->status);
  13567. }
  13568. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13569. // Verify that make_multipart_content_provider coalesces many small segments
  13570. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13571. constexpr size_t kItemCount = 1000;
  13572. UploadFormDataItems items;
  13573. items.reserve(kItemCount);
  13574. for (size_t i = 0; i < kItemCount; i++) {
  13575. items.push_back(
  13576. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13577. }
  13578. const std::string boundary = "----test-boundary";
  13579. auto content_length = detail::get_multipart_content_length(items, boundary);
  13580. auto provider = detail::make_multipart_content_provider(items, boundary);
  13581. // Drive the provider the same way write_content_with_progress does
  13582. size_t write_count = 0;
  13583. size_t total_bytes = 0;
  13584. DataSink sink;
  13585. size_t offset = 0;
  13586. sink.write = [&](const char *d, size_t l) -> bool {
  13587. (void)d;
  13588. write_count++;
  13589. total_bytes += l;
  13590. offset += l;
  13591. return true;
  13592. };
  13593. sink.is_writable = []() -> bool { return true; };
  13594. while (offset < content_length) {
  13595. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13596. }
  13597. EXPECT_EQ(content_length, total_bytes);
  13598. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13599. // With buffering into 64KB blocks, write_count should be much smaller.
  13600. auto segment_count = 3 * kItemCount + 1;
  13601. EXPECT_LT(write_count, segment_count / 10);
  13602. }
  13603. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13604. // Integration test: send many UploadFormDataItems and verify the server
  13605. // receives all of them correctly (#2410).
  13606. constexpr size_t kItemCount = 500;
  13607. auto handled = false;
  13608. Server svr;
  13609. svr.Post("/upload", [&](const Request &req, Response &res) {
  13610. EXPECT_EQ(kItemCount, req.form.fields.size());
  13611. for (size_t i = 0; i < kItemCount; i++) {
  13612. auto key = "field" + std::to_string(i);
  13613. auto val = "value" + std::to_string(i);
  13614. auto it = req.form.fields.find(key);
  13615. if (it != req.form.fields.end()) {
  13616. EXPECT_EQ(val, it->second.content);
  13617. } else {
  13618. ADD_FAILURE() << "Missing field: " << key;
  13619. }
  13620. }
  13621. res.set_content("ok", "text/plain");
  13622. handled = true;
  13623. });
  13624. auto port = svr.bind_to_any_port(HOST);
  13625. auto t = thread([&] { svr.listen_after_bind(); });
  13626. auto se = detail::scope_exit([&] {
  13627. svr.stop();
  13628. t.join();
  13629. ASSERT_FALSE(svr.is_running());
  13630. ASSERT_TRUE(handled);
  13631. });
  13632. svr.wait_until_ready();
  13633. UploadFormDataItems items;
  13634. items.reserve(kItemCount);
  13635. for (size_t i = 0; i < kItemCount; i++) {
  13636. items.push_back(
  13637. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13638. }
  13639. Client cli(HOST, port);
  13640. auto res = cli.Post("/upload", items);
  13641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13642. EXPECT_EQ(StatusCode::OK_200, res->status);
  13643. }
  13644. TEST(MultipartFormDataTest, MakeFileProvider) {
  13645. // Verify make_file_provider sends a file's contents correctly.
  13646. const std::string file_content(4096, 'Z');
  13647. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13648. {
  13649. std::ofstream ofs(tmp_path, std::ios::binary);
  13650. ofs.write(file_content.data(),
  13651. static_cast<std::streamsize>(file_content.size()));
  13652. }
  13653. auto handled = false;
  13654. Server svr;
  13655. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13656. const ContentReader &content_reader) {
  13657. ASSERT_TRUE(req.is_multipart_form_data());
  13658. std::vector<FormData> items;
  13659. content_reader(
  13660. [&](const FormData &file) {
  13661. items.push_back(file);
  13662. return true;
  13663. },
  13664. [&](const char *data, size_t data_length) {
  13665. items.back().content.append(data, data_length);
  13666. return true;
  13667. });
  13668. ASSERT_EQ(1u, items.size());
  13669. EXPECT_EQ("myfile", items[0].name);
  13670. EXPECT_EQ("data.bin", items[0].filename);
  13671. EXPECT_EQ("application/octet-stream", items[0].content_type);
  13672. EXPECT_EQ(file_content, items[0].content);
  13673. handled = true;
  13674. });
  13675. auto port = svr.bind_to_any_port(HOST);
  13676. auto t = thread([&] { svr.listen_after_bind(); });
  13677. auto se = detail::scope_exit([&] {
  13678. svr.stop();
  13679. t.join();
  13680. ASSERT_FALSE(svr.is_running());
  13681. ASSERT_TRUE(handled);
  13682. std::remove(tmp_path.c_str());
  13683. });
  13684. svr.wait_until_ready();
  13685. FormDataProviderItems providers;
  13686. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  13687. "application/octet-stream"));
  13688. Client cli(HOST, port);
  13689. auto res = cli.Post("/upload", {}, {}, providers);
  13690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13691. EXPECT_EQ(StatusCode::OK_200, res->status);
  13692. }
  13693. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  13694. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  13695. // (100) headers is rejected with a 400 Bad Request response.
  13696. Server svr;
  13697. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13698. res.set_content("ok", "text/plain");
  13699. });
  13700. thread t = thread([&] { svr.listen(HOST, PORT); });
  13701. auto se = detail::scope_exit([&] {
  13702. svr.stop();
  13703. t.join();
  13704. ASSERT_FALSE(svr.is_running());
  13705. });
  13706. svr.wait_until_ready();
  13707. // Build a multipart part with 101 custom headers (exceeding
  13708. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  13709. std::stringstream body;
  13710. body << "--simpleboundary\r\n"
  13711. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  13712. for (int i = 0; i < 101; i++) {
  13713. body << "X-Custom-Header-" << i << ": value\r\n";
  13714. }
  13715. body << "\r\n"
  13716. << "value1\r\n"
  13717. << "--simpleboundary--\r\n";
  13718. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  13719. Client cli(HOST, PORT);
  13720. auto res = cli.Post("/post", body.str(), content_type.c_str());
  13721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13722. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13723. }
  13724. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  13725. // A body that never contains the declared boundary must not be accumulated
  13726. // while the parser waits for it. Buffering it would also make every read
  13727. // rescan everything seen so far, which is quadratic in the body size.
  13728. Server svr;
  13729. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13730. res.set_content("ok", "text/plain");
  13731. });
  13732. auto port = svr.bind_to_any_port(HOST);
  13733. thread t = thread([&] { svr.listen_after_bind(); });
  13734. auto se = detail::scope_exit([&] {
  13735. svr.stop();
  13736. t.join();
  13737. ASSERT_FALSE(svr.is_running());
  13738. });
  13739. svr.wait_until_ready();
  13740. Client cli(HOST, port);
  13741. cli.set_read_timeout(60, 0);
  13742. cli.set_write_timeout(60, 0);
  13743. // '-' is the worst case: it matches the first character of the boundary, so
  13744. // every position has to be checked against it.
  13745. auto post_dashes = [&](size_t size) {
  13746. const std::string body(size, '-');
  13747. auto start = std::chrono::steady_clock::now();
  13748. auto res =
  13749. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  13750. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  13751. std::chrono::steady_clock::now() - start)
  13752. .count();
  13753. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  13754. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  13755. return ms;
  13756. };
  13757. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  13758. // Windows.
  13759. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  13760. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  13761. // Comparing the two sizes rather than checking an absolute duration keeps
  13762. // this meaningful across build types and CI load, both of which move the
  13763. // absolute numbers by more than an order of magnitude. Four times the bytes
  13764. // costs about four times the time when parsing is linear, and about sixteen
  13765. // times when the body is buffered and rescanned.
  13766. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  13767. EXPECT_LT(ms_16mb, ms_4mb * 10)
  13768. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  13769. << "ms, which suggests the body is being buffered and rescanned";
  13770. }
  13771. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  13772. // A boundary can only be followed by CRLF or by "--", so anything else is
  13773. // malformed no matter what comes next. The parser must say so right away
  13774. // instead of buffering the rest of the declared body.
  13775. Server svr;
  13776. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13777. res.set_content("ok", "text/plain");
  13778. });
  13779. auto port = svr.bind_to_any_port(HOST);
  13780. thread t = thread([&] { svr.listen_after_bind(); });
  13781. auto se = detail::scope_exit([&] {
  13782. svr.stop();
  13783. t.join();
  13784. ASSERT_FALSE(svr.is_running());
  13785. });
  13786. svr.wait_until_ready();
  13787. // Announce a 1 MB body but send only the malformed prefix. A parser that
  13788. // buffers instead of failing would still be waiting for the remaining bytes.
  13789. const std::string body = "--zzzz\r\n"
  13790. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13791. "\r\n"
  13792. "text1"
  13793. "\r\n--zzzzXX";
  13794. const std::string req = "POST /post HTTP/1.1\r\n"
  13795. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13796. "Content-Length: 1048576\r\n"
  13797. "\r\n" +
  13798. body;
  13799. std::string response;
  13800. ASSERT_TRUE(send_request(3, req, &response, port));
  13801. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  13802. EXPECT_EQ("400", response.substr(9, 3));
  13803. }
  13804. // Posts a multipart body split into two writes, so that the server sees the
  13805. // split at whatever offset the caller chose, and expects the single "text1"
  13806. // field to come through.
  13807. static void expect_split_multipart_ok(const std::string &body1,
  13808. const std::string &body2) {
  13809. auto handled = false;
  13810. Server svr;
  13811. svr.Post("/post", [&](const Request &req, Response &) {
  13812. EXPECT_EQ(1u, req.form.fields.size());
  13813. EXPECT_EQ("text1", req.form.get_field("text1"));
  13814. handled = true;
  13815. });
  13816. auto port = svr.bind_to_any_port(HOST);
  13817. thread t = thread([&] { svr.listen_after_bind(); });
  13818. auto se = detail::scope_exit([&] {
  13819. svr.stop();
  13820. t.join();
  13821. ASSERT_FALSE(svr.is_running());
  13822. ASSERT_TRUE(handled);
  13823. });
  13824. svr.wait_until_ready();
  13825. // "Connection: close" makes the server close once it has answered, so the
  13826. // response drain ends immediately instead of idling until the read timeout.
  13827. const std::string head =
  13828. "POST /post HTTP/1.1\r\n"
  13829. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13830. "Connection: close\r\n"
  13831. "Content-Length: " +
  13832. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  13833. std::string response;
  13834. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  13835. ASSERT_GE(response.size(), 12u) << "no response";
  13836. EXPECT_EQ("200", response.substr(9, 3));
  13837. }
  13838. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  13839. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  13840. // ignored, including when it does not arrive in the same read as the
  13841. // close-delimiter itself.
  13842. expect_split_multipart_ok("--zzzz\r\n"
  13843. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13844. "\r\n"
  13845. "text1"
  13846. "\r\n--zzzz--",
  13847. "\r\nthis epilogue must be ignored\r\n");
  13848. }
  13849. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  13850. // The initial boundary may be preceded by a preamble of any length and may
  13851. // straddle a read boundary. Discarding data while waiting for it must not
  13852. // throw away a partial boundary sitting at the end of the buffer.
  13853. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  13854. "zz\r\n"
  13855. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13856. "\r\n"
  13857. "text1"
  13858. "\r\n--zzzz--\r\n");
  13859. }
  13860. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  13861. // The received boundary was only checked for being non-empty, so it could be
  13862. // as long as a header is allowed to be. The parser scans the body for
  13863. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  13864. // costs a nearly full comparison at nearly every position, making the
  13865. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  13866. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  13867. Server svr;
  13868. svr.Post("/post", [](const Request &req, Response &res) {
  13869. EXPECT_EQ(1u, req.form.fields.size());
  13870. EXPECT_EQ("text1", req.form.get_field("text1"));
  13871. res.set_content("ok", "text/plain");
  13872. });
  13873. auto port = svr.bind_to_any_port(HOST);
  13874. thread t = thread([&] { svr.listen_after_bind(); });
  13875. auto se = detail::scope_exit([&] {
  13876. svr.stop();
  13877. t.join();
  13878. ASSERT_FALSE(svr.is_running());
  13879. });
  13880. svr.wait_until_ready();
  13881. Client cli(HOST, port);
  13882. auto post_with_boundary_of_length = [&](size_t len) {
  13883. const std::string boundary(len, 'a');
  13884. const std::string body =
  13885. "--" + boundary +
  13886. "\r\n"
  13887. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13888. "\r\n"
  13889. "text1"
  13890. "\r\n--" +
  13891. boundary + "--\r\n";
  13892. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  13893. };
  13894. auto res = post_with_boundary_of_length(70);
  13895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13896. EXPECT_EQ(StatusCode::OK_200, res->status);
  13897. res = post_with_boundary_of_length(71);
  13898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13899. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13900. }
  13901. TEST(MakeFileBodyTest, Basic) {
  13902. const std::string file_content(4096, 'Z');
  13903. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  13904. {
  13905. std::ofstream ofs(tmp_path, std::ios::binary);
  13906. ofs.write(file_content.data(),
  13907. static_cast<std::streamsize>(file_content.size()));
  13908. }
  13909. auto handled = false;
  13910. Server svr;
  13911. svr.Post("/upload", [&](const Request &req, Response &res) {
  13912. EXPECT_EQ(file_content, req.body);
  13913. handled = true;
  13914. res.status = StatusCode::OK_200;
  13915. });
  13916. auto port = svr.bind_to_any_port(HOST);
  13917. auto t = thread([&] { svr.listen_after_bind(); });
  13918. auto se = detail::scope_exit([&] {
  13919. svr.stop();
  13920. t.join();
  13921. ASSERT_FALSE(svr.is_running());
  13922. ASSERT_TRUE(handled);
  13923. std::remove(tmp_path.c_str());
  13924. });
  13925. svr.wait_until_ready();
  13926. auto fb = make_file_body(tmp_path);
  13927. ASSERT_GT(fb.first, 0u);
  13928. Client cli(HOST, port);
  13929. auto res =
  13930. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  13931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13932. EXPECT_EQ(StatusCode::OK_200, res->status);
  13933. }
  13934. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  13935. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  13936. {
  13937. std::ofstream ofs(path, std::ios::binary);
  13938. const std::string content(100, 'A');
  13939. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  13940. }
  13941. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  13942. auto body = make_file_body(path);
  13943. ASSERT_EQ(100u, body.first);
  13944. ASSERT_TRUE(static_cast<bool>(body.second));
  13945. // Rewritten shorter after its length was measured - and, on a server, after
  13946. // that length has already gone out as Content-Length.
  13947. {
  13948. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  13949. const std::string content(10, 'A');
  13950. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  13951. }
  13952. std::string written;
  13953. DataSink sink;
  13954. sink.write = [&](const char *d, size_t l) {
  13955. written.append(d, l);
  13956. return true;
  13957. };
  13958. // The provider has to report failure. write_content_with_progress() advances
  13959. // its offset only by what was written, so a provider that returns true
  13960. // without completing the length it promised is called again straight away,
  13961. // and again.
  13962. EXPECT_FALSE(body.second(0, body.first, sink));
  13963. EXPECT_EQ(std::string(10, 'A'), written);
  13964. }
  13965. TEST(MakeFileBodyTest, WholeFileIsSent) {
  13966. const std::string path = "./httplib_test_make_file_body_whole.bin";
  13967. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  13968. {
  13969. std::ofstream ofs(path, std::ios::binary);
  13970. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  13971. }
  13972. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  13973. auto body = make_file_body(path);
  13974. ASSERT_EQ(content.size(), body.first);
  13975. ASSERT_TRUE(static_cast<bool>(body.second));
  13976. std::string written;
  13977. DataSink sink;
  13978. sink.write = [&](const char *d, size_t l) {
  13979. written.append(d, l);
  13980. return true;
  13981. };
  13982. EXPECT_TRUE(body.second(0, body.first, sink));
  13983. EXPECT_EQ(content, written);
  13984. }
  13985. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  13986. static constexpr unsigned int number_of_tasks{1000000};
  13987. std::atomic_uint count{0};
  13988. std::unique_ptr<TaskQueue> task_queue{
  13989. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  13990. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13991. auto queued = task_queue->enqueue(
  13992. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  13993. EXPECT_TRUE(queued);
  13994. }
  13995. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13996. task_queue->shutdown();
  13997. #else
  13998. EXPECT_NO_THROW(task_queue->shutdown());
  13999. #endif
  14000. EXPECT_EQ(number_of_tasks, count.load());
  14001. }
  14002. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14003. static constexpr unsigned int number_of_tasks{1000000};
  14004. static constexpr unsigned int qlimit{2};
  14005. unsigned int queued_count{0};
  14006. std::atomic_uint count{0};
  14007. std::unique_ptr<TaskQueue> task_queue{
  14008. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14009. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14010. if (task_queue->enqueue(
  14011. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14012. queued_count++;
  14013. }
  14014. }
  14015. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14016. task_queue->shutdown();
  14017. #else
  14018. EXPECT_NO_THROW(task_queue->shutdown());
  14019. #endif
  14020. EXPECT_EQ(queued_count, count.load());
  14021. EXPECT_TRUE(queued_count <= number_of_tasks);
  14022. EXPECT_TRUE(queued_count >= qlimit);
  14023. }
  14024. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14025. // Use a short idle timeout so a dynamic thread spawns, times out and
  14026. // exits during the test, and the pool keeps working afterwards.
  14027. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14028. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14029. /*idle_timeout_sec=*/1}};
  14030. std::atomic_uint count{0};
  14031. std::condition_variable cv;
  14032. std::mutex mtx;
  14033. bool release = false;
  14034. // Block the base thread so the second task spawns a dynamic thread.
  14035. EXPECT_TRUE(task_queue->enqueue([&] {
  14036. std::unique_lock<std::mutex> lock(mtx);
  14037. while (!release) {
  14038. cv.wait(lock);
  14039. }
  14040. count++;
  14041. }));
  14042. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14043. // Let the dynamic thread finish its task and exceed the idle timeout.
  14044. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14045. {
  14046. std::unique_lock<std::mutex> lock(mtx);
  14047. release = true;
  14048. }
  14049. cv.notify_all();
  14050. // The pool must still accept and run tasks after the dynamic thread exited.
  14051. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14052. task_queue->shutdown();
  14053. EXPECT_EQ(3u, count.load());
  14054. }
  14055. TEST(TaskQueueTest, MaxQueuedRequests) {
  14056. static constexpr unsigned int qlimit{3};
  14057. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14058. std::condition_variable sem_cv;
  14059. std::mutex sem_mtx;
  14060. int credits = 0;
  14061. bool queued;
  14062. /* Fill up the queue with tasks that will block until we give them credits to
  14063. * complete. */
  14064. for (unsigned int n = 0; n <= qlimit;) {
  14065. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14066. std::unique_lock<std::mutex> lock(sem_mtx);
  14067. while (credits <= 0) {
  14068. sem_cv.wait(lock);
  14069. }
  14070. /* Consume the credit and signal the test code if they are all gone. */
  14071. if (--credits == 0) { sem_cv.notify_one(); }
  14072. });
  14073. if (n < qlimit) {
  14074. /* The first qlimit enqueues must succeed. */
  14075. EXPECT_TRUE(queued);
  14076. } else {
  14077. /* The last one will succeed only when the worker thread
  14078. * starts and dequeues the first blocking task. Although
  14079. * not necessary for the correctness of this test, we sleep for
  14080. * a short while to avoid busy waiting. */
  14081. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14082. }
  14083. if (queued) { n++; }
  14084. }
  14085. /* Further enqueues must fail since the queue is full. */
  14086. for (auto i = 0; i < 4; i++) {
  14087. queued = task_queue->enqueue([] {});
  14088. EXPECT_FALSE(queued);
  14089. }
  14090. /* Give the credits to allow the previous tasks to complete. */
  14091. {
  14092. std::unique_lock<std::mutex> lock(sem_mtx);
  14093. credits += qlimit + 1;
  14094. }
  14095. sem_cv.notify_all();
  14096. /* Wait for all the credits to be consumed. */
  14097. {
  14098. std::unique_lock<std::mutex> lock(sem_mtx);
  14099. while (credits > 0) {
  14100. sem_cv.wait(lock);
  14101. }
  14102. }
  14103. /* Check that we are able again to enqueue at least qlimit tasks. */
  14104. for (unsigned int i = 0; i < qlimit; i++) {
  14105. queued = task_queue->enqueue([] {});
  14106. EXPECT_TRUE(queued);
  14107. }
  14108. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14109. task_queue->shutdown();
  14110. #else
  14111. EXPECT_NO_THROW(task_queue->shutdown());
  14112. #endif
  14113. }
  14114. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14115. Server svr;
  14116. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14117. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14118. });
  14119. svr.Get("/hello", [](const Request &req, Response &res) {
  14120. res.set_content(req.get_param_value("key"), "text/plain");
  14121. });
  14122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14123. auto se = detail::scope_exit([&] {
  14124. svr.stop();
  14125. thread.join();
  14126. ASSERT_FALSE(svr.is_running());
  14127. });
  14128. svr.wait_until_ready();
  14129. {
  14130. Client cli(HOST, PORT);
  14131. cli.set_follow_location(true);
  14132. auto res = cli.Get("/");
  14133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14134. EXPECT_EQ(StatusCode::OK_200, res->status);
  14135. EXPECT_EQ("val&key2=val2", res->body);
  14136. }
  14137. }
  14138. #endif
  14139. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14140. Server svr;
  14141. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14142. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14143. });
  14144. svr.Get("/hello", [](const Request &req, Response &res) {
  14145. res.set_content(req.get_param_value("key"), "text/plain");
  14146. });
  14147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14148. auto se = detail::scope_exit([&] {
  14149. svr.stop();
  14150. thread.join();
  14151. ASSERT_FALSE(svr.is_running());
  14152. });
  14153. svr.wait_until_ready();
  14154. {
  14155. Client cli(HOST, PORT);
  14156. cli.set_follow_location(true);
  14157. auto res = cli.Get("/");
  14158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14159. EXPECT_EQ(StatusCode::OK_200, res->status);
  14160. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14161. }
  14162. }
  14163. TEST(RedirectTest, RedirectWithPlusInPath) {
  14164. Server svr;
  14165. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14166. res.set_redirect("/a+b");
  14167. });
  14168. // Route pattern uses regex; escape + as \\+
  14169. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14170. res.set_content(req.path, "text/plain");
  14171. });
  14172. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14173. auto se = detail::scope_exit([&] {
  14174. svr.stop();
  14175. thread.join();
  14176. ASSERT_FALSE(svr.is_running());
  14177. });
  14178. svr.wait_until_ready();
  14179. {
  14180. Client cli(HOST, PORT);
  14181. cli.set_follow_location(true);
  14182. auto res = cli.Get("/");
  14183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14184. EXPECT_EQ(StatusCode::OK_200, res->status);
  14185. EXPECT_EQ("/a+b", res->body);
  14186. }
  14187. }
  14188. #ifdef CPPHTTPLIB_SSL_ENABLED
  14189. TEST(RedirectTest, Issue2185_Online) {
  14190. SSLClient client("github.com");
  14191. client.set_follow_location(true);
  14192. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14193. "Coollab-Windows.zip");
  14194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14195. EXPECT_EQ(StatusCode::OK_200, res->status);
  14196. EXPECT_EQ(9920427U, res->body.size());
  14197. }
  14198. #endif
  14199. TEST(VulnerabilityTest, CRLFInjection) {
  14200. Server svr;
  14201. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14202. res.set_content("Hello 1", "text/plain");
  14203. });
  14204. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14205. res.set_content("Hello 2", "text/plain");
  14206. });
  14207. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14208. res.set_content("Hello 3", "text/plain");
  14209. });
  14210. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14211. res.set_content("Hello 4", "text/plain");
  14212. });
  14213. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14214. for (const auto &x : req.headers) {
  14215. auto key = x.first;
  14216. EXPECT_STRNE("evil", key.c_str());
  14217. }
  14218. });
  14219. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14220. auto se = detail::scope_exit([&] {
  14221. svr.stop();
  14222. thread.join();
  14223. ASSERT_FALSE(svr.is_running());
  14224. });
  14225. svr.wait_until_ready();
  14226. {
  14227. Client cli(HOST, PORT);
  14228. cli.Post("/test1", "A=B",
  14229. "application/x-www-form-urlencoded\r\nevil: hello1");
  14230. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14231. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14232. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14233. }
  14234. }
  14235. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14236. auto server_thread = std::thread([] {
  14237. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14238. default_socket_options(srv);
  14239. sockaddr_in addr{};
  14240. addr.sin_family = AF_INET;
  14241. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14242. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14243. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14244. ::listen(srv, 1);
  14245. sockaddr_in cli_addr{};
  14246. socklen_t cli_len = sizeof(cli_addr);
  14247. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14248. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14249. std::string buf_all;
  14250. char buf[2048];
  14251. ssize_t n;
  14252. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14253. buf_all.append(buf, static_cast<size_t>(n));
  14254. size_t pos;
  14255. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14256. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14257. auto e = request_block.find("\r\n");
  14258. if (e != std::string::npos) {
  14259. auto request_line = request_block.substr(0, e);
  14260. std::string msg =
  14261. "CRLF injection detected in request line: '" + request_line + "'";
  14262. EXPECT_FALSE(true) << msg;
  14263. }
  14264. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14265. ::send(cli,
  14266. #ifdef _WIN32
  14267. static_cast<const char *>(resp.c_str()),
  14268. static_cast<int>(resp.size()),
  14269. #else
  14270. resp.c_str(), resp.size(),
  14271. #endif
  14272. 0);
  14273. buf_all.erase(0, pos + 4);
  14274. }
  14275. }
  14276. detail::close_socket(cli);
  14277. detail::close_socket(srv);
  14278. });
  14279. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14280. auto cli = Client("127.0.0.1", PORT + 1);
  14281. auto headers = Headers{
  14282. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14283. {"Connection", "keep-alive"}};
  14284. auto res = cli.Get("/hi", headers);
  14285. EXPECT_FALSE(res);
  14286. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14287. server_thread.join();
  14288. }
  14289. TEST(PathParamsTest, StaticMatch) {
  14290. const auto pattern = "/users/all";
  14291. detail::PathParamsMatcher matcher(pattern);
  14292. Request request;
  14293. request.path = "/users/all";
  14294. ASSERT_TRUE(matcher.match(request));
  14295. std::unordered_map<std::string, std::string> expected_params = {};
  14296. EXPECT_EQ(request.path_params, expected_params);
  14297. }
  14298. TEST(PathParamsTest, StaticMismatch) {
  14299. const auto pattern = "/users/all";
  14300. detail::PathParamsMatcher matcher(pattern);
  14301. Request request;
  14302. request.path = "/users/1";
  14303. ASSERT_FALSE(matcher.match(request));
  14304. }
  14305. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14306. const auto pattern = "/users/:id/subscriptions";
  14307. detail::PathParamsMatcher matcher(pattern);
  14308. Request request;
  14309. request.path = "/users/42/subscriptions";
  14310. ASSERT_TRUE(matcher.match(request));
  14311. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14312. EXPECT_EQ(request.path_params, expected_params);
  14313. }
  14314. TEST(PathParamsTest, SingleParamInTheEnd) {
  14315. const auto pattern = "/users/:id";
  14316. detail::PathParamsMatcher matcher(pattern);
  14317. Request request;
  14318. request.path = "/users/24";
  14319. ASSERT_TRUE(matcher.match(request));
  14320. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14321. EXPECT_EQ(request.path_params, expected_params);
  14322. }
  14323. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14324. const auto pattern = "/users/:id/";
  14325. detail::PathParamsMatcher matcher(pattern);
  14326. Request request;
  14327. request.path = "/users/42/";
  14328. ASSERT_TRUE(matcher.match(request));
  14329. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14330. EXPECT_EQ(request.path_params, expected_params);
  14331. }
  14332. TEST(PathParamsTest, EmptyParam) {
  14333. const auto pattern = "/users/:id/";
  14334. detail::PathParamsMatcher matcher(pattern);
  14335. Request request;
  14336. request.path = "/users//";
  14337. ASSERT_TRUE(matcher.match(request));
  14338. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14339. EXPECT_EQ(request.path_params, expected_params);
  14340. }
  14341. TEST(PathParamsTest, FragmentMismatch) {
  14342. const auto pattern = "/users/:id/";
  14343. detail::PathParamsMatcher matcher(pattern);
  14344. Request request;
  14345. request.path = "/admins/24/";
  14346. ASSERT_FALSE(matcher.match(request));
  14347. }
  14348. TEST(PathParamsTest, ExtraFragments) {
  14349. const auto pattern = "/users/:id";
  14350. detail::PathParamsMatcher matcher(pattern);
  14351. Request request;
  14352. request.path = "/users/42/subscriptions";
  14353. ASSERT_FALSE(matcher.match(request));
  14354. }
  14355. TEST(PathParamsTest, MissingTrailingParam) {
  14356. const auto pattern = "/users/:id";
  14357. detail::PathParamsMatcher matcher(pattern);
  14358. Request request;
  14359. request.path = "/users";
  14360. ASSERT_FALSE(matcher.match(request));
  14361. }
  14362. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14363. const auto pattern = "/users/:id/subscriptions";
  14364. detail::PathParamsMatcher matcher(pattern);
  14365. Request request;
  14366. request.path = "/users/subscriptions";
  14367. ASSERT_FALSE(matcher.match(request));
  14368. }
  14369. TEST(PathParamsTest, MultipleParams) {
  14370. const auto pattern = "/users/:userid/subscriptions/:subid";
  14371. detail::PathParamsMatcher matcher(pattern);
  14372. Request request;
  14373. request.path = "/users/42/subscriptions/2";
  14374. ASSERT_TRUE(matcher.match(request));
  14375. std::unordered_map<std::string, std::string> expected_params = {
  14376. {"userid", "42"}, {"subid", "2"}};
  14377. EXPECT_EQ(request.path_params, expected_params);
  14378. }
  14379. TEST(PathParamsTest, SequenceOfParams) {
  14380. const auto pattern = "/values/:x/:y/:z";
  14381. detail::PathParamsMatcher matcher(pattern);
  14382. Request request;
  14383. request.path = "/values/1/2/3";
  14384. ASSERT_TRUE(matcher.match(request));
  14385. std::unordered_map<std::string, std::string> expected_params = {
  14386. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14387. EXPECT_EQ(request.path_params, expected_params);
  14388. }
  14389. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14390. const auto pattern = "/prefix:suffix";
  14391. detail::PathParamsMatcher matcher(pattern);
  14392. Request request;
  14393. request.path = "/prefix:suffix";
  14394. ASSERT_TRUE(matcher.match(request));
  14395. const std::unordered_map<std::string, std::string> expected_params = {};
  14396. EXPECT_EQ(request.path_params, expected_params);
  14397. }
  14398. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14399. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14400. // calling thread's stack on a long enough path for a quantified pattern;
  14401. // RegexMatcher must refuse to run regex matching on paths beyond
  14402. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14403. detail::RegexMatcher matcher("/files/(.*)");
  14404. Request within_limit;
  14405. within_limit.path = "/files/" + std::string(10, 'A');
  14406. EXPECT_TRUE(matcher.match(within_limit));
  14407. Request over_limit;
  14408. over_limit.path =
  14409. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14410. EXPECT_FALSE(matcher.match(over_limit));
  14411. }
  14412. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14413. Server svr;
  14414. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14415. res.set_content("ok", "text/plain");
  14416. });
  14417. auto port = svr.bind_to_any_port(HOST);
  14418. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14419. auto se = detail::scope_exit([&] {
  14420. svr.stop();
  14421. thread.join();
  14422. ASSERT_FALSE(svr.is_running());
  14423. });
  14424. svr.wait_until_ready();
  14425. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14426. // request URI limit; this used to be able to crash the process.
  14427. std::string path =
  14428. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14429. std::string req = "GET " + path +
  14430. " HTTP/1.1\r\n"
  14431. "Host: " +
  14432. std::string(HOST) + ":" + std::to_string(port) +
  14433. "\r\n"
  14434. "Connection: close\r\n"
  14435. "\r\n";
  14436. std::string response;
  14437. ASSERT_TRUE(send_request(5, req, &response, port));
  14438. EXPECT_NE(std::string::npos, response.find("404"));
  14439. }
  14440. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14441. Server svr;
  14442. auto handler = [](const Request & /*req*/, Response &res) {
  14443. res.set_content("hit", "text/plain");
  14444. };
  14445. // No regex metacharacter, so this one is compared literally
  14446. svr.Get("/literal/route", handler);
  14447. // '.' is a regex metacharacter, so this one must keep regex semantics
  14448. svr.Get("/a.c", handler);
  14449. auto port = svr.bind_to_any_port(HOST);
  14450. std::thread t([&]() { svr.listen_after_bind(); });
  14451. auto se = detail::scope_exit([&] {
  14452. svr.stop();
  14453. t.join();
  14454. ASSERT_FALSE(svr.is_running());
  14455. });
  14456. svr.wait_until_ready();
  14457. Client cli(HOST, port);
  14458. struct {
  14459. const char *path;
  14460. int status;
  14461. } cases[] = {
  14462. {"/literal/route", StatusCode::OK_200},
  14463. {"/literal/routes", StatusCode::NotFound_404},
  14464. {"/literal/rout", StatusCode::NotFound_404},
  14465. {"/abc", StatusCode::OK_200},
  14466. {"/a.c", StatusCode::OK_200},
  14467. };
  14468. for (const auto &x : cases) {
  14469. auto res = cli.Get(x.path);
  14470. ASSERT_TRUE(res) << x.path;
  14471. EXPECT_EQ(x.status, res->status) << x.path;
  14472. }
  14473. }
  14474. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14475. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14476. // from exhausting the stack, so it must only constrain routes that actually
  14477. // run a regular expression. A literal route is matched by comparison and
  14478. // stays usable at any length.
  14479. Server svr;
  14480. const std::string pattern =
  14481. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14482. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14483. res.set_content("hit", "text/plain");
  14484. });
  14485. auto port = svr.bind_to_any_port(HOST);
  14486. std::thread t([&]() { svr.listen_after_bind(); });
  14487. auto se = detail::scope_exit([&] {
  14488. svr.stop();
  14489. t.join();
  14490. ASSERT_FALSE(svr.is_running());
  14491. });
  14492. svr.wait_until_ready();
  14493. Client cli(HOST, port);
  14494. auto res = cli.Get(pattern);
  14495. ASSERT_TRUE(res);
  14496. EXPECT_EQ(StatusCode::OK_200, res->status);
  14497. }
  14498. TEST(ParseUrlTest, VariousPatterns) {
  14499. {
  14500. detail::UrlComponents uc;
  14501. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14502. EXPECT_EQ("http", uc.scheme);
  14503. EXPECT_EQ("example.com", uc.host);
  14504. EXPECT_EQ("8080", uc.port);
  14505. EXPECT_EQ("/path", uc.path);
  14506. EXPECT_EQ("?q=1", uc.query);
  14507. }
  14508. {
  14509. detail::UrlComponents uc;
  14510. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  14511. EXPECT_EQ("https", uc.scheme);
  14512. EXPECT_EQ("example.com", uc.host);
  14513. EXPECT_TRUE(uc.port.empty());
  14514. EXPECT_EQ("/path", uc.path);
  14515. }
  14516. {
  14517. detail::UrlComponents uc;
  14518. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  14519. EXPECT_EQ("::1", uc.host);
  14520. EXPECT_EQ("8080", uc.port);
  14521. EXPECT_EQ("/path", uc.path);
  14522. }
  14523. {
  14524. detail::UrlComponents uc;
  14525. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  14526. }
  14527. {
  14528. // Bytes after the IPv6 literal must be a delimiter, not folded into
  14529. // the path while the connection still targets the bracketed host.
  14530. detail::UrlComponents uc;
  14531. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  14532. }
  14533. {
  14534. detail::UrlComponents uc;
  14535. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  14536. }
  14537. {
  14538. detail::UrlComponents uc;
  14539. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  14540. EXPECT_EQ("::1", uc.host);
  14541. EXPECT_TRUE(uc.port.empty());
  14542. EXPECT_EQ("/path", uc.path);
  14543. }
  14544. {
  14545. detail::UrlComponents uc;
  14546. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  14547. EXPECT_TRUE(uc.scheme.empty());
  14548. EXPECT_EQ("example.com", uc.host);
  14549. EXPECT_EQ("/path", uc.path);
  14550. EXPECT_EQ("?q=1", uc.query);
  14551. }
  14552. {
  14553. detail::UrlComponents uc;
  14554. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  14555. EXPECT_TRUE(uc.host.empty());
  14556. EXPECT_EQ("/path", uc.path);
  14557. EXPECT_EQ("?q=1", uc.query);
  14558. }
  14559. {
  14560. detail::UrlComponents uc;
  14561. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  14562. EXPECT_EQ("example.com", uc.host);
  14563. EXPECT_EQ("8080", uc.port);
  14564. }
  14565. {
  14566. // Unix socket path — must not be parsed as host
  14567. detail::UrlComponents uc;
  14568. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  14569. EXPECT_TRUE(uc.host.empty());
  14570. }
  14571. {
  14572. detail::UrlComponents uc;
  14573. ASSERT_TRUE(detail::parse_url("", uc));
  14574. EXPECT_TRUE(uc.host.empty());
  14575. EXPECT_TRUE(uc.path.empty());
  14576. }
  14577. {
  14578. detail::UrlComponents uc;
  14579. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  14580. }
  14581. {
  14582. detail::UrlComponents uc;
  14583. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  14584. }
  14585. {
  14586. // Accepted by parse_url; callers restrict to http/https
  14587. detail::UrlComponents uc;
  14588. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  14589. EXPECT_EQ("ftp", uc.scheme);
  14590. }
  14591. {
  14592. detail::UrlComponents uc;
  14593. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  14594. }
  14595. {
  14596. detail::UrlComponents uc;
  14597. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  14598. }
  14599. }
  14600. TEST(ParseUrlTest, FragmentHandling) {
  14601. {
  14602. detail::UrlComponents uc;
  14603. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  14604. EXPECT_EQ("/path", uc.path);
  14605. EXPECT_TRUE(uc.query.empty());
  14606. }
  14607. {
  14608. detail::UrlComponents uc;
  14609. ASSERT_TRUE(detail::parse_url("#frag", uc));
  14610. EXPECT_TRUE(uc.path.empty());
  14611. EXPECT_TRUE(uc.query.empty());
  14612. }
  14613. }
  14614. TEST(ParseUrlTest, UserinfoHandling) {
  14615. // Userinfo with @ but no colon — host includes @
  14616. detail::UrlComponents uc;
  14617. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  14618. EXPECT_EQ("user@host.com", uc.host);
  14619. EXPECT_EQ("/path", uc.path);
  14620. }
  14621. TEST(ParseUrlTest, IPv6EdgeCases) {
  14622. {
  14623. detail::UrlComponents uc;
  14624. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  14625. EXPECT_TRUE(uc.scheme.empty());
  14626. EXPECT_EQ("::1", uc.host);
  14627. EXPECT_EQ("8080", uc.port);
  14628. }
  14629. {
  14630. // Zone ID '%25' is not in [a-fA-F0-9:]
  14631. detail::UrlComponents uc;
  14632. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  14633. }
  14634. }
  14635. TEST(ParseUrlTest, SchemeEdgeCases) {
  14636. {
  14637. detail::UrlComponents uc;
  14638. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  14639. }
  14640. {
  14641. detail::UrlComponents uc;
  14642. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  14643. }
  14644. {
  14645. detail::UrlComponents uc;
  14646. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  14647. }
  14648. }
  14649. TEST(ParseUrlTest, PortEdgeCases) {
  14650. {
  14651. detail::UrlComponents uc;
  14652. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  14653. EXPECT_TRUE(uc.port.empty());
  14654. EXPECT_EQ("/path", uc.path);
  14655. }
  14656. {
  14657. // parse_url accepts any port string; validation is done by parse_port
  14658. detail::UrlComponents uc;
  14659. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  14660. EXPECT_EQ("abc", uc.port);
  14661. }
  14662. }
  14663. TEST(ParseUrlTest, WebSocketPatterns) {
  14664. {
  14665. detail::UrlComponents uc;
  14666. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  14667. EXPECT_EQ("ws", uc.scheme);
  14668. EXPECT_EQ("echo.example.com", uc.host);
  14669. EXPECT_EQ("8080", uc.port);
  14670. EXPECT_EQ("/ws", uc.path);
  14671. }
  14672. {
  14673. detail::UrlComponents uc;
  14674. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  14675. EXPECT_EQ("wss", uc.scheme);
  14676. EXPECT_EQ("echo.example.com", uc.host);
  14677. EXPECT_TRUE(uc.port.empty());
  14678. EXPECT_EQ("/ws", uc.path);
  14679. }
  14680. }
  14681. TEST(ParseUrlTest, QueryOnly) {
  14682. detail::UrlComponents uc;
  14683. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  14684. EXPECT_TRUE(uc.host.empty());
  14685. EXPECT_TRUE(uc.path.empty());
  14686. EXPECT_EQ("?q=1&r=2", uc.query);
  14687. }
  14688. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  14689. detail::UrlComponents uc;
  14690. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  14691. EXPECT_TRUE(uc.scheme.empty());
  14692. EXPECT_EQ("example.com", uc.host);
  14693. EXPECT_EQ("443", uc.port);
  14694. EXPECT_EQ("/path", uc.path);
  14695. }
  14696. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  14697. // If ipv6 regex working, regex match codepath is taken.
  14698. // else port will default to 80 in Client impl
  14699. int clientImplMagicPort = 80;
  14700. int port = 4321;
  14701. // above ports must be different to avoid false negative
  14702. EXPECT_NE(clientImplMagicPort, port);
  14703. std::string ipV6TestURL = "http://[ff06::c3]";
  14704. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  14705. CLIENT_PRIVATE_KEY_FILE);
  14706. EXPECT_EQ(cli.port(), port);
  14707. }
  14708. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  14709. auto file_path = "./www/dir/index.html";
  14710. auto dir_path = "./www/dir";
  14711. detail::FileStat stat_file(file_path);
  14712. EXPECT_TRUE(stat_file.is_file());
  14713. EXPECT_FALSE(stat_file.is_dir());
  14714. detail::FileStat stat_dir(dir_path);
  14715. EXPECT_FALSE(stat_dir.is_file());
  14716. EXPECT_TRUE(stat_dir.is_dir());
  14717. }
  14718. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  14719. // IPv4 with default HTTP port (80)
  14720. EXPECT_EQ("example.com",
  14721. detail::make_host_and_port_string("example.com", 80, false));
  14722. // IPv4 with default HTTPS port (443)
  14723. EXPECT_EQ("example.com",
  14724. detail::make_host_and_port_string("example.com", 443, true));
  14725. // IPv4 with non-default HTTP port
  14726. EXPECT_EQ("example.com:8080",
  14727. detail::make_host_and_port_string("example.com", 8080, false));
  14728. // IPv4 with non-default HTTPS port
  14729. EXPECT_EQ("example.com:8443",
  14730. detail::make_host_and_port_string("example.com", 8443, true));
  14731. // IPv6 with default HTTP port (80)
  14732. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  14733. // IPv6 with default HTTPS port (443)
  14734. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  14735. // IPv6 with non-default HTTP port
  14736. EXPECT_EQ("[::1]:8080",
  14737. detail::make_host_and_port_string("::1", 8080, false));
  14738. // IPv6 with non-default HTTPS port
  14739. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  14740. // IPv6 full address with default port
  14741. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  14742. detail::make_host_and_port_string(
  14743. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  14744. // IPv6 full address with non-default port
  14745. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  14746. detail::make_host_and_port_string(
  14747. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  14748. // IPv6 localhost with non-default port
  14749. EXPECT_EQ("[::1]:3000",
  14750. detail::make_host_and_port_string("::1", 3000, false));
  14751. // IPv6 with zone ID (link-local address) with default port
  14752. EXPECT_EQ("[fe80::1%eth0]",
  14753. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  14754. // IPv6 with zone ID (link-local address) with non-default port
  14755. EXPECT_EQ("[fe80::1%eth0]:8080",
  14756. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  14757. // Edge case: Port 443 with is_ssl=false (should add port)
  14758. EXPECT_EQ("example.com:443",
  14759. detail::make_host_and_port_string("example.com", 443, false));
  14760. // Edge case: Port 80 with is_ssl=true (should add port)
  14761. EXPECT_EQ("example.com:80",
  14762. detail::make_host_and_port_string("example.com", 80, true));
  14763. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  14764. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  14765. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  14766. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  14767. // Security fix: Already bracketed IPv6 should not get double brackets
  14768. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  14769. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  14770. EXPECT_EQ("[::1]:8080",
  14771. detail::make_host_and_port_string("[::1]", 8080, false));
  14772. EXPECT_EQ("[2001:db8::1]:8080",
  14773. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  14774. EXPECT_EQ("[fe80::1%eth0]",
  14775. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  14776. EXPECT_EQ("[fe80::1%eth0]:8080",
  14777. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  14778. // Edge case: Empty host (should return as-is)
  14779. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  14780. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  14781. // This is a known limitation but shouldn't crash
  14782. EXPECT_EQ("[host:name]",
  14783. detail::make_host_and_port_string("host:name", 80, false));
  14784. // Port number edge cases (no validation, but should not crash)
  14785. EXPECT_EQ("example.com:0",
  14786. detail::make_host_and_port_string("example.com", 0, false));
  14787. EXPECT_EQ("example.com:-1",
  14788. detail::make_host_and_port_string("example.com", -1, false));
  14789. EXPECT_EQ("example.com:65535",
  14790. detail::make_host_and_port_string("example.com", 65535, false));
  14791. EXPECT_EQ("example.com:65536",
  14792. detail::make_host_and_port_string("example.com", 65536, false));
  14793. }
  14794. #ifdef CPPHTTPLIB_SSL_ENABLED
  14795. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  14796. httplib::SSLClient cli("roblox.com", 443);
  14797. cli.set_follow_location(true);
  14798. auto res = cli.Get("/");
  14799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14800. EXPECT_EQ(StatusCode::OK_200, res->status);
  14801. }
  14802. #endif
  14803. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  14804. Server svr;
  14805. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14806. EXPECT_EQ(res.status, 400);
  14807. });
  14808. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14809. auto se = detail::scope_exit([&] {
  14810. svr.stop();
  14811. thread.join();
  14812. ASSERT_FALSE(svr.is_running());
  14813. });
  14814. svr.wait_until_ready();
  14815. Client cli(HOST, PORT);
  14816. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  14817. }
  14818. TEST(InvalidHeaderCharsTest, is_field_name) {
  14819. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  14820. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  14821. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  14822. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  14823. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  14824. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  14825. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  14826. EXPECT_FALSE(detail::fields::is_field_name(""));
  14827. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  14828. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  14829. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  14830. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  14831. }
  14832. TEST(InvalidHeaderCharsTest, is_field_value) {
  14833. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  14834. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  14835. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  14836. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  14837. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  14838. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  14839. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  14840. EXPECT_TRUE(detail::fields::is_field_value(""));
  14841. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  14842. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  14843. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  14844. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  14845. EXPECT_TRUE(detail::fields::is_field_value("0"));
  14846. }
  14847. TEST(InvalidHeaderCharsTest, OnServer) {
  14848. Server svr;
  14849. svr.Get("/test_name", [&](const Request &req, Response &res) {
  14850. std::string header = "Not Set";
  14851. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14852. res.set_header(header, "value");
  14853. res.set_content("Page Content Page Content", "text/plain");
  14854. });
  14855. svr.Get("/test_value", [&](const Request &req, Response &res) {
  14856. std::string header = "Not Set";
  14857. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14858. res.set_header("X-Test", header);
  14859. res.set_content("Page Content Page Content", "text/plain");
  14860. });
  14861. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14862. auto se = detail::scope_exit([&] {
  14863. svr.stop();
  14864. thread.join();
  14865. ASSERT_FALSE(svr.is_running());
  14866. });
  14867. svr.wait_until_ready();
  14868. Client cli(HOST, PORT);
  14869. {
  14870. auto res = cli.Get(
  14871. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14873. EXPECT_EQ("Page Content Page Content", res->body);
  14874. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14875. }
  14876. {
  14877. auto res = cli.Get(
  14878. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14880. EXPECT_EQ("Page Content Page Content", res->body);
  14881. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14882. }
  14883. }
  14884. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  14885. auto handled = false;
  14886. Server svr;
  14887. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14888. thread t = thread([&] { svr.listen(HOST, PORT); });
  14889. auto se = detail::scope_exit([&] {
  14890. svr.stop();
  14891. t.join();
  14892. ASSERT_FALSE(svr.is_running());
  14893. ASSERT_FALSE(handled);
  14894. });
  14895. svr.wait_until_ready();
  14896. auto req = "POST /test HTTP/1.1\r\n"
  14897. "Content-Length: x\r\n"
  14898. "\r\n";
  14899. std::string response;
  14900. ASSERT_TRUE(send_request(1, req, &response));
  14901. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14902. response.substr(0, response.find("\r\n")));
  14903. }
  14904. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  14905. // case-insensitive, and a server that receives a 100-continue expectation in
  14906. // an HTTP/1.0 request MUST ignore it.
  14907. static void probe_expect(int port, const std::string &req, bool *got_100) {
  14908. std::string response;
  14909. ASSERT_TRUE(send_request(1, req, &response, port));
  14910. *got_100 = response.find("100 Continue") != std::string::npos;
  14911. }
  14912. class ExpectTokenTest : public ::testing::Test {
  14913. protected:
  14914. void SetUp() override {
  14915. svr_.Post("/p", [](const Request &, Response &res) {
  14916. res.set_content("ok", "text/plain");
  14917. });
  14918. port_ = svr_.bind_to_any_port(HOST);
  14919. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14920. svr_.wait_until_ready();
  14921. }
  14922. void TearDown() override {
  14923. svr_.stop();
  14924. if (thread_.joinable()) { thread_.join(); }
  14925. }
  14926. std::string request(const char *version, const char *expect_value) const {
  14927. return std::string("POST /p ") + version +
  14928. "\r\n"
  14929. "Host: localhost\r\n"
  14930. "Content-Length: 2\r\n"
  14931. "Connection: close\r\n"
  14932. "Expect: " +
  14933. expect_value +
  14934. "\r\n"
  14935. "\r\n"
  14936. "hi";
  14937. }
  14938. Server svr_;
  14939. int port_ = 0;
  14940. thread thread_;
  14941. };
  14942. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  14943. bool got_100 = false;
  14944. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  14945. EXPECT_TRUE(got_100);
  14946. }
  14947. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  14948. bool got_100 = true;
  14949. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  14950. EXPECT_FALSE(got_100);
  14951. }
  14952. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  14953. bool got_100 = false;
  14954. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  14955. EXPECT_TRUE(got_100);
  14956. }
  14957. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  14958. bool got_100 = false;
  14959. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  14960. EXPECT_TRUE(got_100);
  14961. }
  14962. #ifndef _WIN32
  14963. TEST(Expect100ContinueTest, ServerClosesConnection) {
  14964. static constexpr char reject[] = "Unauthorized";
  14965. static constexpr char accept[] = "Upload accepted";
  14966. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  14967. Server svr;
  14968. svr.set_expect_100_continue_handler(
  14969. [](const Request & /*req*/, Response &res) {
  14970. res.status = StatusCode::Unauthorized_401;
  14971. res.set_content(reject, "text/plain");
  14972. return res.status;
  14973. });
  14974. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  14975. res.set_content(accept, "text/plain");
  14976. });
  14977. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14978. auto se = detail::scope_exit([&] {
  14979. svr.stop();
  14980. thread.join();
  14981. ASSERT_FALSE(svr.is_running());
  14982. });
  14983. svr.wait_until_ready();
  14984. {
  14985. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  14986. curl_easy_init(), &curl_easy_cleanup};
  14987. ASSERT_NE(curl, nullptr);
  14988. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  14989. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  14990. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  14991. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  14992. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  14993. &curl_slist_free_all};
  14994. ASSERT_NE(list, nullptr);
  14995. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  14996. struct read_data {
  14997. size_t read_size;
  14998. size_t total_size;
  14999. } data = {0, total_size};
  15000. using read_callback_t =
  15001. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15002. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15003. void *userdata) -> size_t {
  15004. read_data *d = (read_data *)userdata;
  15005. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15006. std::fill_n(ptr, size * nmemb, 'A');
  15007. d->read_size += size * nmemb;
  15008. return size * nmemb;
  15009. };
  15010. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15011. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15012. std::vector<char> buffer;
  15013. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15014. using write_callback_t =
  15015. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15016. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15017. void *userdata) -> size_t {
  15018. std::vector<char> *buf = (std::vector<char> *)userdata;
  15019. buf->reserve(buf->size() + size * nmemb + 1);
  15020. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15021. return size * nmemb;
  15022. };
  15023. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15024. {
  15025. const auto res = curl_easy_perform(curl.get());
  15026. ASSERT_EQ(res, CURLE_OK);
  15027. }
  15028. {
  15029. auto response_code = long{};
  15030. const auto res =
  15031. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15032. ASSERT_EQ(res, CURLE_OK);
  15033. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15034. }
  15035. {
  15036. auto dl = curl_off_t{};
  15037. const auto res =
  15038. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15039. ASSERT_EQ(res, CURLE_OK);
  15040. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15041. }
  15042. {
  15043. buffer.push_back('\0');
  15044. ASSERT_STRCASEEQ(buffer.data(), reject);
  15045. }
  15046. }
  15047. }
  15048. #endif
  15049. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15050. // Regression test for #2458.
  15051. //
  15052. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15053. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15054. // ticket can make the client socket spuriously readable during the
  15055. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15056. // the client withholds the body and then blocks reading a response that never
  15057. // comes, failing with `Failed to read connection`.
  15058. //
  15059. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15060. // within the timeout. This raw OpenSSL server deliberately never sends
  15061. // `100 Continue`; the client must still deliver the body and receive 200.
  15062. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15063. signal(SIGPIPE, SIG_IGN);
  15064. const auto port = PORT + 4;
  15065. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15066. ASSERT_NE(srv, INVALID_SOCKET);
  15067. int opt = 1;
  15068. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15069. sockaddr_in addr{};
  15070. addr.sin_family = AF_INET;
  15071. addr.sin_port = htons(static_cast<uint16_t>(port));
  15072. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15073. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15074. ASSERT_EQ(0, ::listen(srv, 1));
  15075. std::atomic<size_t> server_body_bytes{0};
  15076. auto server_thread = std::thread([&] {
  15077. sockaddr_in cli_addr{};
  15078. socklen_t cli_len = sizeof(cli_addr);
  15079. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15080. if (cli == INVALID_SOCKET) { return; }
  15081. // Bound the lifetime of the server side so a buggy client (which never
  15082. // sends the body) cannot make this thread block forever on join.
  15083. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15084. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15085. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15086. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15087. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15088. SSL *ssl = SSL_new(ctx);
  15089. SSL_set_fd(ssl, static_cast<int>(cli));
  15090. if (SSL_accept(ssl) > 0) {
  15091. // Read the request headers. Reading here also flushes the TLS 1.3
  15092. // session tickets to the client. Deliberately do NOT send
  15093. // `100 Continue`.
  15094. std::string buf;
  15095. char tmp[1024];
  15096. while (buf.find("\r\n\r\n") == std::string::npos) {
  15097. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15098. if (n <= 0) { break; }
  15099. buf.append(tmp, static_cast<size_t>(n));
  15100. }
  15101. // A correct client sends the body now; count what arrives.
  15102. auto pos = buf.find("\r\n\r\n");
  15103. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15104. while (body < 4096) {
  15105. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15106. if (n <= 0) { break; }
  15107. body += static_cast<size_t>(n);
  15108. }
  15109. server_body_bytes = body;
  15110. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15111. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15112. SSL_shutdown(ssl);
  15113. }
  15114. SSL_free(ssl);
  15115. detail::close_socket(cli);
  15116. SSL_CTX_free(ctx);
  15117. });
  15118. auto se = detail::scope_exit([&] {
  15119. server_thread.join();
  15120. detail::close_socket(srv);
  15121. });
  15122. SSLClient cli("127.0.0.1", port);
  15123. cli.enable_server_certificate_verification(false);
  15124. cli.set_connection_timeout(5, 0);
  15125. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15126. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15127. std::string body(4096, 'A');
  15128. auto res = cli.Put("/api/test", body, "application/json");
  15129. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15130. EXPECT_EQ(StatusCode::OK_200, res->status);
  15131. EXPECT_EQ(body.size(), server_body_bytes.load());
  15132. }
  15133. #endif
  15134. template <typename S, typename C>
  15135. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15136. svr.Get("/stream", [&](const Request &, Response &res) {
  15137. auto data = new std::string("01234567890123456789");
  15138. res.set_content_provider(
  15139. data->size(), "text/plain",
  15140. [&, data](size_t offset, size_t length, DataSink &sink) {
  15141. const size_t DATA_CHUNK_SIZE = 4;
  15142. const auto &d = *data;
  15143. std::this_thread::sleep_for(std::chrono::seconds(1));
  15144. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15145. return true;
  15146. },
  15147. [data](bool success) {
  15148. EXPECT_FALSE(success);
  15149. delete data;
  15150. });
  15151. });
  15152. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15153. auto i = new size_t(0);
  15154. res.set_content_provider(
  15155. "text/plain",
  15156. [i](size_t, DataSink &sink) {
  15157. if (*i < 5) {
  15158. std::this_thread::sleep_for(std::chrono::seconds(1));
  15159. sink.write("abcd", 4);
  15160. (*i)++;
  15161. } else {
  15162. sink.done();
  15163. }
  15164. return true;
  15165. },
  15166. [i](bool success) {
  15167. EXPECT_FALSE(success);
  15168. delete i;
  15169. });
  15170. });
  15171. svr.Get("/chunked", [&](const Request &, Response &res) {
  15172. auto i = new size_t(0);
  15173. res.set_chunked_content_provider(
  15174. "text/plain",
  15175. [i](size_t, DataSink &sink) {
  15176. if (*i < 5) {
  15177. std::this_thread::sleep_for(std::chrono::seconds(1));
  15178. sink.os << "abcd";
  15179. (*i)++;
  15180. } else {
  15181. sink.done();
  15182. }
  15183. return true;
  15184. },
  15185. [i](bool success) {
  15186. EXPECT_FALSE(success);
  15187. delete i;
  15188. });
  15189. });
  15190. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15191. auto se = detail::scope_exit([&] {
  15192. svr.stop();
  15193. listen_thread.join();
  15194. ASSERT_FALSE(svr.is_running());
  15195. });
  15196. svr.wait_until_ready();
  15197. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15198. {
  15199. auto start = std::chrono::steady_clock::now();
  15200. auto res = cli.Get("/stream");
  15201. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15202. std::chrono::steady_clock::now() - start)
  15203. .count();
  15204. ASSERT_FALSE(res);
  15205. EXPECT_EQ(Error::Read, res.error());
  15206. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15207. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15208. }
  15209. {
  15210. auto start = std::chrono::steady_clock::now();
  15211. auto res = cli.Get("/stream_without_length");
  15212. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15213. std::chrono::steady_clock::now() - start)
  15214. .count();
  15215. ASSERT_FALSE(res);
  15216. EXPECT_EQ(Error::Read, res.error());
  15217. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15218. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15219. }
  15220. {
  15221. auto start = std::chrono::steady_clock::now();
  15222. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15223. EXPECT_EQ("abcd", string(data, data_length));
  15224. return true;
  15225. });
  15226. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15227. std::chrono::steady_clock::now() - start)
  15228. .count();
  15229. ASSERT_FALSE(res);
  15230. EXPECT_EQ(Error::Read, res.error());
  15231. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15232. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15233. }
  15234. }
  15235. TEST(MaxTimeoutTest, ContentStream) {
  15236. time_t timeout = 2000;
  15237. time_t threshold = 200;
  15238. Server svr;
  15239. Client cli("localhost", PORT);
  15240. max_timeout_test(svr, cli, timeout, threshold);
  15241. }
  15242. #ifdef CPPHTTPLIB_SSL_ENABLED
  15243. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15244. time_t timeout = 2000;
  15245. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15247. SSLClient cli("localhost", PORT);
  15248. cli.enable_server_certificate_verification(false);
  15249. max_timeout_test(svr, cli, timeout, threshold);
  15250. }
  15251. #endif
  15252. class EventDispatcher {
  15253. public:
  15254. EventDispatcher() {}
  15255. bool wait_event(DataSink *sink) {
  15256. unique_lock<mutex> lk(m_);
  15257. int id = id_;
  15258. // Wait with timeout to prevent hanging if client disconnects
  15259. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15260. [&] { return cid_ == id; })) {
  15261. return false; // Timeout occurred
  15262. }
  15263. sink->write(message_.data(), message_.size());
  15264. return true;
  15265. }
  15266. void send_event(const string &message) {
  15267. lock_guard<mutex> lk(m_);
  15268. cid_ = id_++;
  15269. message_ = message;
  15270. cv_.notify_all();
  15271. }
  15272. private:
  15273. mutex m_;
  15274. condition_variable cv_;
  15275. atomic_int id_{0};
  15276. atomic_int cid_{-1};
  15277. string message_;
  15278. };
  15279. TEST(ClientInThreadTest, Issue2068) {
  15280. EventDispatcher ed;
  15281. Server svr;
  15282. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15283. res.set_chunked_content_provider("text/event-stream",
  15284. [&](size_t /*offset*/, DataSink &sink) {
  15285. return ed.wait_event(&sink);
  15286. });
  15287. });
  15288. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15289. svr.wait_until_ready();
  15290. thread event_thread([&] {
  15291. int id = 0;
  15292. while (svr.is_running()) {
  15293. this_thread::sleep_for(chrono::milliseconds(500));
  15294. std::stringstream ss;
  15295. ss << "data: " << id << "\n\n";
  15296. ed.send_event(ss.str());
  15297. id++;
  15298. }
  15299. });
  15300. auto se = detail::scope_exit([&] {
  15301. svr.stop();
  15302. listen_thread.join();
  15303. event_thread.join();
  15304. ASSERT_FALSE(svr.is_running());
  15305. });
  15306. {
  15307. auto client = detail::make_unique<Client>(HOST, PORT);
  15308. client->set_read_timeout(std::chrono::minutes(10));
  15309. std::atomic<bool> stop{false};
  15310. std::thread t([&] {
  15311. client->Get("/event1",
  15312. [&](const char *, size_t) -> bool { return !stop; });
  15313. });
  15314. std::this_thread::sleep_for(std::chrono::seconds(2));
  15315. stop = true;
  15316. client->stop();
  15317. t.join();
  15318. // Reset client after thread has finished
  15319. client.reset();
  15320. }
  15321. }
  15322. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  15323. auto handled = false;
  15324. Server svr;
  15325. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15326. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15327. auto se = detail::scope_exit([&] {
  15328. svr.stop();
  15329. t.join();
  15330. ASSERT_FALSE(svr.is_running());
  15331. ASSERT_FALSE(handled);
  15332. });
  15333. svr.wait_until_ready();
  15334. // Two Content-Length headers with different values — must be rejected
  15335. auto req = "POST /test HTTP/1.1\r\n"
  15336. "Content-Length: 5\r\n"
  15337. "Content-Length: 10\r\n"
  15338. "\r\n"
  15339. "hello";
  15340. std::string response;
  15341. ASSERT_TRUE(send_request(1, req, &response));
  15342. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15343. response.substr(0, response.find("\r\n")));
  15344. }
  15345. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  15346. auto handled = false;
  15347. Server svr;
  15348. svr.Post("/test", [&](const Request &, Response &res) {
  15349. handled = true;
  15350. res.set_content("ok", "text/plain");
  15351. });
  15352. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15353. auto se = detail::scope_exit([&] {
  15354. svr.stop();
  15355. t.join();
  15356. ASSERT_FALSE(svr.is_running());
  15357. ASSERT_TRUE(handled);
  15358. });
  15359. svr.wait_until_ready();
  15360. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  15361. auto req = "POST /test HTTP/1.1\r\n"
  15362. "Content-Length: 5\r\n"
  15363. "Content-Length: 5\r\n"
  15364. "\r\n"
  15365. "hello";
  15366. std::string response;
  15367. ASSERT_TRUE(send_request(1, req, &response));
  15368. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  15369. }
  15370. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  15371. Server svr;
  15372. svr.Get("/", [](const Request &req, Response &res) {
  15373. EXPECT_EQ(2U, req.trailers.size());
  15374. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  15375. // Denied
  15376. EXPECT_FALSE(req.has_trailer("Content-Length"));
  15377. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  15378. // Accepted
  15379. EXPECT_TRUE(req.has_trailer("X-Hello"));
  15380. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  15381. EXPECT_TRUE(req.has_trailer("X-World"));
  15382. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  15383. res.set_content("ok", "text/plain");
  15384. });
  15385. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15386. auto se = detail::scope_exit([&] {
  15387. svr.stop();
  15388. t.join();
  15389. ASSERT_FALSE(svr.is_running());
  15390. });
  15391. svr.wait_until_ready();
  15392. const std::string req = "GET / HTTP/1.1\r\n"
  15393. "Transfer-Encoding: chunked\r\n"
  15394. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  15395. "\r\n"
  15396. "0\r\n"
  15397. "Content-Length: 10\r\n"
  15398. "Host: internal.local\r\n"
  15399. "Content-Type: malicious/content\r\n"
  15400. "Cookie: any\r\n"
  15401. "Set-Cookie: any\r\n"
  15402. "X-Forwarded-For: attacker.com\r\n"
  15403. "X-Real-Ip: 1.1.1.1\r\n"
  15404. "X-Hello: hello\r\n"
  15405. "X-World: world\r\n"
  15406. "\r\n";
  15407. std::string res;
  15408. ASSERT_TRUE(send_request(1, req, &res));
  15409. }
  15410. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  15411. // several field lines, and the combined value is what has to be parsed. A
  15412. // Trailer field split across lines therefore declares every name it lists;
  15413. // reading only the first line silently drops the trailers the later lines
  15414. // declare. The prohibited-trailer filter still applies to every line.
  15415. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  15416. Server svr;
  15417. size_t observed_trailer_count = 0;
  15418. std::string observed_hello;
  15419. std::string observed_world;
  15420. bool observed_content_length = true;
  15421. svr.Get("/", [&](const Request &req, Response &res) {
  15422. observed_trailer_count = req.trailers.size();
  15423. observed_hello = req.get_trailer_value("X-Hello");
  15424. observed_world = req.get_trailer_value("X-World");
  15425. observed_content_length = req.has_trailer("Content-Length");
  15426. res.set_content("ok", "text/plain");
  15427. });
  15428. auto port = svr.bind_to_any_port(HOST);
  15429. thread t = thread([&]() { svr.listen_after_bind(); });
  15430. auto se = detail::scope_exit([&] {
  15431. svr.stop();
  15432. t.join();
  15433. ASSERT_FALSE(svr.is_running());
  15434. });
  15435. svr.wait_until_ready();
  15436. const std::string req = "GET / HTTP/1.1\r\n"
  15437. "Transfer-Encoding: chunked\r\n"
  15438. "Trailer: X-Hello\r\n"
  15439. "Trailer: X-World, Content-Length\r\n"
  15440. "\r\n"
  15441. "0\r\n"
  15442. "X-Hello: hello\r\n"
  15443. "X-World: world\r\n"
  15444. "Content-Length: 10\r\n"
  15445. "\r\n";
  15446. std::string res;
  15447. ASSERT_TRUE(send_request(1, req, &res, port));
  15448. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  15449. // Accepted: both field lines contribute to the declared set
  15450. EXPECT_EQ(2U, observed_trailer_count);
  15451. EXPECT_EQ(observed_hello, "hello");
  15452. EXPECT_EQ(observed_world, "world");
  15453. // Denied: a prohibited name stays prohibited on a later field line
  15454. EXPECT_FALSE(observed_content_length);
  15455. }
  15456. // A direct client that is not listed in trusted_proxies must not be able to
  15457. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  15458. // the peer address on the actual TCP connection determines whether the
  15459. // header is honored.
  15460. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  15461. Server svr;
  15462. // Deliberately does NOT include the loopback address the test client
  15463. // actually connects from, so the direct connection is not a trusted proxy.
  15464. svr.set_trusted_proxies({"203.0.113.66"});
  15465. std::string observed_remote_addr;
  15466. svr.Get("/ip", [&](const Request &req, Response &res) {
  15467. observed_remote_addr = req.remote_addr;
  15468. res.set_content("ok", "text/plain");
  15469. });
  15470. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15471. auto se = detail::scope_exit([&] {
  15472. svr.stop();
  15473. t.join();
  15474. ASSERT_FALSE(svr.is_running());
  15475. });
  15476. svr.wait_until_ready();
  15477. Client cli(HOST, PORT);
  15478. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  15479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15480. EXPECT_EQ(StatusCode::OK_200, res->status);
  15481. // The connecting peer is not a trusted proxy, so the spoofed header must be
  15482. // ignored entirely and the real connection-level address retained.
  15483. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15484. observed_remote_addr == "127.0.0.1");
  15485. }
  15486. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  15487. Server svr;
  15488. std::string observed_remote_addr;
  15489. std::string observed_xff;
  15490. svr.Get("/ip", [&](const Request &req, Response &res) {
  15491. observed_remote_addr = req.remote_addr;
  15492. observed_xff = req.get_header_value("X-Forwarded-For");
  15493. res.set_content("ok", "text/plain");
  15494. });
  15495. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15496. auto se = detail::scope_exit([&] {
  15497. svr.stop();
  15498. t.join();
  15499. ASSERT_FALSE(svr.is_running());
  15500. });
  15501. svr.wait_until_ready();
  15502. Client cli(HOST, PORT);
  15503. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  15504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15505. EXPECT_EQ(StatusCode::OK_200, res->status);
  15506. EXPECT_EQ(observed_xff, "203.0.113.66");
  15507. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15508. observed_remote_addr == "127.0.0.1");
  15509. }
  15510. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  15511. Server svr;
  15512. svr.set_trusted_proxies({"203.0.113.66"});
  15513. std::string observed_remote_addr;
  15514. std::string observed_xff;
  15515. svr.Get("/ip", [&](const Request &req, Response &res) {
  15516. observed_remote_addr = req.remote_addr;
  15517. observed_xff = req.get_header_value("X-Forwarded-For");
  15518. res.set_content("ok", "text/plain");
  15519. });
  15520. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15521. auto se = detail::scope_exit([&] {
  15522. svr.stop();
  15523. t.join();
  15524. ASSERT_FALSE(svr.is_running());
  15525. });
  15526. svr.wait_until_ready();
  15527. Client cli(HOST, PORT);
  15528. auto res = cli.Get("/ip");
  15529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15530. EXPECT_EQ(StatusCode::OK_200, res->status);
  15531. EXPECT_EQ(observed_xff, "");
  15532. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15533. observed_remote_addr == "127.0.0.1");
  15534. }
  15535. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  15536. Server svr;
  15537. // Include the loopback address the test client actually connects from, so
  15538. // the direct connection itself is recognized as the trusted proxy hop.
  15539. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  15540. std::string observed_remote_addr;
  15541. std::string observed_xff;
  15542. svr.Get("/ip", [&](const Request &req, Response &res) {
  15543. observed_remote_addr = req.remote_addr;
  15544. observed_xff = req.get_header_value("X-Forwarded-For");
  15545. res.set_content("ok", "text/plain");
  15546. });
  15547. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15548. auto se = detail::scope_exit([&] {
  15549. svr.stop();
  15550. t.join();
  15551. ASSERT_FALSE(svr.is_running());
  15552. });
  15553. svr.wait_until_ready();
  15554. Client cli(HOST, PORT);
  15555. auto res = cli.Get(
  15556. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  15557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15558. EXPECT_EQ(StatusCode::OK_200, res->status);
  15559. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  15560. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15561. }
  15562. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  15563. Server svr;
  15564. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  15565. std::string observed_remote_addr;
  15566. std::string observed_xff;
  15567. svr.Get("/ip", [&](const Request &req, Response &res) {
  15568. observed_remote_addr = req.remote_addr;
  15569. observed_xff = req.get_header_value("X-Forwarded-For");
  15570. res.set_content("ok", "text/plain");
  15571. });
  15572. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15573. auto se = detail::scope_exit([&] {
  15574. svr.stop();
  15575. t.join();
  15576. ASSERT_FALSE(svr.is_running());
  15577. });
  15578. svr.wait_until_ready();
  15579. Client cli(HOST, PORT);
  15580. auto res = cli.Get(
  15581. "/ip",
  15582. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15584. EXPECT_EQ(StatusCode::OK_200, res->status);
  15585. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15586. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15587. }
  15588. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  15589. Server svr;
  15590. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15591. std::string observed_remote_addr;
  15592. std::string observed_xff;
  15593. svr.Get("/ip", [&](const Request &req, Response &res) {
  15594. observed_remote_addr = req.remote_addr;
  15595. observed_xff = req.get_header_value("X-Forwarded-For");
  15596. res.set_content("ok", "text/plain");
  15597. });
  15598. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15599. auto se = detail::scope_exit([&] {
  15600. svr.stop();
  15601. t.join();
  15602. ASSERT_FALSE(svr.is_running());
  15603. });
  15604. svr.wait_until_ready();
  15605. Client cli(HOST, PORT);
  15606. auto res = cli.Get(
  15607. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  15608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15609. EXPECT_EQ(StatusCode::OK_200, res->status);
  15610. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  15611. // by the closest hop) is used. The leftmost entry is fully client-controlled
  15612. // and must not be selected.
  15613. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  15614. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  15615. }
  15616. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  15617. Server svr;
  15618. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  15619. std::string observed_remote_addr;
  15620. svr.Get("/ip", [&](const Request &req, Response &res) {
  15621. observed_remote_addr = req.remote_addr;
  15622. res.set_content("ok", "text/plain");
  15623. });
  15624. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15625. auto se = detail::scope_exit([&] {
  15626. svr.stop();
  15627. t.join();
  15628. ASSERT_FALSE(svr.is_running());
  15629. });
  15630. svr.wait_until_ready();
  15631. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  15632. // a forged address and the trusted proxy's own address; the forged value must
  15633. // not win over the address the trusted proxy actually recorded.
  15634. Client cli(HOST, PORT);
  15635. auto res = cli.Get(
  15636. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  15637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15638. EXPECT_EQ(StatusCode::OK_200, res->status);
  15639. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  15640. }
  15641. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  15642. Server svr;
  15643. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15644. std::string observed_remote_addr;
  15645. std::string observed_xff;
  15646. svr.Get("/ip", [&](const Request &req, Response &res) {
  15647. observed_remote_addr = req.remote_addr;
  15648. observed_xff = req.get_header_value("X-Forwarded-For");
  15649. res.set_content("ok", "text/plain");
  15650. });
  15651. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15652. auto se = detail::scope_exit([&] {
  15653. svr.stop();
  15654. t.join();
  15655. ASSERT_FALSE(svr.is_running());
  15656. });
  15657. svr.wait_until_ready();
  15658. Client cli(HOST, PORT);
  15659. auto res = cli.Get(
  15660. "/ip",
  15661. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15663. EXPECT_EQ(StatusCode::OK_200, res->status);
  15664. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15665. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15666. }
  15667. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  15668. Server svr;
  15669. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15670. std::string observed_remote_addr;
  15671. std::string observed_xff;
  15672. svr.Get("/ip", [&](const Request &req, Response &res) {
  15673. observed_remote_addr = req.remote_addr;
  15674. observed_xff = req.get_header_value("X-Forwarded-For");
  15675. res.set_content("ok", "text/plain");
  15676. });
  15677. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15678. auto se = detail::scope_exit([&] {
  15679. svr.stop();
  15680. t.join();
  15681. ASSERT_FALSE(svr.is_running());
  15682. });
  15683. svr.wait_until_ready();
  15684. std::string raw_req =
  15685. "GET /ip HTTP/1.1\r\n"
  15686. "Host: localhost\r\n"
  15687. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  15688. "Connection: close\r\n"
  15689. "\r\n";
  15690. std::string out;
  15691. ASSERT_TRUE(send_request(5, raw_req, &out));
  15692. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15693. // Header parser trims surrounding whitespace of the header value
  15694. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  15695. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15696. }
  15697. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  15698. // one comma-joined value, in the order received. Proxies such as HAProxy append
  15699. // their own X-Forwarded-For as a separate field line rather than extending the
  15700. // one the client sent, so every occurrence has to be taken into account.
  15701. // Reading only the first one hands back the address the client chose.
  15702. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  15703. Server svr;
  15704. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15705. std::string observed_remote_addr;
  15706. size_t observed_xff_count = 0;
  15707. svr.Get("/ip", [&](const Request &req, Response &res) {
  15708. observed_remote_addr = req.remote_addr;
  15709. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  15710. res.set_content("ok", "text/plain");
  15711. });
  15712. auto port = svr.bind_to_any_port(HOST);
  15713. thread t = thread([&]() { svr.listen_after_bind(); });
  15714. auto se = detail::scope_exit([&] {
  15715. svr.stop();
  15716. t.join();
  15717. ASSERT_FALSE(svr.is_running());
  15718. });
  15719. svr.wait_until_ready();
  15720. // The client supplies the first field line; the trusted proxy appends the
  15721. // address it observed as a second one.
  15722. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  15723. "Host: localhost\r\n"
  15724. "X-Forwarded-For: 1.2.3.4\r\n"
  15725. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  15726. "Connection: close\r\n"
  15727. "\r\n";
  15728. std::string out;
  15729. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15730. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15731. EXPECT_EQ(observed_xff_count, 2U);
  15732. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15733. // The same chain spread over one field line per hop derives the same client
  15734. // address, i.e. the split and the comma-joined representations agree.
  15735. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  15736. "Host: localhost\r\n"
  15737. "X-Forwarded-For: 1.2.3.4\r\n"
  15738. "X-Forwarded-For: 198.51.100.23\r\n"
  15739. "X-Forwarded-For: 192.0.2.45\r\n"
  15740. "Connection: close\r\n"
  15741. "\r\n";
  15742. out.clear();
  15743. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  15744. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15745. EXPECT_EQ(observed_xff_count, 3U);
  15746. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15747. }
  15748. // An X-Forwarded-For header whose value parses to zero IP segments must not
  15749. // crash the server (it used to call front() on an empty vector inside
  15750. // get_client_ip). The connection-level remote address must be retained instead.
  15751. static void run_malformed_xff_test(const std::string &xff_value) {
  15752. Server svr;
  15753. svr.set_trusted_proxies({"192.0.2.45"});
  15754. std::string observed_remote_addr;
  15755. svr.Get("/ip", [&](const Request &req, Response &res) {
  15756. observed_remote_addr = req.remote_addr;
  15757. res.set_content("ok", "text/plain");
  15758. });
  15759. int port = 0;
  15760. thread t = thread([&]() {
  15761. port = svr.bind_to_any_port(HOST);
  15762. svr.listen_after_bind();
  15763. });
  15764. auto se = detail::scope_exit([&] {
  15765. svr.stop();
  15766. t.join();
  15767. ASSERT_FALSE(svr.is_running());
  15768. });
  15769. svr.wait_until_ready();
  15770. Client cli(HOST, port);
  15771. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  15772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15773. EXPECT_EQ(StatusCode::OK_200, res->status);
  15774. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15775. observed_remote_addr == "127.0.0.1");
  15776. }
  15777. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  15778. run_malformed_xff_test("");
  15779. }
  15780. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  15781. run_malformed_xff_test(",");
  15782. }
  15783. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  15784. run_malformed_xff_test(", , ,");
  15785. }
  15786. // The same rule applies to Accept: a request whose acceptable types are spread
  15787. // over several field lines must be negotiated against all of them.
  15788. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  15789. // case-insensitive connection options. Comparing the whole field value against
  15790. // one option misses a client that sends several of them, and misses every
  15791. // casing but the one written in the comparison.
  15792. //
  15793. // Sends req, reads the response, then reuses the same socket for a second
  15794. // request to find out whether the server kept the connection.
  15795. static void probe_connection_reuse(int port, const std::string &req,
  15796. bool *announced_close, bool *reusable) {
  15797. auto error = Error::Success;
  15798. auto sock = detail::create_client_socket(
  15799. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15800. /*connection_timeout_sec=*/5, 0,
  15801. /*read_timeout_sec=*/1, 0,
  15802. /*write_timeout_sec=*/5, 0, std::string(), error);
  15803. ASSERT_NE(sock, INVALID_SOCKET);
  15804. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  15805. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  15806. "Host: localhost\r\n"
  15807. "Connection: close\r\n"
  15808. "\r\n";
  15809. std::string first_response;
  15810. std::string second_response;
  15811. detail::process_client_socket(
  15812. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  15813. [&](Stream &strm) {
  15814. if (strm.write(req.data(), req.size()) !=
  15815. static_cast<ssize_t>(req.size())) {
  15816. return false;
  15817. }
  15818. char buf[512];
  15819. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  15820. // Headers plus the two-byte body of the handler below
  15821. while (reader.getline()) {
  15822. first_response += reader.ptr();
  15823. if (first_response.find("ok") != std::string::npos) { break; }
  15824. }
  15825. if (strm.write(second.data(), second.size()) !=
  15826. static_cast<ssize_t>(second.size())) {
  15827. return true;
  15828. }
  15829. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  15830. while (reader2.getline()) {
  15831. second_response += reader2.ptr();
  15832. if (second_response.find("ok") != std::string::npos) { break; }
  15833. }
  15834. return true;
  15835. });
  15836. *announced_close =
  15837. first_response.find("Connection: close") != std::string::npos;
  15838. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  15839. }
  15840. class ConnectionTokenTest : public ::testing::Test {
  15841. protected:
  15842. void SetUp() override {
  15843. svr_.Get("/keepalive", [](const Request &, Response &res) {
  15844. res.set_content("ok", "text/plain");
  15845. });
  15846. port_ = svr_.bind_to_any_port(HOST);
  15847. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15848. svr_.wait_until_ready();
  15849. }
  15850. void TearDown() override {
  15851. svr_.stop();
  15852. if (thread_.joinable()) { thread_.join(); }
  15853. }
  15854. Server svr_;
  15855. int port_ = 0;
  15856. thread thread_;
  15857. };
  15858. // "close" alongside another option still closes the connection, and the
  15859. // response says so rather than leaving the peer to discover it.
  15860. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  15861. bool announced_close = false;
  15862. bool reusable = true;
  15863. probe_connection_reuse(port_,
  15864. "GET /keepalive HTTP/1.1\r\n"
  15865. "Host: localhost\r\n"
  15866. "Connection: keep-alive, close\r\n"
  15867. "\r\n",
  15868. &announced_close, &reusable);
  15869. EXPECT_TRUE(announced_close);
  15870. EXPECT_FALSE(reusable);
  15871. }
  15872. // "close" split over two field lines is the same list, so it is honored too.
  15873. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  15874. bool announced_close = false;
  15875. bool reusable = true;
  15876. probe_connection_reuse(port_,
  15877. "GET /keepalive HTTP/1.1\r\n"
  15878. "Host: localhost\r\n"
  15879. "Connection: keep-alive\r\n"
  15880. "Connection: close\r\n"
  15881. "\r\n",
  15882. &announced_close, &reusable);
  15883. EXPECT_TRUE(announced_close);
  15884. EXPECT_FALSE(reusable);
  15885. }
  15886. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  15887. // keep-alive in the spelling everyone actually sends keeps its connection.
  15888. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  15889. bool announced_close = false;
  15890. bool reusable = false;
  15891. probe_connection_reuse(port_,
  15892. "GET /keepalive HTTP/1.0\r\n"
  15893. "Host: localhost\r\n"
  15894. "Connection: keep-alive\r\n"
  15895. "\r\n",
  15896. &announced_close, &reusable);
  15897. EXPECT_FALSE(announced_close);
  15898. EXPECT_TRUE(reusable);
  15899. }
  15900. // A token the value merely contains is not the token itself.
  15901. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  15902. bool announced_close = false;
  15903. bool reusable = false;
  15904. probe_connection_reuse(port_,
  15905. "GET /keepalive HTTP/1.1\r\n"
  15906. "Host: localhost\r\n"
  15907. "Connection: notclose\r\n"
  15908. "\r\n",
  15909. &announced_close, &reusable);
  15910. EXPECT_FALSE(announced_close);
  15911. EXPECT_TRUE(reusable);
  15912. }
  15913. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  15914. Server svr;
  15915. std::vector<std::string> observed_types;
  15916. svr.Get("/", [&](const Request &req, Response &res) {
  15917. observed_types = req.accept_content_types;
  15918. res.set_content("ok", "text/plain");
  15919. });
  15920. auto port = svr.bind_to_any_port(HOST);
  15921. thread t = thread([&]() { svr.listen_after_bind(); });
  15922. auto se = detail::scope_exit([&] {
  15923. svr.stop();
  15924. t.join();
  15925. ASSERT_FALSE(svr.is_running());
  15926. });
  15927. svr.wait_until_ready();
  15928. Client cli(HOST, port);
  15929. Headers headers;
  15930. headers.emplace("Accept", "text/plain;q=0.5");
  15931. headers.emplace("Accept", "application/json");
  15932. auto res = cli.Get("/", headers);
  15933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15934. EXPECT_EQ(StatusCode::OK_200, res->status);
  15935. // Sorted by q-value, so the second field line's type comes first
  15936. ASSERT_EQ(2U, observed_types.size());
  15937. EXPECT_EQ("application/json", observed_types[0]);
  15938. EXPECT_EQ("text/plain", observed_types[1]);
  15939. }
  15940. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  15941. // empty field line must not contribute a bare comma to the combined value.
  15942. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  15943. Server svr;
  15944. std::vector<std::string> observed_types;
  15945. svr.Get("/", [&](const Request &req, Response &res) {
  15946. observed_types = req.accept_content_types;
  15947. res.set_content("ok", "text/plain");
  15948. });
  15949. auto port = svr.bind_to_any_port(HOST);
  15950. thread t = thread([&]() { svr.listen_after_bind(); });
  15951. auto se = detail::scope_exit([&] {
  15952. svr.stop();
  15953. t.join();
  15954. ASSERT_FALSE(svr.is_running());
  15955. });
  15956. svr.wait_until_ready();
  15957. // Empty first field line, then a real one
  15958. std::string raw_req = "GET / HTTP/1.1\r\n"
  15959. "Host: localhost\r\n"
  15960. "Accept:\r\n"
  15961. "Accept: application/json\r\n"
  15962. "Connection: close\r\n"
  15963. "\r\n";
  15964. std::string out;
  15965. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15966. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15967. ASSERT_EQ(1U, observed_types.size());
  15968. EXPECT_EQ("application/json", observed_types[0]);
  15969. }
  15970. // The skip in get_combined_header_value() is what keeps an empty field line
  15971. // from contributing a bare comma. Only a trailing empty field line exercises
  15972. // it: a leading one is already covered by the "combined is still empty" check,
  15973. // and parse_accept_header() now ignores the empty element either way, so the
  15974. // request-level test above can no longer tell the two apart.
  15975. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  15976. Headers headers;
  15977. headers.emplace("Accept", "text/html");
  15978. headers.emplace("Accept", "");
  15979. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  15980. headers.clear();
  15981. headers.emplace("Accept", "");
  15982. headers.emplace("Accept", "application/json");
  15983. EXPECT_EQ("application/json",
  15984. detail::get_combined_header_value(headers, "Accept"));
  15985. }
  15986. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15987. // An encoding offered on a later Accept-Encoding field line is still offered.
  15988. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  15989. Server svr;
  15990. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15991. res.set_content(std::string(1024, 'x'), "text/plain");
  15992. });
  15993. auto port = svr.bind_to_any_port(HOST);
  15994. thread t = thread([&]() { svr.listen_after_bind(); });
  15995. auto se = detail::scope_exit([&] {
  15996. svr.stop();
  15997. t.join();
  15998. ASSERT_FALSE(svr.is_running());
  15999. });
  16000. svr.wait_until_ready();
  16001. Client cli(HOST, port);
  16002. cli.set_decompress(false);
  16003. Headers headers;
  16004. headers.emplace("Accept-Encoding", "identity");
  16005. headers.emplace("Accept-Encoding", "gzip");
  16006. auto res = cli.Get("/", headers);
  16007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16008. EXPECT_EQ(StatusCode::OK_200, res->status);
  16009. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16010. }
  16011. #endif
  16012. #ifndef _WIN32
  16013. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16014. Server svr;
  16015. svr.Post("/post", [&](const Request &req, Response &res) {
  16016. res.set_content(req.body, "text/plain");
  16017. });
  16018. svr.Put("/put", [&](const Request &req, Response &res) {
  16019. res.set_content(req.body, "text/plain");
  16020. });
  16021. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16022. res.set_content(req.body, "text/plain");
  16023. });
  16024. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16025. res.set_content(req.body, "text/plain");
  16026. });
  16027. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16028. auto se = detail::scope_exit([&] {
  16029. svr.stop();
  16030. t.join();
  16031. ASSERT_FALSE(svr.is_running());
  16032. });
  16033. svr.wait_until_ready();
  16034. std::string resp;
  16035. // POST without Content-Length
  16036. ASSERT_TRUE(send_request(5,
  16037. "POST /post HTTP/1.1\r\n"
  16038. "Host: localhost\r\n"
  16039. "Connection: close\r\n"
  16040. "\r\n",
  16041. &resp));
  16042. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16043. // PUT without Content-Length
  16044. resp.clear();
  16045. ASSERT_TRUE(send_request(5,
  16046. "PUT /put HTTP/1.1\r\n"
  16047. "Host: localhost\r\n"
  16048. "Connection: close\r\n"
  16049. "\r\n",
  16050. &resp));
  16051. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16052. // PATCH without Content-Length
  16053. resp.clear();
  16054. ASSERT_TRUE(send_request(5,
  16055. "PATCH /patch HTTP/1.1\r\n"
  16056. "Host: localhost\r\n"
  16057. "Connection: close\r\n"
  16058. "\r\n",
  16059. &resp));
  16060. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16061. // DELETE without Content-Length
  16062. resp.clear();
  16063. ASSERT_TRUE(send_request(5,
  16064. "DELETE /delete HTTP/1.1\r\n"
  16065. "Host: localhost\r\n"
  16066. "Connection: close\r\n"
  16067. "\r\n",
  16068. &resp));
  16069. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16070. }
  16071. #endif
  16072. //==============================================================================
  16073. // open_stream() Tests
  16074. //==============================================================================
  16075. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16076. std::string result;
  16077. char buf[8192];
  16078. ssize_t n;
  16079. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16080. result.append(buf, static_cast<size_t>(n));
  16081. }
  16082. return result;
  16083. }
  16084. // Mock stream for unit tests
  16085. class MockStream : public Stream {
  16086. public:
  16087. std::string data;
  16088. size_t pos = 0;
  16089. ssize_t error_after = -1; // -1 = no error
  16090. explicit MockStream(const std::string &d, ssize_t err = -1)
  16091. : data(d), error_after(err) {}
  16092. bool is_readable() const override { return true; }
  16093. bool wait_readable() const override { return true; }
  16094. bool wait_writable() const override { return true; }
  16095. ssize_t read(char *ptr, size_t size) override {
  16096. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16097. if (pos >= data.size()) return 0;
  16098. size_t limit =
  16099. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16100. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16101. std::memcpy(ptr, data.data() + pos, to_read);
  16102. pos += to_read;
  16103. return static_cast<ssize_t>(to_read);
  16104. }
  16105. ssize_t write(const char *, size_t) override { return -1; }
  16106. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16107. ip = "127.0.0.1";
  16108. port = 0;
  16109. }
  16110. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16111. ip = "127.0.0.1";
  16112. port = 0;
  16113. }
  16114. socket_t socket() const override { return INVALID_SOCKET; }
  16115. time_t duration() const override { return 0; }
  16116. };
  16117. TEST(StreamHandleTest, Basic) {
  16118. ClientImpl::StreamHandle handle;
  16119. EXPECT_FALSE(handle.is_valid());
  16120. handle.response = detail::make_unique<Response>();
  16121. handle.error = Error::Connection;
  16122. EXPECT_FALSE(handle.is_valid());
  16123. handle.error = Error::Success;
  16124. EXPECT_TRUE(handle.is_valid());
  16125. }
  16126. TEST(BodyReaderTest, Basic) {
  16127. MockStream stream("Hello, World!");
  16128. detail::BodyReader reader;
  16129. reader.stream = &stream;
  16130. reader.content_length = 13;
  16131. char buf[32];
  16132. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16133. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16134. EXPECT_TRUE(reader.eof);
  16135. }
  16136. TEST(BodyReaderTest, NoStream) {
  16137. detail::BodyReader reader;
  16138. char buf[32];
  16139. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16140. EXPECT_EQ(Error::Connection, reader.last_error);
  16141. }
  16142. TEST(BodyReaderTest, Error) {
  16143. MockStream stream("Hello, World!", 5);
  16144. detail::BodyReader reader;
  16145. reader.stream = &stream;
  16146. reader.content_length = 13;
  16147. char buf[32];
  16148. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16149. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16150. EXPECT_EQ(Error::Read, reader.last_error);
  16151. }
  16152. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16153. // Mock-based StreamHandle tests relying on private internals are removed.
  16154. class OpenStreamTest : public ::testing::Test {
  16155. protected:
  16156. void SetUp() override {
  16157. svr_.Get("/hello", [](const Request &, Response &res) {
  16158. res.set_content("Hello World!", "text/plain");
  16159. });
  16160. svr_.Get("/large", [](const Request &, Response &res) {
  16161. res.set_content(std::string(10000, 'X'), "text/plain");
  16162. });
  16163. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16164. res.set_content("Hello World!", "image/jpeg");
  16165. res.set_header("Content-Encoding", "UTF-8");
  16166. });
  16167. svr_.Get("/chunked", [](const Request &, Response &res) {
  16168. res.set_chunked_content_provider("text/plain",
  16169. [](size_t offset, DataSink &sink) {
  16170. if (offset < 15) {
  16171. sink.write("chunk", 5);
  16172. return true;
  16173. }
  16174. sink.done();
  16175. return true;
  16176. });
  16177. });
  16178. svr_.Get("/compressible", [](const Request &, Response &res) {
  16179. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16180. DataSink &sink) {
  16181. if (offset < 100 * 1024) {
  16182. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16183. sink.write(chunk.data(), chunk.size());
  16184. return true;
  16185. }
  16186. sink.done();
  16187. return true;
  16188. });
  16189. });
  16190. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16191. [](const Request & /*req*/, Response &res) {
  16192. auto i = new int(0);
  16193. res.set_header("Trailer", "Content-Length, X-Allowed");
  16194. res.set_chunked_content_provider(
  16195. "text/plain",
  16196. [i](size_t /*offset*/, DataSink &sink) {
  16197. switch (*i) {
  16198. case 0: sink.os << "123"; break;
  16199. case 1: sink.os << "456"; break;
  16200. case 2: sink.os << "789"; break;
  16201. case 3: {
  16202. sink.done_with_trailer(
  16203. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16204. } break;
  16205. }
  16206. (*i)++;
  16207. return true;
  16208. },
  16209. [i](bool success) {
  16210. EXPECT_TRUE(success);
  16211. delete i;
  16212. });
  16213. });
  16214. // Echo headers endpoint for header-related tests
  16215. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16216. std::string body;
  16217. for (const auto &h : req.headers) {
  16218. body.append(h.first);
  16219. body.push_back(':');
  16220. body.append(h.second);
  16221. body.push_back('\n');
  16222. }
  16223. res.set_content(body, "text/plain");
  16224. });
  16225. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16226. std::string body;
  16227. for (const auto &h : req.headers) {
  16228. body.append(h.first);
  16229. body.push_back(':');
  16230. body.append(h.second);
  16231. body.push_back('\n');
  16232. }
  16233. res.set_content(body, "text/plain");
  16234. });
  16235. port_ = svr_.bind_to_any_port("127.0.0.1");
  16236. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16237. svr_.wait_until_ready();
  16238. }
  16239. void TearDown() override {
  16240. svr_.stop();
  16241. if (thread_.joinable()) thread_.join();
  16242. }
  16243. Server svr_;
  16244. std::thread thread_;
  16245. int port_ = 0;
  16246. };
  16247. TEST_F(OpenStreamTest, Basic) {
  16248. Client cli("127.0.0.1", port_);
  16249. auto handle = cli.open_stream("GET", "/hello");
  16250. EXPECT_TRUE(handle.is_valid());
  16251. EXPECT_EQ("Hello World!", read_all(handle));
  16252. }
  16253. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  16254. Client cli("127.0.0.1", port_);
  16255. auto handle = cli.open_stream("GET", "/unknown-encoding");
  16256. ASSERT_TRUE(handle.is_valid());
  16257. EXPECT_EQ("Hello World!", read_all(handle));
  16258. }
  16259. TEST_F(OpenStreamTest, SmallBuffer) {
  16260. Client cli("127.0.0.1", port_);
  16261. auto handle = cli.open_stream("GET", "/hello");
  16262. std::string result;
  16263. char buf[4];
  16264. ssize_t n;
  16265. while ((n = handle.read(buf, sizeof(buf))) > 0)
  16266. result.append(buf, static_cast<size_t>(n));
  16267. EXPECT_EQ("Hello World!", result);
  16268. }
  16269. TEST_F(OpenStreamTest, DefaultHeaders) {
  16270. Client cli("127.0.0.1", port_);
  16271. // open_stream GET should include Host, User-Agent and Accept-Encoding
  16272. {
  16273. auto handle = cli.open_stream("GET", "/echo-headers");
  16274. ASSERT_TRUE(handle.is_valid());
  16275. auto body = read_all(handle);
  16276. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  16277. std::string::npos);
  16278. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  16279. std::string::npos);
  16280. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  16281. }
  16282. // open_stream POST with body and no explicit content_type should NOT add
  16283. // text/plain Content-Type (behavior differs from non-streaming path), but
  16284. // should include Content-Length
  16285. {
  16286. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  16287. ASSERT_TRUE(handle.is_valid());
  16288. auto body = read_all(handle);
  16289. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  16290. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  16291. }
  16292. // open_stream POST with explicit Content-Type should preserve it
  16293. {
  16294. auto handle = cli.open_stream("POST", "/echo-headers", {},
  16295. {{"Content-Type", "application/custom"}},
  16296. "{}", "application/custom");
  16297. ASSERT_TRUE(handle.is_valid());
  16298. auto body = read_all(handle);
  16299. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  16300. }
  16301. // User-specified User-Agent must not be overwritten for stream API
  16302. {
  16303. auto handle = cli.open_stream("GET", "/echo-headers", {},
  16304. {{"User-Agent", "MyAgent/1.2"}});
  16305. ASSERT_TRUE(handle.is_valid());
  16306. auto body = read_all(handle);
  16307. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  16308. }
  16309. }
  16310. TEST_F(OpenStreamTest, Large) {
  16311. Client cli("127.0.0.1", port_);
  16312. auto handle = cli.open_stream("GET", "/large");
  16313. EXPECT_EQ(10000u, read_all(handle).size());
  16314. }
  16315. TEST_F(OpenStreamTest, ConnectionError) {
  16316. Client cli("127.0.0.1", 9999);
  16317. auto handle = cli.open_stream("GET", "/hello");
  16318. EXPECT_FALSE(handle.is_valid());
  16319. }
  16320. TEST_F(OpenStreamTest, Chunked) {
  16321. Client cli("127.0.0.1", port_);
  16322. auto handle = cli.open_stream("GET", "/chunked");
  16323. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16324. "Transfer-Encoding") == "chunked");
  16325. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  16326. }
  16327. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  16328. Client cli("127.0.0.1", port_);
  16329. auto handle =
  16330. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  16331. ASSERT_TRUE(handle.is_valid());
  16332. // Consume body to allow trailers to be received/parsed
  16333. auto body = read_all(handle);
  16334. // Explicitly parse trailers (ensure trailers are available for assertion)
  16335. handle.parse_trailers_if_needed();
  16336. EXPECT_EQ(std::string("123456789"), body);
  16337. // The response should include a Trailer header declaring both names
  16338. ASSERT_TRUE(handle.response);
  16339. EXPECT_TRUE(handle.response->has_header("Trailer"));
  16340. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  16341. handle.response->get_header_value("Trailer"));
  16342. // Prohibited trailer must not be present
  16343. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  16344. // Allowed trailer should be present
  16345. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  16346. EXPECT_EQ(std::string("yes"),
  16347. handle.response->get_trailer_value("X-Allowed"));
  16348. // Verify trailers are NOT present as regular headers
  16349. EXPECT_EQ(std::string(""),
  16350. handle.response->get_header_value("Content-Length"));
  16351. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  16352. }
  16353. static std::thread serve_single_response(std::promise<int> &port_promise,
  16354. const std::string &response) {
  16355. return std::thread([&port_promise, response] {
  16356. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16357. default_socket_options(srv);
  16358. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  16359. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  16360. sockaddr_in addr{};
  16361. addr.sin_family = AF_INET;
  16362. addr.sin_port = htons(0); // Let OS assign a free port
  16363. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16364. int opt = 1;
  16365. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  16366. #ifdef _WIN32
  16367. reinterpret_cast<const char *>(&opt),
  16368. #else
  16369. &opt,
  16370. #endif
  16371. sizeof(opt));
  16372. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  16373. ::listen(srv, 1) != 0) {
  16374. port_promise.set_value(-1);
  16375. detail::close_socket(srv);
  16376. return;
  16377. }
  16378. socklen_t addr_len = sizeof(addr);
  16379. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  16380. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  16381. sockaddr_in cli_addr{};
  16382. socklen_t cli_len = sizeof(cli_addr);
  16383. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16384. if (cli != INVALID_SOCKET) {
  16385. // Read the complete HTTP request (until the blank line that terminates
  16386. // headers) before sending the response. If the server closes the socket
  16387. // while the client's request data is still unread in the kernel receive
  16388. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  16389. // connection on both sides: it discards the client's receive buffer
  16390. // (which already holds our response) and causes any in-progress write on
  16391. // the client to fail with ECONNRESET. Reading all request data first
  16392. // ensures close() emits a graceful FIN.
  16393. {
  16394. char rbuf[256];
  16395. std::string req;
  16396. while (req.find("\r\n\r\n") == std::string::npos) {
  16397. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  16398. if (n <= 0) { break; }
  16399. req.append(rbuf, static_cast<size_t>(n));
  16400. }
  16401. }
  16402. ::send(cli,
  16403. #ifdef _WIN32
  16404. static_cast<const char *>(response.c_str()),
  16405. static_cast<int>(response.size()),
  16406. #else
  16407. response.c_str(), response.size(),
  16408. #endif
  16409. 0);
  16410. detail::close_socket(cli);
  16411. }
  16412. detail::close_socket(srv);
  16413. });
  16414. }
  16415. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  16416. #ifndef _WIN32
  16417. signal(SIGPIPE, SIG_IGN);
  16418. #endif
  16419. std::promise<int> port_promise;
  16420. auto port_future = port_promise.get_future();
  16421. auto server_thread =
  16422. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  16423. "Content-Type: text/plain\r\n"
  16424. "Content-Length: not-a-number\r\n"
  16425. "Connection: close\r\n"
  16426. "\r\n"
  16427. "hello");
  16428. auto port = port_future.get();
  16429. ASSERT_GT(port, 0);
  16430. Client cli("127.0.0.1", port);
  16431. auto handle = cli.open_stream("GET", "/");
  16432. EXPECT_FALSE(handle.is_valid());
  16433. server_thread.join();
  16434. }
  16435. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  16436. #ifndef _WIN32
  16437. signal(SIGPIPE, SIG_IGN);
  16438. #endif
  16439. std::promise<int> port_promise;
  16440. auto port_future = port_promise.get_future();
  16441. auto server_thread = serve_single_response(
  16442. port_promise, "HTTP/1.1 200 OK\r\n"
  16443. "Content-Type: text/plain\r\n"
  16444. "Content-Length: 99999999999999999999999999\r\n"
  16445. "Connection: close\r\n"
  16446. "\r\n"
  16447. "hello");
  16448. auto port = port_future.get();
  16449. ASSERT_GT(port, 0);
  16450. // Historically std::stoull would throw std::out_of_range here and crash
  16451. // the process, then parsing silently clamped to a bogus framing length and
  16452. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  16453. // so the stream fails to open, matching the not-a-number case above. The
  16454. // process still must NOT terminate.
  16455. Client cli("127.0.0.1", port);
  16456. auto handle = cli.open_stream("GET", "/");
  16457. EXPECT_FALSE(handle.is_valid());
  16458. server_thread.join();
  16459. }
  16460. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16461. TEST_F(OpenStreamTest, Gzip) {
  16462. Client cli("127.0.0.1", port_);
  16463. auto handle = cli.open_stream("GET", "/compressible", {},
  16464. {{"Accept-Encoding", "gzip"}});
  16465. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  16466. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16467. }
  16468. #endif
  16469. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16470. TEST_F(OpenStreamTest, Brotli) {
  16471. Client cli("127.0.0.1", port_);
  16472. auto handle =
  16473. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  16474. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  16475. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16476. }
  16477. #endif
  16478. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16479. TEST_F(OpenStreamTest, Zstd) {
  16480. Client cli("127.0.0.1", port_);
  16481. auto handle = cli.open_stream("GET", "/compressible", {},
  16482. {{"Accept-Encoding", "zstd"}});
  16483. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  16484. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16485. }
  16486. #endif
  16487. #ifdef CPPHTTPLIB_SSL_ENABLED
  16488. class SSLOpenStreamTest : public ::testing::Test {
  16489. protected:
  16490. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  16491. void SetUp() override {
  16492. svr_.Get("/hello", [](const Request &, Response &res) {
  16493. res.set_content("Hello SSL World!", "text/plain");
  16494. });
  16495. svr_.Get("/chunked", [](const Request &, Response &res) {
  16496. res.set_chunked_content_provider("text/plain",
  16497. [](size_t offset, DataSink &sink) {
  16498. if (offset < 15) {
  16499. sink.write("chunk", 5);
  16500. return true;
  16501. }
  16502. sink.done();
  16503. return true;
  16504. });
  16505. });
  16506. svr_.Post("/echo", [](const Request &req, Response &res) {
  16507. res.set_content(req.body, req.get_header_value("Content-Type"));
  16508. });
  16509. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  16510. std::string body = req.body;
  16511. res.set_chunked_content_provider(
  16512. "text/plain", [body](size_t offset, DataSink &sink) {
  16513. if (offset < body.size()) {
  16514. sink.write(body.data() + offset, body.size() - offset);
  16515. }
  16516. sink.done();
  16517. return true;
  16518. });
  16519. });
  16520. port_ = svr_.bind_to_any_port("127.0.0.1");
  16521. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16522. svr_.wait_until_ready();
  16523. }
  16524. void TearDown() override {
  16525. svr_.stop();
  16526. if (thread_.joinable()) thread_.join();
  16527. }
  16528. SSLServer svr_;
  16529. std::thread thread_;
  16530. int port_ = 0;
  16531. };
  16532. TEST_F(SSLOpenStreamTest, Basic) {
  16533. SSLClient cli("127.0.0.1", port_);
  16534. cli.enable_server_certificate_verification(false);
  16535. auto handle = cli.open_stream("GET", "/hello");
  16536. ASSERT_TRUE(handle.is_valid());
  16537. EXPECT_EQ("Hello SSL World!", read_all(handle));
  16538. }
  16539. TEST_F(SSLOpenStreamTest, Chunked) {
  16540. SSLClient cli("127.0.0.1", port_);
  16541. cli.enable_server_certificate_verification(false);
  16542. auto handle = cli.open_stream("GET", "/chunked");
  16543. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16544. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16545. "Transfer-Encoding") == "chunked");
  16546. auto body = read_all(handle);
  16547. EXPECT_EQ("chunkchunkchunk", body);
  16548. }
  16549. TEST_F(SSLOpenStreamTest, Post) {
  16550. SSLClient cli("127.0.0.1", port_);
  16551. cli.enable_server_certificate_verification(false);
  16552. auto handle =
  16553. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  16554. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16555. EXPECT_EQ(200, handle.response->status);
  16556. auto body = read_all(handle);
  16557. EXPECT_EQ("Hello SSL POST", body);
  16558. }
  16559. TEST_F(SSLOpenStreamTest, PostChunked) {
  16560. SSLClient cli("127.0.0.1", port_);
  16561. cli.enable_server_certificate_verification(false);
  16562. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  16563. "Chunked SSL Data", "text/plain");
  16564. ASSERT_TRUE(handle.is_valid());
  16565. EXPECT_EQ(200, handle.response->status);
  16566. auto body = read_all(handle);
  16567. EXPECT_EQ("Chunked SSL Data", body);
  16568. }
  16569. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  16570. // Content-Length is terminated by the server closing the connection. When the
  16571. // SSL peer sends a close_notify after the body, the client must treat it as a
  16572. // clean EOF and return a successful response rather than an error.
  16573. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  16574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16575. ASSERT_TRUE(svr.is_valid());
  16576. svr.set_keep_alive_max_count(1);
  16577. const std::string expected_body = "Hello from connection-close response!";
  16578. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  16579. res.set_content_provider("text/plain",
  16580. [&](size_t offset, DataSink &sink) -> bool {
  16581. if (offset < expected_body.size()) {
  16582. sink.write(expected_body.data() + offset,
  16583. expected_body.size() - offset);
  16584. }
  16585. sink.done();
  16586. return true;
  16587. });
  16588. });
  16589. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  16590. auto se = detail::scope_exit([&] {
  16591. svr.stop();
  16592. listen_thread.join();
  16593. ASSERT_FALSE(svr.is_running());
  16594. });
  16595. svr.wait_until_ready();
  16596. SSLClient cli(HOST, PORT);
  16597. cli.enable_server_certificate_verification(false);
  16598. auto res = cli.Get("/no-content-length");
  16599. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  16600. EXPECT_EQ(StatusCode::OK_200, res->status);
  16601. EXPECT_EQ(expected_body, res->body);
  16602. }
  16603. #endif // CPPHTTPLIB_SSL_ENABLED
  16604. //==============================================================================
  16605. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  16606. // results for various scenarios.
  16607. //==============================================================================
  16608. TEST(ParityTest, GetVsOpenStream) {
  16609. Server svr;
  16610. const std::string path = "/parity";
  16611. const std::string content = "Parity test content: hello world";
  16612. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16613. res.set_content(content, "text/plain");
  16614. });
  16615. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16616. auto se = detail::scope_exit([&] {
  16617. svr.stop();
  16618. t.join();
  16619. ASSERT_FALSE(svr.is_running());
  16620. });
  16621. svr.wait_until_ready();
  16622. Client cli(HOST, PORT);
  16623. // Non-stream path
  16624. auto r1 = cli.Get(path);
  16625. ASSERT_TRUE(r1);
  16626. EXPECT_EQ(StatusCode::OK_200, r1->status);
  16627. // Stream path
  16628. auto h = cli.open_stream("GET", path);
  16629. ASSERT_TRUE(h.is_valid());
  16630. EXPECT_EQ(r1->body, read_all(h));
  16631. }
  16632. // Helper to compress data with provided compressor type T
  16633. template <typename Compressor>
  16634. static std::string compress_payload_for_parity(const std::string &in) {
  16635. std::string out;
  16636. Compressor compressor;
  16637. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  16638. [&](const char *data, size_t n) {
  16639. out.append(data, n);
  16640. return true;
  16641. });
  16642. EXPECT_TRUE(ok);
  16643. return out;
  16644. }
  16645. // Helper function for compression parity tests
  16646. template <typename Compressor>
  16647. static void test_compression_parity(const std::string &original,
  16648. const std::string &path,
  16649. const std::string &encoding) {
  16650. const std::string compressed =
  16651. compress_payload_for_parity<Compressor>(original);
  16652. Server svr;
  16653. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16654. res.set_content(compressed, "application/octet-stream");
  16655. res.set_header("Content-Encoding", encoding);
  16656. });
  16657. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  16658. auto se = detail::scope_exit([&] {
  16659. svr.stop();
  16660. t.join();
  16661. ASSERT_FALSE(svr.is_running());
  16662. });
  16663. svr.wait_until_ready();
  16664. Client cli(HOST, PORT);
  16665. // Non-streaming
  16666. {
  16667. auto res = cli.Get(path);
  16668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16669. EXPECT_EQ(StatusCode::OK_200, res->status);
  16670. EXPECT_EQ(original, res->body);
  16671. }
  16672. // Streaming
  16673. {
  16674. auto h = cli.open_stream("GET", path);
  16675. ASSERT_TRUE(h.is_valid());
  16676. EXPECT_EQ(original, read_all(h));
  16677. }
  16678. }
  16679. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16680. TEST(ParityTest, Gzip) {
  16681. test_compression_parity<detail::gzip_compressor>(
  16682. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  16683. }
  16684. #endif
  16685. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16686. TEST(ParityTest, Brotli) {
  16687. test_compression_parity<detail::brotli_compressor>(
  16688. "Hello, brotli parity test payload", "/parity-br", "br");
  16689. }
  16690. #endif
  16691. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16692. TEST(ParityTest, Zstd) {
  16693. test_compression_parity<detail::zstd_compressor>(
  16694. "Zstandard parity test payload", "/parity-zstd", "zstd");
  16695. }
  16696. #endif
  16697. //==============================================================================
  16698. // New Stream API Tests
  16699. //==============================================================================
  16700. inline std::string read_body(httplib::stream::Result &result) {
  16701. std::string body;
  16702. while (result.next()) {
  16703. body.append(result.data(), result.size());
  16704. }
  16705. return body;
  16706. }
  16707. TEST(ClientConnectionTest, Basic) {
  16708. httplib::ClientConnection conn;
  16709. EXPECT_FALSE(conn.is_open());
  16710. conn.sock = 1;
  16711. EXPECT_TRUE(conn.is_open());
  16712. httplib::ClientConnection conn2(std::move(conn));
  16713. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  16714. conn2.sock = INVALID_SOCKET;
  16715. }
  16716. // Unified test server for all stream::* tests
  16717. class StreamApiTest : public ::testing::Test {
  16718. protected:
  16719. void SetUp() override {
  16720. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16721. res.set_content("Hello World!", "text/plain");
  16722. });
  16723. svr_.Get("/echo-params",
  16724. [](const httplib::Request &req, httplib::Response &res) {
  16725. std::string r;
  16726. for (const auto &p : req.params) {
  16727. if (!r.empty()) r += "&";
  16728. r += p.first + "=" + p.second;
  16729. }
  16730. res.set_content(r, "text/plain");
  16731. });
  16732. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16733. res.set_content(req.body, req.get_header_value("Content-Type"));
  16734. });
  16735. svr_.Post("/echo-headers",
  16736. [](const httplib::Request &req, httplib::Response &res) {
  16737. std::string r;
  16738. for (const auto &h : req.headers)
  16739. r += h.first + ": " + h.second + "\n";
  16740. res.set_content(r, "text/plain");
  16741. });
  16742. svr_.Post("/echo-params",
  16743. [](const httplib::Request &req, httplib::Response &res) {
  16744. std::string r = "params:";
  16745. for (const auto &p : req.params)
  16746. r += p.first + "=" + p.second + ";";
  16747. res.set_content(r + " body:" + req.body, "text/plain");
  16748. });
  16749. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  16750. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  16751. });
  16752. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16753. res.set_content("PUT:" + req.body, "text/plain");
  16754. });
  16755. svr_.Patch("/echo",
  16756. [](const httplib::Request &req, httplib::Response &res) {
  16757. res.set_content("PATCH:" + req.body, "text/plain");
  16758. });
  16759. svr_.Delete(
  16760. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  16761. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  16762. "text/plain");
  16763. });
  16764. svr_.Get("/head-test",
  16765. [](const httplib::Request &, httplib::Response &res) {
  16766. res.set_content("body for HEAD", "text/plain");
  16767. });
  16768. svr_.Options("/options",
  16769. [](const httplib::Request &, httplib::Response &res) {
  16770. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  16771. });
  16772. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  16773. svr_.wait_until_ready();
  16774. }
  16775. void TearDown() override {
  16776. svr_.stop();
  16777. if (thread_.joinable()) thread_.join();
  16778. }
  16779. httplib::Server svr_;
  16780. std::thread thread_;
  16781. };
  16782. // stream::Get tests
  16783. TEST_F(StreamApiTest, GetBasic) {
  16784. httplib::Client cli(HOST, PORT);
  16785. auto result = httplib::stream::Get(cli, "/hello");
  16786. ASSERT_TRUE(result.is_valid());
  16787. EXPECT_EQ(200, result.status());
  16788. EXPECT_EQ("Hello World!", read_body(result));
  16789. }
  16790. TEST_F(StreamApiTest, GetWithParams) {
  16791. httplib::Client cli(HOST, PORT);
  16792. httplib::Params params{{"foo", "bar"}};
  16793. auto result = httplib::stream::Get(cli, "/echo-params", params);
  16794. ASSERT_TRUE(result.is_valid());
  16795. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  16796. }
  16797. TEST_F(StreamApiTest, GetConnectionError) {
  16798. httplib::Client cli(HOST, 9999);
  16799. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  16800. }
  16801. TEST_F(StreamApiTest, Get404) {
  16802. httplib::Client cli(HOST, PORT);
  16803. auto result = httplib::stream::Get(cli, "/nonexistent");
  16804. EXPECT_TRUE(result.is_valid());
  16805. EXPECT_EQ(404, result.status());
  16806. }
  16807. // stream::Post tests
  16808. TEST_F(StreamApiTest, PostBasic) {
  16809. httplib::Client cli(HOST, PORT);
  16810. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  16811. "application/json");
  16812. ASSERT_TRUE(result.is_valid());
  16813. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  16814. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  16815. }
  16816. TEST_F(StreamApiTest, PostWithHeaders) {
  16817. httplib::Client cli(HOST, PORT);
  16818. httplib::Headers headers{{"X-Custom", "value"}};
  16819. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  16820. "text/plain");
  16821. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  16822. }
  16823. TEST_F(StreamApiTest, PostWithParams) {
  16824. httplib::Client cli(HOST, PORT);
  16825. httplib::Params params{{"k", "v"}};
  16826. auto result =
  16827. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  16828. auto body = read_body(result);
  16829. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  16830. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  16831. }
  16832. TEST_F(StreamApiTest, PostLarge) {
  16833. httplib::Client cli(HOST, PORT);
  16834. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  16835. size_t total = 0;
  16836. while (result.next()) {
  16837. total += result.size();
  16838. }
  16839. EXPECT_EQ(100u * 1024u, total);
  16840. }
  16841. // stream::Put/Patch tests
  16842. TEST_F(StreamApiTest, PutAndPatch) {
  16843. httplib::Client cli(HOST, PORT);
  16844. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  16845. EXPECT_EQ("PUT:test", read_body(put));
  16846. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  16847. EXPECT_EQ("PATCH:test", read_body(patch));
  16848. }
  16849. // stream::Delete tests
  16850. TEST_F(StreamApiTest, Delete) {
  16851. httplib::Client cli(HOST, PORT);
  16852. auto del1 = httplib::stream::Delete(cli, "/resource");
  16853. EXPECT_EQ("Deleted", read_body(del1));
  16854. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  16855. EXPECT_EQ("Deleted:data", read_body(del2));
  16856. }
  16857. // stream::Head/Options tests
  16858. TEST_F(StreamApiTest, HeadAndOptions) {
  16859. httplib::Client cli(HOST, PORT);
  16860. auto head = httplib::stream::Head(cli, "/head-test");
  16861. EXPECT_TRUE(head.is_valid());
  16862. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  16863. auto opts = httplib::stream::Options(cli, "/options");
  16864. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  16865. }
  16866. // SSL stream::* tests
  16867. #ifdef CPPHTTPLIB_SSL_ENABLED
  16868. class SSLStreamApiTest : public ::testing::Test {
  16869. protected:
  16870. void SetUp() override {
  16871. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16872. res.set_content("Hello SSL!", "text/plain");
  16873. });
  16874. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16875. res.set_content(req.body, "text/plain");
  16876. });
  16877. port_ = svr_.bind_to_any_port("127.0.0.1");
  16878. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16879. svr_.wait_until_ready();
  16880. }
  16881. void TearDown() override {
  16882. svr_.stop();
  16883. if (thread_.joinable()) thread_.join();
  16884. }
  16885. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  16886. std::thread thread_;
  16887. int port_ = 0;
  16888. };
  16889. TEST_F(SSLStreamApiTest, GetAndPost) {
  16890. httplib::SSLClient cli("127.0.0.1", port_);
  16891. cli.enable_server_certificate_verification(false);
  16892. auto get = httplib::stream::Get(cli, "/hello");
  16893. EXPECT_EQ("Hello SSL!", read_body(get));
  16894. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  16895. EXPECT_EQ("test", read_body(post));
  16896. }
  16897. #endif
  16898. // Tests for Error::Timeout and Error::ConnectionClosed error types
  16899. // These errors are set in SocketStream/SSLSocketStream and propagated through
  16900. // BodyReader
  16901. TEST(ErrorHandlingTest, StreamReadTimeout) {
  16902. // Test that read timeout during streaming is detected
  16903. // Use a large content-length response where server delays mid-stream
  16904. Server svr;
  16905. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16906. // Send a large response with delay in the middle
  16907. res.set_content_provider(
  16908. 1000, // content_length
  16909. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  16910. if (offset < 100) {
  16911. // Send first 100 bytes immediately
  16912. std::string data(100, 'A');
  16913. sink.write(data.c_str(), data.size());
  16914. return true;
  16915. }
  16916. // Then delay longer than client timeout
  16917. std::this_thread::sleep_for(std::chrono::seconds(3));
  16918. std::string data(900, 'B');
  16919. sink.write(data.c_str(), data.size());
  16920. return true;
  16921. });
  16922. });
  16923. auto port = 8091;
  16924. std::thread t([&]() { svr.listen("localhost", port); });
  16925. svr.wait_until_ready();
  16926. Client cli("localhost", port);
  16927. cli.set_read_timeout(1, 0); // 1 second timeout
  16928. auto handle = cli.open_stream("GET", "/slow-stream");
  16929. ASSERT_TRUE(handle.is_valid());
  16930. char buf[256];
  16931. ssize_t total = 0;
  16932. ssize_t n;
  16933. bool got_error = false;
  16934. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16935. total += n;
  16936. }
  16937. if (n < 0) {
  16938. got_error = true;
  16939. // Should be timeout or read error
  16940. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16941. handle.get_read_error() == Error::Read)
  16942. << "Actual error: " << to_string(handle.get_read_error());
  16943. }
  16944. // Either we got an error, or we got less data than expected
  16945. EXPECT_TRUE(got_error || total < 1000)
  16946. << "Expected timeout but got all " << total << " bytes";
  16947. svr.stop();
  16948. t.join();
  16949. }
  16950. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  16951. // Test connection closed detection via BodyReader
  16952. Server svr;
  16953. std::atomic<bool> close_now{false};
  16954. svr.Get("/will-close", [&](const Request &, Response &res) {
  16955. res.set_content_provider(
  16956. 10000, // Large content_length that we won't fully send
  16957. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16958. if (offset < 100) {
  16959. std::string data(100, 'X');
  16960. sink.write(data.c_str(), data.size());
  16961. return true;
  16962. }
  16963. // Wait for signal then abort
  16964. while (!close_now) {
  16965. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16966. }
  16967. return false; // Abort - server will close connection
  16968. });
  16969. });
  16970. auto port = 8092;
  16971. std::thread t([&]() { svr.listen("localhost", port); });
  16972. svr.wait_until_ready();
  16973. Client cli("localhost", port);
  16974. auto handle = cli.open_stream("GET", "/will-close");
  16975. ASSERT_TRUE(handle.is_valid());
  16976. char buf[256];
  16977. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16978. EXPECT_GT(n, 0) << "First read should succeed";
  16979. // Signal server to close
  16980. close_now = true;
  16981. // Keep reading until error or EOF
  16982. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16983. // Keep reading
  16984. }
  16985. // Should get an error since content_length wasn't satisfied
  16986. if (n < 0) {
  16987. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16988. handle.get_read_error() == Error::Read)
  16989. << "Actual error: " << to_string(handle.get_read_error());
  16990. }
  16991. svr.stop();
  16992. t.join();
  16993. }
  16994. #ifdef CPPHTTPLIB_SSL_ENABLED
  16995. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  16996. // Test that read timeout during SSL streaming is detected
  16997. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16998. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16999. res.set_content_provider(
  17000. 1000, "text/plain",
  17001. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17002. if (offset < 100) {
  17003. std::string data(100, 'A');
  17004. sink.write(data.c_str(), data.size());
  17005. return true;
  17006. }
  17007. std::this_thread::sleep_for(std::chrono::seconds(3));
  17008. std::string data(900, 'B');
  17009. sink.write(data.c_str(), data.size());
  17010. return true;
  17011. });
  17012. });
  17013. auto port = 8093;
  17014. std::thread t([&]() { svr.listen("localhost", port); });
  17015. svr.wait_until_ready();
  17016. SSLClient cli("localhost", port);
  17017. cli.enable_server_certificate_verification(false);
  17018. cli.set_read_timeout(1, 0); // 1 second timeout
  17019. auto handle = cli.open_stream("GET", "/slow-stream");
  17020. ASSERT_TRUE(handle.is_valid());
  17021. char buf[256];
  17022. ssize_t total = 0;
  17023. ssize_t n;
  17024. bool got_error = false;
  17025. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17026. total += n;
  17027. }
  17028. if (n < 0) {
  17029. got_error = true;
  17030. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17031. handle.get_read_error() == Error::Read)
  17032. << "Actual error: " << to_string(handle.get_read_error());
  17033. }
  17034. EXPECT_TRUE(got_error || total < 1000)
  17035. << "Expected timeout but got all " << total << " bytes";
  17036. svr.stop();
  17037. t.join();
  17038. }
  17039. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17040. // Test SSL connection closed detection
  17041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17042. std::atomic<bool> close_now{false};
  17043. svr.Get("/will-close", [&](const Request &, Response &res) {
  17044. res.set_content_provider(
  17045. 10000, "text/plain",
  17046. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17047. if (offset < 100) {
  17048. std::string data(100, 'X');
  17049. sink.write(data.c_str(), data.size());
  17050. return true;
  17051. }
  17052. while (!close_now) {
  17053. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17054. }
  17055. return false;
  17056. });
  17057. });
  17058. auto port = 8094;
  17059. std::thread t([&]() { svr.listen("localhost", port); });
  17060. svr.wait_until_ready();
  17061. SSLClient cli("localhost", port);
  17062. cli.enable_server_certificate_verification(false);
  17063. auto handle = cli.open_stream("GET", "/will-close");
  17064. ASSERT_TRUE(handle.is_valid());
  17065. char buf[256];
  17066. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17067. EXPECT_GT(n, 0);
  17068. // Signal server to close
  17069. close_now = true;
  17070. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17071. // Keep reading
  17072. }
  17073. if (n < 0) {
  17074. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17075. handle.get_read_error() == Error::Read)
  17076. << "Actual error: " << to_string(handle.get_read_error());
  17077. }
  17078. svr.stop();
  17079. t.join();
  17080. }
  17081. #endif
  17082. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17083. using namespace httplib;
  17084. // Create a test file
  17085. const char *fname = "etag_testfile.txt";
  17086. const char *content = "etag-content";
  17087. {
  17088. std::ofstream ofs(fname);
  17089. ofs << content;
  17090. ASSERT_TRUE(ofs.good());
  17091. }
  17092. Server svr;
  17093. svr.set_mount_point("/static", ".");
  17094. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17095. svr.wait_until_ready();
  17096. Client cli(HOST, PORT);
  17097. // First request: should get 200 with ETag header
  17098. auto res1 = cli.Get("/static/etag_testfile.txt");
  17099. ASSERT_TRUE(res1);
  17100. ASSERT_EQ(200, res1->status);
  17101. ASSERT_TRUE(res1->has_header("ETag"));
  17102. std::string etag = res1->get_header_value("ETag");
  17103. EXPECT_FALSE(etag.empty());
  17104. // Verify ETag format: W/"hex-hex"
  17105. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17106. EXPECT_EQ('W', etag[0]);
  17107. EXPECT_EQ('/', etag[1]);
  17108. EXPECT_EQ('"', etag[2]);
  17109. EXPECT_EQ('"', etag.back());
  17110. // Exact match: expect 304 Not Modified
  17111. Headers h2 = {{"If-None-Match", etag}};
  17112. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17113. ASSERT_TRUE(res2);
  17114. EXPECT_EQ(304, res2->status);
  17115. // Wildcard match: expect 304 Not Modified
  17116. Headers h3 = {{"If-None-Match", "*"}};
  17117. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17118. ASSERT_TRUE(res3);
  17119. EXPECT_EQ(304, res3->status);
  17120. // Non-matching ETag: expect 200
  17121. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17122. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17123. ASSERT_TRUE(res4);
  17124. EXPECT_EQ(200, res4->status);
  17125. // Multiple ETags with one matching: expect 304
  17126. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17127. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17128. ASSERT_TRUE(res5);
  17129. EXPECT_EQ(304, res5->status);
  17130. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17131. // that equivalent to the single comma-separated list above, so the match on
  17132. // the second line must still be found.
  17133. Headers h6;
  17134. h6.emplace("If-None-Match", "W/\"other\"");
  17135. h6.emplace("If-None-Match", etag);
  17136. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17137. ASSERT_TRUE(res6);
  17138. EXPECT_EQ(304, res6->status);
  17139. svr.stop();
  17140. t.join();
  17141. std::remove(fname);
  17142. }
  17143. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  17144. using namespace httplib;
  17145. Server svr;
  17146. svr.set_mount_point("/static", ".");
  17147. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17148. svr.wait_until_ready();
  17149. Client cli(HOST, PORT);
  17150. // Send If-None-Match: * to a non-existent file
  17151. Headers h = {{"If-None-Match", "*"}};
  17152. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  17153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17154. EXPECT_EQ(404, res->status);
  17155. svr.stop();
  17156. t.join();
  17157. }
  17158. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  17159. using namespace httplib;
  17160. // Create a test file
  17161. const char *fname = "etag_boundary_testfile.txt";
  17162. const char *content = "boundary-test";
  17163. {
  17164. std::ofstream ofs(fname);
  17165. ofs << content;
  17166. ASSERT_TRUE(ofs.good());
  17167. }
  17168. Server svr;
  17169. svr.set_mount_point("/static", ".");
  17170. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17171. svr.wait_until_ready();
  17172. Client cli(HOST, PORT);
  17173. // Get the actual ETag
  17174. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  17175. ASSERT_TRUE(res1);
  17176. ASSERT_EQ(200, res1->status);
  17177. ASSERT_TRUE(res1->has_header("ETag"));
  17178. std::string etag = res1->get_header_value("ETag");
  17179. // Test 1: Very long ETag value (longer than actual ETag)
  17180. // Should NOT match and return 200 (not trigger out-of-bounds read)
  17181. Headers h1 = {{"If-None-Match", "W/"
  17182. "\"very-long-etag-value-that-is-much-longer-"
  17183. "than-the-actual-etag-value\""}};
  17184. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  17185. ASSERT_TRUE(res2);
  17186. EXPECT_EQ(200, res2->status); // Should not match
  17187. // Test 2: Long string followed by wildcard
  17188. // Should match on "*" and return 304 (without out-of-bounds read on the long
  17189. // string)
  17190. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  17191. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  17192. ASSERT_TRUE(res3);
  17193. EXPECT_EQ(304, res3->status); // Should match on "*"
  17194. // Test 3: Wildcard followed by long string
  17195. // Should match on "*" immediately and return 304
  17196. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  17197. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  17198. ASSERT_TRUE(res4);
  17199. EXPECT_EQ(304, res4->status); // Should match on "*"
  17200. // Test 4: Multiple long non-matching values
  17201. // Should NOT match and return 200 (test that all comparisons are safe)
  17202. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  17203. "W/\"second-long-non-matching-value\", "
  17204. "W/\"third-long-non-matching-value\""}};
  17205. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  17206. ASSERT_TRUE(res5);
  17207. EXPECT_EQ(200, res5->status); // Should not match
  17208. // Test 5: Single character that is not "*" (edge case)
  17209. Headers h5 = {{"If-None-Match", "X"}};
  17210. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  17211. ASSERT_TRUE(res6);
  17212. EXPECT_EQ(200, res6->status); // Should not match
  17213. svr.stop();
  17214. t.join();
  17215. std::remove(fname);
  17216. }
  17217. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  17218. using namespace httplib;
  17219. // Create a test file
  17220. const char *fname = "ims_testfile.txt";
  17221. const char *content = "if-modified-since-test";
  17222. {
  17223. std::ofstream ofs(fname);
  17224. ofs << content;
  17225. ASSERT_TRUE(ofs.good());
  17226. }
  17227. Server svr;
  17228. svr.set_mount_point("/static", ".");
  17229. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17230. svr.wait_until_ready();
  17231. Client cli(HOST, PORT);
  17232. // First request: should get 200 with Last-Modified header
  17233. auto res1 = cli.Get("/static/ims_testfile.txt");
  17234. ASSERT_TRUE(res1);
  17235. ASSERT_EQ(200, res1->status);
  17236. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17237. std::string last_modified = res1->get_header_value("Last-Modified");
  17238. EXPECT_FALSE(last_modified.empty());
  17239. // If-Modified-Since with same time: expect 304
  17240. Headers h2 = {{"If-Modified-Since", last_modified}};
  17241. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  17242. ASSERT_TRUE(res2);
  17243. EXPECT_EQ(304, res2->status);
  17244. // If-Modified-Since with future time: expect 304
  17245. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17246. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  17247. ASSERT_TRUE(res3);
  17248. EXPECT_EQ(304, res3->status);
  17249. // If-Modified-Since with past time: expect 200
  17250. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17251. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  17252. ASSERT_TRUE(res4);
  17253. EXPECT_EQ(200, res4->status);
  17254. // If-None-Match takes precedence over If-Modified-Since
  17255. // (send matching ETag with old If-Modified-Since -> should still be 304)
  17256. ASSERT_TRUE(res1->has_header("ETag"));
  17257. std::string etag = res1->get_header_value("ETag");
  17258. Headers h5 = {{"If-None-Match", etag},
  17259. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17260. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  17261. ASSERT_TRUE(res5);
  17262. EXPECT_EQ(304, res5->status);
  17263. svr.stop();
  17264. t.join();
  17265. std::remove(fname);
  17266. }
  17267. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  17268. using namespace httplib;
  17269. Server svr;
  17270. // Endpoint that returns compressible content
  17271. svr.Get("/compressible", [](const Request &, Response &res) {
  17272. // Return a large enough body to trigger compression
  17273. std::string body(1000, 'a');
  17274. res.set_content(body, "text/plain");
  17275. });
  17276. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17277. svr.wait_until_ready();
  17278. Client cli(HOST, PORT);
  17279. // Request with gzip support: should get Vary header when compressed
  17280. cli.set_compress(true);
  17281. auto res1 = cli.Get("/compressible");
  17282. ASSERT_TRUE(res1);
  17283. EXPECT_EQ(200, res1->status);
  17284. // If Content-Encoding is set, Vary should also be set
  17285. if (res1->has_header("Content-Encoding")) {
  17286. EXPECT_TRUE(res1->has_header("Vary"));
  17287. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  17288. }
  17289. // Request without Accept-Encoding header: should not have compression
  17290. Headers h_no_compress;
  17291. auto res2 = cli.Get("/compressible", h_no_compress);
  17292. ASSERT_TRUE(res2);
  17293. EXPECT_EQ(200, res2->status);
  17294. // Verify Vary header is present when compression is applied
  17295. // (the exact behavior depends on server configuration)
  17296. svr.stop();
  17297. t.join();
  17298. }
  17299. TEST(ETagTest, IfRangeWithETag) {
  17300. using namespace httplib;
  17301. // Create a test file with known content
  17302. const char *fname = "if_range_testfile.txt";
  17303. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  17304. {
  17305. std::ofstream ofs(fname);
  17306. ofs << content;
  17307. ASSERT_TRUE(ofs.good());
  17308. }
  17309. Server svr;
  17310. svr.set_mount_point("/static", ".");
  17311. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17312. svr.wait_until_ready();
  17313. Client cli(HOST, PORT);
  17314. // First request: get ETag
  17315. auto res1 = cli.Get("/static/if_range_testfile.txt");
  17316. ASSERT_TRUE(res1);
  17317. ASSERT_EQ(200, res1->status);
  17318. ASSERT_TRUE(res1->has_header("ETag"));
  17319. std::string etag = res1->get_header_value("ETag");
  17320. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  17321. // Since our server generates weak ETags (W/"..."), If-Range with our
  17322. // ETag should NOT result in partial content - it should return full content.
  17323. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  17324. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  17325. ASSERT_TRUE(res2);
  17326. // Weak ETag in If-Range -> full content (200), not partial (206)
  17327. EXPECT_EQ(200, res2->status);
  17328. EXPECT_EQ(content, res2->body);
  17329. EXPECT_FALSE(res2->has_header("Content-Range"));
  17330. // Range request with non-matching If-Range (ETag): should get 200 (full
  17331. // content)
  17332. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  17333. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  17334. ASSERT_TRUE(res3);
  17335. EXPECT_EQ(200, res3->status);
  17336. EXPECT_EQ(content, res3->body);
  17337. EXPECT_FALSE(res3->has_header("Content-Range"));
  17338. // Range request with strong ETag (hypothetical - our server doesn't generate
  17339. // strong ETags, but if client sends a strong ETag that doesn't match, it
  17340. // should return full content)
  17341. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  17342. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  17343. ASSERT_TRUE(res4);
  17344. EXPECT_EQ(200, res4->status);
  17345. EXPECT_EQ(content, res4->body);
  17346. EXPECT_FALSE(res4->has_header("Content-Range"));
  17347. svr.stop();
  17348. t.join();
  17349. std::remove(fname);
  17350. }
  17351. TEST(ETagTest, IfRangeWithDate) {
  17352. using namespace httplib;
  17353. // Create a test file
  17354. const char *fname = "if_range_date_testfile.txt";
  17355. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  17356. {
  17357. std::ofstream ofs(fname);
  17358. ofs << content;
  17359. ASSERT_TRUE(ofs.good());
  17360. }
  17361. Server svr;
  17362. svr.set_mount_point("/static", ".");
  17363. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17364. svr.wait_until_ready();
  17365. Client cli(HOST, PORT);
  17366. // First request: get Last-Modified
  17367. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  17368. ASSERT_TRUE(res1);
  17369. ASSERT_EQ(200, res1->status);
  17370. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17371. std::string last_modified = res1->get_header_value("Last-Modified");
  17372. // Range request with matching If-Range (date): should get 206
  17373. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  17374. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  17375. ASSERT_TRUE(res2);
  17376. EXPECT_EQ(206, res2->status);
  17377. EXPECT_EQ("FGHIJ", res2->body);
  17378. // Range request with old If-Range date: should get 200 (full content)
  17379. Headers h3 = {{"Range", "bytes=5-9"},
  17380. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17381. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  17382. ASSERT_TRUE(res3);
  17383. EXPECT_EQ(200, res3->status);
  17384. EXPECT_EQ(content, res3->body);
  17385. // Range request with future If-Range date: should get 206
  17386. Headers h4 = {{"Range", "bytes=0-4"},
  17387. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17388. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  17389. ASSERT_TRUE(res4);
  17390. EXPECT_EQ(206, res4->status);
  17391. EXPECT_EQ("ABCDE", res4->body);
  17392. svr.stop();
  17393. t.join();
  17394. std::remove(fname);
  17395. }
  17396. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  17397. using namespace httplib;
  17398. const char *fname = "etag_malformed.txt";
  17399. const char *content = "malformed-etag";
  17400. {
  17401. std::ofstream ofs(fname);
  17402. ofs << content;
  17403. ASSERT_TRUE(ofs.good());
  17404. }
  17405. Server svr;
  17406. svr.set_mount_point("/static", ".");
  17407. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17408. svr.wait_until_ready();
  17409. Client cli(HOST, PORT);
  17410. // baseline: should get 200 and an ETag
  17411. auto res1 = cli.Get("/static/etag_malformed.txt");
  17412. ASSERT_TRUE(res1);
  17413. ASSERT_EQ(200, res1->status);
  17414. ASSERT_TRUE(res1->has_header("ETag"));
  17415. // Malformed ETag value (missing quotes) should be treated as non-matching
  17416. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  17417. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  17418. ASSERT_TRUE(res_bad);
  17419. EXPECT_EQ(200, res_bad->status);
  17420. // Whitespace-only header value should be considered invalid / non-matching
  17421. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  17422. "Host: localhost\r\n"
  17423. "If-None-Match: \r\n"
  17424. "Connection: close\r\n"
  17425. "\r\n";
  17426. std::string out;
  17427. ASSERT_TRUE(send_request(5, raw_req, &out));
  17428. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17429. svr.stop();
  17430. t.join();
  17431. std::remove(fname);
  17432. }
  17433. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  17434. using namespace httplib;
  17435. const char *fname = "ims_invalid_format.txt";
  17436. const char *content = "ims-bad-format";
  17437. {
  17438. std::ofstream ofs(fname);
  17439. ofs << content;
  17440. ASSERT_TRUE(ofs.good());
  17441. }
  17442. Server svr;
  17443. svr.set_mount_point("/static", ".");
  17444. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17445. svr.wait_until_ready();
  17446. Client cli(HOST, PORT);
  17447. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  17448. ASSERT_TRUE(res1);
  17449. ASSERT_EQ(200, res1->status);
  17450. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17451. // If-Modified-Since with invalid format should not result in 304
  17452. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  17453. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  17454. ASSERT_TRUE(res_bad);
  17455. EXPECT_EQ(200, res_bad->status);
  17456. // If-Range with invalid date format should be treated as mismatch -> full
  17457. // content (200)
  17458. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  17459. {"If-Range", "invalid-date"}};
  17460. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  17461. ASSERT_TRUE(res_ifrange);
  17462. EXPECT_EQ(200, res_ifrange->status);
  17463. svr.stop();
  17464. t.join();
  17465. std::remove(fname);
  17466. }
  17467. TEST(ETagTest, IfRangeWithMalformedETag) {
  17468. using namespace httplib;
  17469. const char *fname = "ifrange_malformed.txt";
  17470. const std::string content = "0123456789";
  17471. {
  17472. std::ofstream ofs(fname);
  17473. ofs << content;
  17474. ASSERT_TRUE(ofs.good());
  17475. }
  17476. Server svr;
  17477. svr.set_mount_point("/static", ".");
  17478. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17479. svr.wait_until_ready();
  17480. Client cli(HOST, PORT);
  17481. // First request: get ETag
  17482. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  17483. ASSERT_TRUE(res1);
  17484. ASSERT_EQ(200, res1->status);
  17485. ASSERT_TRUE(res1->has_header("ETag"));
  17486. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  17487. // full content (200)
  17488. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  17489. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  17490. ASSERT_TRUE(res2);
  17491. EXPECT_EQ(200, res2->status);
  17492. EXPECT_EQ(content, res2->body);
  17493. svr.stop();
  17494. t.join();
  17495. std::remove(fname);
  17496. }
  17497. TEST(ETagTest, ExtremeLargeDateValues) {
  17498. using namespace httplib;
  17499. const char *fname = "ims_extreme_date.txt";
  17500. const char *content = "ims-extreme-date";
  17501. {
  17502. std::ofstream ofs(fname);
  17503. ofs << content;
  17504. ASSERT_TRUE(ofs.good());
  17505. }
  17506. Server svr;
  17507. svr.set_mount_point("/static", ".");
  17508. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17509. svr.wait_until_ready();
  17510. Client cli(HOST, PORT);
  17511. auto res1 = cli.Get(std::string("/static/") + fname);
  17512. ASSERT_TRUE(res1);
  17513. ASSERT_EQ(200, res1->status);
  17514. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17515. // Extremely large year that may overflow date parsing routines.
  17516. Headers h_large_date = {
  17517. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17518. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  17519. ASSERT_TRUE(res_bad);
  17520. // Expect server to treat this as invalid/mismatch and return full content
  17521. EXPECT_EQ(200, res_bad->status);
  17522. // If-Range with extremely large date should be treated as mismatch -> full
  17523. // content (200)
  17524. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  17525. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17526. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  17527. ASSERT_TRUE(res_ifrange);
  17528. EXPECT_EQ(200, res_ifrange->status);
  17529. svr.stop();
  17530. t.join();
  17531. std::remove(fname);
  17532. }
  17533. TEST(ETagTest, NegativeFileModificationTime) {
  17534. using namespace httplib;
  17535. const char *fname = "ims_negative_mtime.txt";
  17536. const std::string content = "negative-mtime";
  17537. {
  17538. std::ofstream ofs(fname);
  17539. ofs << content;
  17540. ASSERT_TRUE(ofs.good());
  17541. }
  17542. // Try to set file mtime to a negative value. This may fail on some
  17543. // platforms/filesystems; if it fails, the test will still verify server
  17544. // behaves safely by performing a regular conditional request.
  17545. #if defined(__APPLE__) || defined(__linux__)
  17546. bool set_negative = false;
  17547. do {
  17548. struct timeval times[2];
  17549. // access time: now
  17550. times[0].tv_sec = time(nullptr);
  17551. times[0].tv_usec = 0;
  17552. // modification time: negative (e.g., -1)
  17553. times[1].tv_sec = -1;
  17554. times[1].tv_usec = 0;
  17555. if (utimes(fname, times) == 0) { set_negative = true; }
  17556. } while (0);
  17557. #else
  17558. bool set_negative = false;
  17559. #endif
  17560. Server svr;
  17561. svr.set_mount_point("/static", ".");
  17562. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17563. svr.wait_until_ready();
  17564. Client cli(HOST, PORT);
  17565. auto res1 = cli.Get(std::string("/static/") + fname);
  17566. ASSERT_TRUE(res1);
  17567. ASSERT_EQ(200, res1->status);
  17568. bool has_last_modified = res1->has_header("Last-Modified");
  17569. std::string last_modified;
  17570. if (has_last_modified) {
  17571. last_modified = res1->get_header_value("Last-Modified");
  17572. }
  17573. if (set_negative) {
  17574. // If we successfully set a negative mtime, ensure server returns a
  17575. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  17576. // with an old date and ensure server handles it without crash.
  17577. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  17578. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  17579. ASSERT_TRUE(res2);
  17580. // Behavior may vary; at minimum ensure server responds (200 or 304).
  17581. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  17582. } else {
  17583. // Could not set negative mtime on this platform; fall back to verifying
  17584. // that normal invalid/malformed dates are treated safely (non-304).
  17585. Headers h_bad_date = {
  17586. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17587. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  17588. ASSERT_TRUE(res_bad);
  17589. EXPECT_EQ(200, res_bad->status);
  17590. }
  17591. svr.stop();
  17592. t.join();
  17593. std::remove(fname);
  17594. }
  17595. //==============================================================================
  17596. // SSE Parsing Tests
  17597. //==============================================================================
  17598. class SSEParsingTest : public ::testing::Test {
  17599. protected:
  17600. // Test helper that mimics SSE parsing behavior
  17601. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  17602. int &retry_ms) {
  17603. // Blank line signals end of event
  17604. if (line.empty() || line == "\r") { return true; }
  17605. // Lines starting with ':' are comments (ignored)
  17606. if (!line.empty() && line[0] == ':') { return false; }
  17607. // Find the colon separator
  17608. auto colon_pos = line.find(':');
  17609. if (colon_pos == std::string::npos) {
  17610. // Line with no colon is treated as field name with empty value
  17611. return false;
  17612. }
  17613. std::string field = line.substr(0, colon_pos);
  17614. std::string value;
  17615. // Value starts after colon, skip optional single space
  17616. if (colon_pos + 1 < line.size()) {
  17617. size_t value_start = colon_pos + 1;
  17618. if (line[value_start] == ' ') { value_start++; }
  17619. value = line.substr(value_start);
  17620. // Remove trailing \r if present
  17621. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  17622. }
  17623. // Handle known fields
  17624. if (field == "event") {
  17625. msg.event = value;
  17626. } else if (field == "data") {
  17627. // Multiple data lines are concatenated with newlines
  17628. if (!msg.data.empty()) { msg.data += "\n"; }
  17629. msg.data += value;
  17630. } else if (field == "id") {
  17631. // Empty id is valid (clears the last event ID)
  17632. msg.id = value;
  17633. } else if (field == "retry") {
  17634. // Parse retry interval in milliseconds
  17635. {
  17636. int v = 0;
  17637. auto res =
  17638. detail::from_chars(value.data(), value.data() + value.size(), v);
  17639. if (res.ec == std::errc{}) { retry_ms = v; }
  17640. }
  17641. }
  17642. // Unknown fields are ignored per SSE spec
  17643. return false;
  17644. }
  17645. };
  17646. // Test: Single-line data
  17647. TEST_F(SSEParsingTest, SingleLineData) {
  17648. sse::SSEMessage msg;
  17649. int retry_ms = 3000;
  17650. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  17651. EXPECT_EQ(msg.data, "hello");
  17652. EXPECT_EQ(msg.event, "message");
  17653. // Blank line ends event
  17654. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17655. }
  17656. // Test: Multi-line data
  17657. TEST_F(SSEParsingTest, MultiLineData) {
  17658. sse::SSEMessage msg;
  17659. int retry_ms = 3000;
  17660. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  17661. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  17662. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  17663. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  17664. }
  17665. // Test: Custom event types
  17666. TEST_F(SSEParsingTest, CustomEventType) {
  17667. sse::SSEMessage msg;
  17668. int retry_ms = 3000;
  17669. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  17670. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  17671. EXPECT_EQ(msg.event, "update");
  17672. EXPECT_EQ(msg.data, "payload");
  17673. }
  17674. // Test: Event ID handling
  17675. TEST_F(SSEParsingTest, EventIdHandling) {
  17676. sse::SSEMessage msg;
  17677. int retry_ms = 3000;
  17678. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  17679. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  17680. EXPECT_EQ(msg.id, "12345");
  17681. }
  17682. // Test: Empty event ID (clears last event ID)
  17683. TEST_F(SSEParsingTest, EmptyEventId) {
  17684. sse::SSEMessage msg;
  17685. msg.id = "previous";
  17686. int retry_ms = 3000;
  17687. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  17688. EXPECT_EQ(msg.id, "");
  17689. }
  17690. // Test: Retry field parsing
  17691. TEST_F(SSEParsingTest, RetryFieldParsing) {
  17692. sse::SSEMessage msg;
  17693. int retry_ms = 3000;
  17694. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  17695. EXPECT_EQ(retry_ms, 5000);
  17696. }
  17697. // Test: Invalid retry value
  17698. TEST_F(SSEParsingTest, InvalidRetryValue) {
  17699. sse::SSEMessage msg;
  17700. int retry_ms = 3000;
  17701. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  17702. EXPECT_EQ(retry_ms, 3000); // Unchanged
  17703. }
  17704. // Test: Comments (lines starting with :)
  17705. TEST_F(SSEParsingTest, CommentsIgnored) {
  17706. sse::SSEMessage msg;
  17707. int retry_ms = 3000;
  17708. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  17709. EXPECT_EQ(msg.data, "");
  17710. EXPECT_EQ(msg.event, "message");
  17711. }
  17712. // Test: Colon in value
  17713. TEST_F(SSEParsingTest, ColonInValue) {
  17714. sse::SSEMessage msg;
  17715. int retry_ms = 3000;
  17716. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  17717. EXPECT_EQ(msg.data, "hello:world:test");
  17718. }
  17719. // Test: Line with no colon (field name only)
  17720. TEST_F(SSEParsingTest, FieldNameOnly) {
  17721. sse::SSEMessage msg;
  17722. int retry_ms = 3000;
  17723. // According to SSE spec, this is treated as field name with empty value
  17724. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  17725. // Since we don't recognize "data" without colon, data should be empty
  17726. EXPECT_EQ(msg.data, "");
  17727. }
  17728. // Test: Trailing \r handling
  17729. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  17730. sse::SSEMessage msg;
  17731. int retry_ms = 3000;
  17732. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  17733. EXPECT_EQ(msg.data, "hello");
  17734. }
  17735. // Test: Unknown fields ignored
  17736. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  17737. sse::SSEMessage msg;
  17738. int retry_ms = 3000;
  17739. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  17740. EXPECT_EQ(msg.data, "");
  17741. EXPECT_EQ(msg.event, "message");
  17742. }
  17743. // Test: Space after colon is optional
  17744. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  17745. sse::SSEMessage msg1, msg2;
  17746. int retry_ms = 3000;
  17747. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  17748. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  17749. EXPECT_EQ(msg1.data, "hello");
  17750. EXPECT_EQ(msg2.data, "hello");
  17751. }
  17752. // Test: SSEMessage clear
  17753. TEST_F(SSEParsingTest, MessageClear) {
  17754. sse::SSEMessage msg;
  17755. msg.event = "custom";
  17756. msg.data = "some data";
  17757. msg.id = "123";
  17758. msg.clear();
  17759. EXPECT_EQ(msg.event, "message");
  17760. EXPECT_EQ(msg.data, "");
  17761. EXPECT_EQ(msg.id, "");
  17762. }
  17763. // Test: Complete event parsing
  17764. TEST_F(SSEParsingTest, CompleteEventParsing) {
  17765. sse::SSEMessage msg;
  17766. int retry_ms = 3000;
  17767. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  17768. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  17769. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  17770. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  17771. // Blank line ends event
  17772. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17773. EXPECT_EQ(msg.event, "notification");
  17774. EXPECT_EQ(msg.id, "evt-42");
  17775. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  17776. EXPECT_EQ(retry_ms, 1000);
  17777. }
  17778. //==============================================================================
  17779. // Integration Tests with Server
  17780. //==============================================================================
  17781. class SSEIntegrationTest : public ::testing::Test {
  17782. protected:
  17783. void SetUp() override {
  17784. stop_server_.store(false);
  17785. events_.clear();
  17786. server_ = httplib::detail::make_unique<Server>();
  17787. setup_server();
  17788. start_server();
  17789. }
  17790. void TearDown() override {
  17791. stop_server_.store(true);
  17792. event_cv_.notify_all();
  17793. server_->stop();
  17794. if (server_thread_.joinable()) { server_thread_.join(); }
  17795. }
  17796. void setup_server() {
  17797. // Simple SSE endpoint
  17798. server_->Get("/events", [this](const Request &req, Response &res) {
  17799. auto last_id = req.get_header_value("Last-Event-ID");
  17800. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  17801. res.set_chunked_content_provider(
  17802. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  17803. std::unique_lock<std::mutex> lock(event_mutex_);
  17804. if (event_cv_.wait_for(
  17805. lock, std::chrono::milliseconds(200), [this] {
  17806. return !events_.empty() || stop_server_.load();
  17807. })) {
  17808. if (stop_server_.load()) { return false; }
  17809. if (!events_.empty()) {
  17810. std::string event = events_.front();
  17811. events_.erase(events_.begin());
  17812. sink.write(event.data(), event.size());
  17813. return true;
  17814. }
  17815. }
  17816. return !stop_server_.load();
  17817. });
  17818. });
  17819. // Endpoint that returns error
  17820. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  17821. res.status = 500;
  17822. res.set_content("Internal Server Error", "text/plain");
  17823. });
  17824. // Endpoint for custom event types
  17825. server_->Get("/custom-events", [](const Request &, Response &res) {
  17826. res.set_chunked_content_provider(
  17827. "text/event-stream", [](size_t offset, DataSink &sink) {
  17828. if (offset == 0) {
  17829. std::string event = "event: update\ndata: updated\n\n"
  17830. "event: delete\ndata: deleted\n\n";
  17831. sink.write(event.data(), event.size());
  17832. }
  17833. return false; // End stream after sending
  17834. });
  17835. });
  17836. }
  17837. void start_server() {
  17838. port_ = server_->bind_to_any_port(HOST);
  17839. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17840. // Wait for server to start
  17841. while (!server_->is_running()) {
  17842. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17843. }
  17844. }
  17845. int get_port() const { return port_; }
  17846. void send_event(const std::string &event) {
  17847. std::lock_guard<std::mutex> lock(event_mutex_);
  17848. events_.push_back(event);
  17849. event_cv_.notify_all();
  17850. }
  17851. std::unique_ptr<Server> server_;
  17852. std::thread server_thread_;
  17853. std::mutex event_mutex_;
  17854. std::condition_variable event_cv_;
  17855. std::vector<std::string> events_;
  17856. std::atomic<bool> stop_server_{false};
  17857. std::string last_received_event_id_;
  17858. int port_ = 0;
  17859. };
  17860. // Test: Successful connection and on_open callback
  17861. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  17862. // Add a simple endpoint that sends one event and closes
  17863. server_->Get("/simple-event", [](const Request &, Response &res) {
  17864. res.set_chunked_content_provider(
  17865. "text/event-stream", [](size_t offset, DataSink &sink) {
  17866. if (offset == 0) {
  17867. std::string event = "data: hello\n\n";
  17868. sink.write(event.data(), event.size());
  17869. }
  17870. return false; // Close stream after sending
  17871. });
  17872. });
  17873. Client client("localhost", get_port());
  17874. sse::SSEClient sse(client, "/simple-event");
  17875. std::atomic<bool> open_called{false};
  17876. std::atomic<bool> message_received{false};
  17877. sse.on_open([&open_called]() { open_called.store(true); });
  17878. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  17879. if (msg.data == "hello") { message_received.store(true); }
  17880. });
  17881. sse.set_reconnect_interval(100);
  17882. sse.set_max_reconnect_attempts(1);
  17883. // Start async
  17884. sse.start_async();
  17885. // Wait for message to be processed
  17886. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17887. sse.stop();
  17888. EXPECT_TRUE(open_called.load());
  17889. EXPECT_TRUE(message_received.load());
  17890. }
  17891. // Test: on_message callback
  17892. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  17893. // Endpoint that sends multiple events then closes
  17894. server_->Get("/multi-event", [](const Request &, Response &res) {
  17895. res.set_chunked_content_provider(
  17896. "text/event-stream", [](size_t offset, DataSink &sink) {
  17897. if (offset == 0) {
  17898. std::string events = "data: message1\n\ndata: message2\n\n";
  17899. sink.write(events.data(), events.size());
  17900. }
  17901. return false;
  17902. });
  17903. });
  17904. Client client("localhost", get_port());
  17905. sse::SSEClient sse(client, "/multi-event");
  17906. std::vector<std::string> received_messages;
  17907. std::mutex messages_mutex;
  17908. sse.on_message([&](const sse::SSEMessage &msg) {
  17909. std::lock_guard<std::mutex> lock(messages_mutex);
  17910. received_messages.push_back(msg.data);
  17911. });
  17912. sse.set_reconnect_interval(100);
  17913. sse.set_max_reconnect_attempts(1);
  17914. sse.start_async();
  17915. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17916. sse.stop();
  17917. std::lock_guard<std::mutex> lock(messages_mutex);
  17918. EXPECT_GE(received_messages.size(), 2u);
  17919. if (received_messages.size() >= 2) {
  17920. EXPECT_EQ(received_messages[0], "message1");
  17921. EXPECT_EQ(received_messages[1], "message2");
  17922. }
  17923. }
  17924. // Test: on_event for specific types
  17925. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  17926. Client client("localhost", get_port());
  17927. sse::SSEClient sse(client, "/custom-events");
  17928. std::atomic<bool> update_received{false};
  17929. std::atomic<bool> delete_received{false};
  17930. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  17931. if (msg.data == "updated") { update_received.store(true); }
  17932. });
  17933. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  17934. if (msg.data == "deleted") { delete_received.store(true); }
  17935. });
  17936. sse.set_max_reconnect_attempts(1);
  17937. sse.start_async();
  17938. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  17939. sse.stop();
  17940. EXPECT_TRUE(update_received.load());
  17941. EXPECT_TRUE(delete_received.load());
  17942. }
  17943. // Test: on_error callback on connection failure
  17944. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  17945. // Connect to a non-existent port
  17946. Client client("localhost", 59999);
  17947. sse::SSEClient sse(client, "/events");
  17948. std::atomic<bool> error_called{false};
  17949. Error received_error = Error::Success;
  17950. sse.on_error([&](Error err) {
  17951. error_called.store(true);
  17952. received_error = err;
  17953. });
  17954. sse.set_reconnect_interval(50);
  17955. sse.set_max_reconnect_attempts(1);
  17956. sse.start_async();
  17957. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17958. sse.stop();
  17959. EXPECT_TRUE(error_called.load());
  17960. EXPECT_NE(received_error, Error::Success);
  17961. }
  17962. // Test: Last-Event-ID header sent on reconnect
  17963. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  17964. // Endpoint that sends event with ID
  17965. server_->Get("/event-with-id", [](const Request &, Response &res) {
  17966. res.set_chunked_content_provider(
  17967. "text/event-stream", [](size_t offset, DataSink &sink) {
  17968. if (offset == 0) {
  17969. std::string event = "id: evt-123\ndata: test\n\n";
  17970. sink.write(event.data(), event.size());
  17971. }
  17972. return false;
  17973. });
  17974. });
  17975. Client client("localhost", get_port());
  17976. sse::SSEClient sse(client, "/event-with-id");
  17977. std::atomic<bool> id_received{false};
  17978. sse.on_message([&](const sse::SSEMessage &msg) {
  17979. if (!msg.id.empty()) { id_received.store(true); }
  17980. });
  17981. sse.set_reconnect_interval(100);
  17982. sse.set_max_reconnect_attempts(1);
  17983. sse.start_async();
  17984. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17985. sse.stop();
  17986. EXPECT_TRUE(id_received.load());
  17987. EXPECT_EQ(sse.last_event_id(), "evt-123");
  17988. }
  17989. // Test: Manual stop
  17990. TEST_F(SSEIntegrationTest, ManualStop) {
  17991. // Endpoint that sends one event and stays open briefly
  17992. std::atomic<bool> handler_running{true};
  17993. server_->Get("/stay-open", [&handler_running](const Request &,
  17994. Response &res) {
  17995. res.set_chunked_content_provider(
  17996. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  17997. if (offset == 0) {
  17998. std::string event = "data: connected\n\n";
  17999. sink.write(event.data(), event.size());
  18000. }
  18001. // Keep connection open while handler_running is true
  18002. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18003. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18004. }
  18005. return false;
  18006. });
  18007. });
  18008. Client client("localhost", get_port());
  18009. sse::SSEClient sse(client, "/stay-open");
  18010. std::atomic<bool> connected{false};
  18011. sse.on_open([&connected]() { connected.store(true); });
  18012. sse.set_reconnect_interval(100);
  18013. sse.set_max_reconnect_attempts(1);
  18014. sse.start_async();
  18015. // Wait for connection to establish
  18016. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18017. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18018. }
  18019. EXPECT_TRUE(connected.load());
  18020. EXPECT_TRUE(sse.is_connected());
  18021. // Signal handler to stop
  18022. handler_running.store(false);
  18023. // Stop SSE client
  18024. sse.stop();
  18025. EXPECT_FALSE(sse.is_connected());
  18026. }
  18027. // Test: SSEClient with custom headers
  18028. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18029. // Setup a server endpoint that checks for custom header
  18030. std::atomic<bool> header_received{false};
  18031. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18032. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18033. header_received.store(true);
  18034. }
  18035. res.set_chunked_content_provider("text/event-stream",
  18036. [](size_t, DataSink &) { return false; });
  18037. });
  18038. Client client("localhost", get_port());
  18039. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18040. sse::SSEClient sse(client, "/header-check", headers);
  18041. sse.set_max_reconnect_attempts(1);
  18042. sse.start_async();
  18043. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18044. sse.stop();
  18045. EXPECT_TRUE(header_received.load());
  18046. }
  18047. // Test: Reconnect interval configuration
  18048. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18049. Client client("localhost", get_port());
  18050. sse::SSEClient sse(client, "/events");
  18051. auto &result = sse.set_reconnect_interval(500);
  18052. // Builder pattern should return reference to self
  18053. EXPECT_EQ(&result, &sse);
  18054. }
  18055. // Test: Max reconnect attempts
  18056. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18057. // Connect to non-existent port to force reconnects
  18058. Client client("localhost", 59998);
  18059. sse::SSEClient sse(client, "/events");
  18060. std::atomic<int> error_count{0};
  18061. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18062. sse.set_reconnect_interval(50);
  18063. sse.set_max_reconnect_attempts(2);
  18064. auto start = std::chrono::steady_clock::now();
  18065. sse.start(); // Blocking call
  18066. auto end = std::chrono::steady_clock::now();
  18067. // Should have stopped after 2 failed attempts
  18068. EXPECT_GE(error_count.load(), 2);
  18069. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18070. auto duration =
  18071. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18072. #ifdef _WIN32
  18073. // Windows is much slower for socket connection failures
  18074. EXPECT_LT(duration.count(), 7000);
  18075. #else
  18076. EXPECT_LT(duration.count(), 1000);
  18077. #endif
  18078. }
  18079. // Test: Multi-line data in integration
  18080. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18081. // Endpoint with multi-line data
  18082. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18083. res.set_chunked_content_provider(
  18084. "text/event-stream", [](size_t offset, DataSink &sink) {
  18085. if (offset == 0) {
  18086. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18087. sink.write(event.data(), event.size());
  18088. }
  18089. return false;
  18090. });
  18091. });
  18092. Client client("localhost", get_port());
  18093. sse::SSEClient sse(client, "/multiline-data");
  18094. std::string received_data;
  18095. std::mutex data_mutex;
  18096. sse.on_message([&](const sse::SSEMessage &msg) {
  18097. std::lock_guard<std::mutex> lock(data_mutex);
  18098. received_data = msg.data;
  18099. });
  18100. sse.set_reconnect_interval(100);
  18101. sse.set_max_reconnect_attempts(1);
  18102. sse.start_async();
  18103. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18104. sse.stop();
  18105. std::lock_guard<std::mutex> lock(data_mutex);
  18106. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18107. }
  18108. // Test: Auto-reconnect after server disconnection
  18109. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18110. std::atomic<int> connection_count{0};
  18111. std::atomic<int> message_count{0};
  18112. // Endpoint that sends one event and closes, forcing reconnect
  18113. server_->Get("/reconnect-test",
  18114. [&connection_count](const Request &, Response &res) {
  18115. connection_count.fetch_add(1);
  18116. res.set_chunked_content_provider(
  18117. "text/event-stream", [](size_t offset, DataSink &sink) {
  18118. if (offset == 0) {
  18119. std::string event = "data: hello\n\n";
  18120. sink.write(event.data(), event.size());
  18121. }
  18122. return false; // Close connection after sending
  18123. });
  18124. });
  18125. Client client("localhost", get_port());
  18126. sse::SSEClient sse(client, "/reconnect-test");
  18127. sse.on_message([&message_count](const sse::SSEMessage &) {
  18128. message_count.fetch_add(1);
  18129. });
  18130. sse.set_reconnect_interval(100);
  18131. sse.set_max_reconnect_attempts(3);
  18132. sse.start_async();
  18133. // Wait long enough for multiple reconnects
  18134. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18135. sse.stop();
  18136. // Should have connected multiple times (initial + reconnects)
  18137. EXPECT_GE(connection_count.load(), 2);
  18138. // Should have received messages from multiple connections
  18139. EXPECT_GE(message_count.load(), 2);
  18140. }
  18141. // Test: Last-Event-ID sent on reconnect
  18142. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  18143. std::atomic<int> connection_count{0};
  18144. std::vector<std::string> received_last_event_ids;
  18145. std::mutex id_mutex;
  18146. // Endpoint that checks Last-Event-ID header and sends event with ID
  18147. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  18148. int conn = connection_count.fetch_add(1);
  18149. // Capture the Last-Event-ID header from each connection
  18150. {
  18151. std::lock_guard<std::mutex> lock(id_mutex);
  18152. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  18153. }
  18154. res.set_chunked_content_provider(
  18155. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  18156. if (offset == 0) {
  18157. std::string event =
  18158. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  18159. sink.write(event.data(), event.size());
  18160. }
  18161. return false;
  18162. });
  18163. });
  18164. Client client("localhost", get_port());
  18165. sse::SSEClient sse(client, "/reconnect-with-id");
  18166. sse.set_reconnect_interval(100);
  18167. sse.set_max_reconnect_attempts(3);
  18168. sse.start_async();
  18169. // Wait for at least 2 connections
  18170. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18171. sse.stop();
  18172. // Verify behavior
  18173. std::lock_guard<std::mutex> lock(id_mutex);
  18174. EXPECT_GE(received_last_event_ids.size(), 2u);
  18175. // First connection should have no Last-Event-ID
  18176. if (!received_last_event_ids.empty()) {
  18177. EXPECT_EQ(received_last_event_ids[0], "");
  18178. }
  18179. // Second connection should have Last-Event-ID from first connection
  18180. if (received_last_event_ids.size() >= 2) {
  18181. EXPECT_EQ(received_last_event_ids[1], "event-0");
  18182. }
  18183. }
  18184. // Test: set_headers updates headers used on reconnect
  18185. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  18186. std::vector<std::string> received_tokens;
  18187. std::mutex token_mutex;
  18188. // Endpoint that captures Authorization header
  18189. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  18190. {
  18191. std::lock_guard<std::mutex> lock(token_mutex);
  18192. received_tokens.push_back(req.get_header_value("Authorization"));
  18193. }
  18194. res.set_chunked_content_provider(
  18195. "text/event-stream", [](size_t offset, DataSink &sink) {
  18196. if (offset == 0) {
  18197. std::string event = "data: hello\n\n";
  18198. sink.write(event.data(), event.size());
  18199. }
  18200. return false; // Close connection to trigger reconnect
  18201. });
  18202. });
  18203. Client client("localhost", get_port());
  18204. Headers headers = {{"Authorization", "Bearer old-token"}};
  18205. sse::SSEClient sse(client, "/auth-check", headers);
  18206. // Update headers on each successful connection
  18207. sse.on_open(
  18208. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  18209. sse.set_reconnect_interval(100);
  18210. sse.set_max_reconnect_attempts(3);
  18211. sse.start_async();
  18212. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18213. sse.stop();
  18214. std::lock_guard<std::mutex> lock(token_mutex);
  18215. ASSERT_GE(received_tokens.size(), 2u);
  18216. // First connection uses original header
  18217. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  18218. // Second connection uses updated header from set_headers
  18219. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  18220. }
  18221. // Test: 401 allows reconnection (so on_error can refresh headers)
  18222. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  18223. std::atomic<int> connection_count{0};
  18224. // Endpoint: returns 401 on first attempt, 200 on second
  18225. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  18226. int conn = connection_count.fetch_add(1);
  18227. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  18228. res.status = StatusCode::Unauthorized_401;
  18229. res.set_content("Unauthorized", "text/plain");
  18230. return;
  18231. }
  18232. res.set_chunked_content_provider(
  18233. "text/event-stream", [](size_t offset, DataSink &sink) {
  18234. if (offset == 0) {
  18235. std::string event = "data: authenticated\n\n";
  18236. sink.write(event.data(), event.size());
  18237. }
  18238. return false;
  18239. });
  18240. });
  18241. Client client("localhost", get_port());
  18242. Headers headers = {{"Authorization", "Bearer expired"}};
  18243. sse::SSEClient sse(client, "/auth-retry", headers);
  18244. std::atomic<bool> message_received{false};
  18245. // Refresh token on error
  18246. sse.on_error(
  18247. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  18248. sse.on_message([&](const sse::SSEMessage &msg) {
  18249. if (msg.data == "authenticated") { message_received.store(true); }
  18250. });
  18251. sse.set_reconnect_interval(100);
  18252. sse.set_max_reconnect_attempts(3);
  18253. sse.start_async();
  18254. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18255. sse.stop();
  18256. // Should have reconnected after 401 and succeeded with new token
  18257. EXPECT_GE(connection_count.load(), 2);
  18258. EXPECT_TRUE(message_received.load());
  18259. }
  18260. TEST(Issue2318Test, EmptyHostString) {
  18261. {
  18262. httplib::Client cli_empty("", PORT);
  18263. auto res = cli_empty.Get("/");
  18264. ASSERT_FALSE(res);
  18265. EXPECT_EQ(httplib::Error::Connection, res.error());
  18266. }
  18267. {
  18268. httplib::Client cli(" ", PORT);
  18269. auto res = cli.Get("/");
  18270. ASSERT_FALSE(res);
  18271. EXPECT_EQ(httplib::Error::Connection, res.error());
  18272. }
  18273. }
  18274. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18275. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  18276. Server svr;
  18277. // Set a small payload limit (1KB)
  18278. svr.set_payload_max_length(1024);
  18279. svr.Post("/test", [&](const Request &req, Response &res) {
  18280. res.set_content("Body size: " + std::to_string(req.body.size()),
  18281. "text/plain");
  18282. });
  18283. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18284. auto se = detail::scope_exit([&] {
  18285. svr.stop();
  18286. listen_thread.join();
  18287. });
  18288. svr.wait_until_ready();
  18289. // Create data that compresses well but exceeds limit when decompressed
  18290. // 8KB of repeated null bytes compresses to a very small size
  18291. std::string original_data(8 * 1024, '\0');
  18292. // Compress the data using gzip
  18293. std::string compressed_data;
  18294. detail::gzip_compressor compressor;
  18295. compressor.compress(original_data.data(), original_data.size(), true,
  18296. [&](const char *data, size_t size) {
  18297. compressed_data.append(data, size);
  18298. return true;
  18299. });
  18300. // Verify compression worked (compressed should be much smaller)
  18301. ASSERT_LT(compressed_data.size(), original_data.size());
  18302. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  18303. // Send compressed data with Content-Encoding: gzip
  18304. Client cli(HOST, PORT);
  18305. Headers headers = {{"Content-Encoding", "gzip"}};
  18306. auto res =
  18307. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  18308. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  18309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18310. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  18311. }
  18312. #endif
  18313. // ============================================================================
  18314. // OpenSSL-Specific Tests
  18315. // ============================================================================
  18316. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18317. X509 *readCertificate(const std::string &strFileName) {
  18318. std::ifstream inStream(strFileName);
  18319. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  18320. std::istreambuf_iterator<char>());
  18321. if (strCertPEM.empty()) return (nullptr);
  18322. BIO *pbCert = BIO_new(BIO_s_mem());
  18323. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  18324. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  18325. BIO_free(pbCert);
  18326. return (pCert);
  18327. }
  18328. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  18329. std::ifstream inStream(strFileName);
  18330. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  18331. std::istreambuf_iterator<char>());
  18332. if (strPrivateKeyPEM.empty()) return (nullptr);
  18333. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  18334. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  18335. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  18336. BIO_free(pbPrivKey);
  18337. return (pPrivateKey);
  18338. }
  18339. TEST(BindServerTest, UpdateCerts) {
  18340. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18341. int port = svr.bind_to_any_port("0.0.0.0");
  18342. ASSERT_TRUE(svr.is_valid());
  18343. ASSERT_TRUE(port > 0);
  18344. X509 *cert = readCertificate(SERVER_CERT_FILE);
  18345. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  18346. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  18347. ASSERT_TRUE(cert != nullptr);
  18348. ASSERT_TRUE(ca_cert != nullptr);
  18349. ASSERT_TRUE(key != nullptr);
  18350. X509_STORE *cert_store = X509_STORE_new();
  18351. X509_STORE_add_cert(cert_store, ca_cert);
  18352. // svr.update_certs(cert, key, cert_store); // deprecated
  18353. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  18354. CLIENT_CA_CERT_FILE);
  18355. ASSERT_TRUE(svr.is_valid());
  18356. svr.stop();
  18357. X509_STORE_free(cert_store);
  18358. X509_free(cert);
  18359. X509_free(ca_cert);
  18360. EVP_PKEY_free(key);
  18361. }
  18362. // Test that update_certs() updates client CA list correctly
  18363. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  18364. // Start with file-based constructor
  18365. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18366. ASSERT_TRUE(svr.is_valid());
  18367. // Initially no client CA list should be set
  18368. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  18369. ASSERT_TRUE(ssl_ctx != nullptr);
  18370. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  18371. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  18372. EXPECT_EQ(0, count_before);
  18373. // Now update with client CA (PEM string)
  18374. std::string cert_pem, key_pem, ca_pem;
  18375. read_file(SERVER_CERT_FILE, cert_pem);
  18376. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  18377. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  18378. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  18379. ASSERT_TRUE(svr.is_valid());
  18380. // Now client CA list should be set
  18381. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  18382. ASSERT_TRUE(ca_list_after != nullptr);
  18383. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  18384. }
  18385. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  18386. // Test that the file-path SSLServer constructor properly sets the client CA
  18387. // list that is sent to clients during the TLS handshake (CertificateRequest)
  18388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18389. ASSERT_TRUE(svr.is_valid());
  18390. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  18391. ASSERT_TRUE(ssl_ctx != nullptr);
  18392. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  18393. ASSERT_TRUE(ca_list != nullptr);
  18394. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  18395. }
  18396. #endif
  18397. // ============================================================================
  18398. // MbedTLS-Specific Tests
  18399. // ============================================================================
  18400. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  18401. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  18402. using namespace httplib::tls;
  18403. // Track if callback was invoked
  18404. bool callback_invoked = false;
  18405. // The callback receives void* ctx which is actually MbedTlsContext*
  18406. // We can access the mbedtls_ssl_config via the context
  18407. auto setup_callback = [&callback_invoked](void *ctx) {
  18408. callback_invoked = true;
  18409. // Cast to MbedTlsContext* to access the ssl config
  18410. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  18411. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  18412. // Use static variables to hold certificate data (simplified for test)
  18413. static mbedtls_x509_crt own_cert;
  18414. static mbedtls_pk_context own_key;
  18415. static mbedtls_x509_crt ca_chain;
  18416. static bool initialized = false;
  18417. if (!initialized) {
  18418. mbedtls_x509_crt_init(&own_cert);
  18419. mbedtls_pk_init(&own_key);
  18420. mbedtls_x509_crt_init(&ca_chain);
  18421. // Load server certificate
  18422. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  18423. return false;
  18424. }
  18425. // Load server private key.
  18426. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  18427. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  18428. #if MBEDTLS_VERSION_MAJOR == 3
  18429. ,
  18430. mbedtls_ctr_drbg_random, nullptr
  18431. #endif
  18432. ) != 0) {
  18433. return false;
  18434. }
  18435. // Load CA chain for client verification
  18436. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  18437. return false;
  18438. }
  18439. initialized = true;
  18440. }
  18441. // Configure the SSL config
  18442. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  18443. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  18444. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  18445. // Set minimum TLS version using mbedTLS native API
  18446. #if MBEDTLS_VERSION_MAJOR >= 3
  18447. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  18448. #else
  18449. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  18450. MBEDTLS_SSL_MINOR_VERSION_3);
  18451. #endif
  18452. return true;
  18453. };
  18454. SSLServer svr(setup_callback);
  18455. ASSERT_TRUE(svr.is_valid());
  18456. ASSERT_TRUE(callback_invoked);
  18457. svr.Get("/test", [&](const Request &req, Response &res) {
  18458. res.set_content("test", "text/plain");
  18459. auto cert = req.peer_cert();
  18460. ASSERT_TRUE(static_cast<bool>(cert));
  18461. auto common_name = cert.subject_cn();
  18462. EXPECT_EQ("Common Name", common_name);
  18463. });
  18464. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18465. auto se = detail::scope_exit([&] {
  18466. svr.stop();
  18467. t.join();
  18468. ASSERT_FALSE(svr.is_running());
  18469. });
  18470. svr.wait_until_ready();
  18471. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  18472. cli.enable_server_certificate_verification(false);
  18473. cli.set_connection_timeout(30);
  18474. auto res = cli.Get("/test");
  18475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18476. ASSERT_EQ(StatusCode::OK_200, res->status);
  18477. }
  18478. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  18479. // context (owning mbedtls_ssl_config) before shutting down a still-open
  18480. // keep-alive SSL session, which reads through that config in
  18481. // mbedtls_ssl_close_notify.
  18482. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  18483. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18484. ASSERT_TRUE(svr.is_valid());
  18485. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18486. res.set_content("test", "text/plain");
  18487. });
  18488. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18489. auto se = detail::scope_exit([&] {
  18490. svr.stop();
  18491. t.join();
  18492. ASSERT_FALSE(svr.is_running());
  18493. });
  18494. svr.wait_until_ready();
  18495. {
  18496. SSLClient cli(HOST, PORT);
  18497. cli.enable_server_certificate_verification(false);
  18498. cli.set_keep_alive(true);
  18499. auto res = cli.Get("/test");
  18500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18501. ASSERT_EQ(StatusCode::OK_200, res->status);
  18502. // cli is destructed here with the keep-alive SSL session still open.
  18503. }
  18504. }
  18505. #endif
  18506. // WebSocket Tests
  18507. TEST(WebSocketTest, RSVBitsMustBeZero) {
  18508. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  18509. // defining the meaning of these bits has been negotiated.
  18510. auto make_frame = [](uint8_t first_byte) {
  18511. std::string frame;
  18512. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  18513. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  18514. frame += "Hello";
  18515. return frame;
  18516. };
  18517. // RSV1 set (0x40)
  18518. {
  18519. detail::BufferStream strm;
  18520. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  18521. ws::Opcode opcode;
  18522. std::string payload;
  18523. bool fin;
  18524. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18525. false, 1024));
  18526. }
  18527. // RSV2 set (0x20)
  18528. {
  18529. detail::BufferStream strm;
  18530. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  18531. ws::Opcode opcode;
  18532. std::string payload;
  18533. bool fin;
  18534. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18535. false, 1024));
  18536. }
  18537. // RSV3 set (0x10)
  18538. {
  18539. detail::BufferStream strm;
  18540. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  18541. ws::Opcode opcode;
  18542. std::string payload;
  18543. bool fin;
  18544. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18545. false, 1024));
  18546. }
  18547. // No RSV bits set - should succeed
  18548. {
  18549. detail::BufferStream strm;
  18550. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  18551. ws::Opcode opcode;
  18552. std::string payload;
  18553. bool fin;
  18554. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18555. false, 1024));
  18556. EXPECT_EQ(ws::Opcode::Text, opcode);
  18557. EXPECT_EQ("Hello", payload);
  18558. EXPECT_TRUE(fin);
  18559. }
  18560. }
  18561. TEST(WebSocketTest, ControlFrameValidation) {
  18562. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  18563. // payload length <= 125.
  18564. // Ping with FIN=0 - must be rejected
  18565. {
  18566. detail::BufferStream strm;
  18567. std::string frame;
  18568. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  18569. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18570. strm.write(frame.data(), frame.size());
  18571. ws::Opcode opcode;
  18572. std::string payload;
  18573. bool fin;
  18574. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18575. false, 1024));
  18576. }
  18577. // Close with FIN=0 - must be rejected
  18578. {
  18579. detail::BufferStream strm;
  18580. std::string frame;
  18581. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  18582. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18583. strm.write(frame.data(), frame.size());
  18584. ws::Opcode opcode;
  18585. std::string payload;
  18586. bool fin;
  18587. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18588. false, 1024));
  18589. }
  18590. // Ping with payload_len=126 (extended length) - must be rejected
  18591. {
  18592. detail::BufferStream strm;
  18593. std::string frame;
  18594. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18595. frame += static_cast<char>(126); // payload_len=126 (>125)
  18596. frame += static_cast<char>(0x00); // extended length high byte
  18597. frame += static_cast<char>(126); // extended length low byte
  18598. frame += std::string(126, 'x');
  18599. strm.write(frame.data(), frame.size());
  18600. ws::Opcode opcode;
  18601. std::string payload;
  18602. bool fin;
  18603. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18604. false, 1024));
  18605. }
  18606. // Ping with FIN=1 and payload_len=125 - should succeed
  18607. {
  18608. detail::BufferStream strm;
  18609. std::string frame;
  18610. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18611. frame += static_cast<char>(125); // payload_len=125
  18612. frame += std::string(125, 'x');
  18613. strm.write(frame.data(), frame.size());
  18614. ws::Opcode opcode;
  18615. std::string payload;
  18616. bool fin;
  18617. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18618. false, 1024));
  18619. EXPECT_EQ(ws::Opcode::Ping, opcode);
  18620. EXPECT_EQ(125u, payload.size());
  18621. EXPECT_TRUE(fin);
  18622. }
  18623. }
  18624. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  18625. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  18626. // length MUST be 0.
  18627. // MSB set - must be rejected
  18628. {
  18629. detail::BufferStream strm;
  18630. std::string frame;
  18631. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18632. frame += static_cast<char>(127); // 64-bit extended length
  18633. frame += static_cast<char>(0x80); // MSB set (invalid)
  18634. frame += std::string(7, '\0'); // remaining 7 bytes of length
  18635. strm.write(frame.data(), frame.size());
  18636. ws::Opcode opcode;
  18637. std::string payload;
  18638. bool fin;
  18639. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18640. false, 1024));
  18641. }
  18642. // MSB clear - should pass length parsing (will be rejected by max_len,
  18643. // but that's a different check; use a small length to verify)
  18644. {
  18645. detail::BufferStream strm;
  18646. std::string frame;
  18647. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18648. frame += static_cast<char>(127); // 64-bit extended length
  18649. frame += std::string(7, '\0'); // high bytes = 0
  18650. frame += static_cast<char>(0x03); // length = 3
  18651. frame += "abc";
  18652. strm.write(frame.data(), frame.size());
  18653. ws::Opcode opcode;
  18654. std::string payload;
  18655. bool fin;
  18656. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18657. false, 1024));
  18658. EXPECT_EQ(ws::Opcode::Text, opcode);
  18659. EXPECT_EQ("abc", payload);
  18660. }
  18661. }
  18662. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  18663. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  18664. // Valid UTF-8
  18665. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  18666. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  18667. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  18668. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  18669. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  18670. // Invalid UTF-8
  18671. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  18672. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  18673. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  18674. EXPECT_FALSE(
  18675. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  18676. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  18677. }
  18678. TEST(WebSocketTest, ConnectAndDisconnect) {
  18679. Server svr;
  18680. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18681. std::string msg;
  18682. while (ws.read(msg)) {}
  18683. });
  18684. auto port = svr.bind_to_any_port(HOST);
  18685. std::thread t([&]() { svr.listen_after_bind(); });
  18686. svr.wait_until_ready();
  18687. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18688. auto res = client.connect();
  18689. ASSERT_TRUE(res);
  18690. EXPECT_EQ(Error::Success, res.error());
  18691. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  18692. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  18693. EXPECT_TRUE(client.is_open());
  18694. client.close();
  18695. EXPECT_FALSE(client.is_open());
  18696. svr.stop();
  18697. t.join();
  18698. }
  18699. TEST(WebSocketTest, ValidURL) {
  18700. ws::WebSocketClient ws1("ws://localhost:8080/path");
  18701. EXPECT_TRUE(ws1.is_valid());
  18702. ws::WebSocketClient ws2("ws://example.com/path");
  18703. EXPECT_TRUE(ws2.is_valid());
  18704. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  18705. EXPECT_TRUE(ws3.is_valid());
  18706. #ifdef CPPHTTPLIB_SSL_ENABLED
  18707. ws::WebSocketClient wss1("wss://example.com/path");
  18708. EXPECT_TRUE(wss1.is_valid());
  18709. ws::WebSocketClient wss2("wss://example.com:443/path");
  18710. EXPECT_TRUE(wss2.is_valid());
  18711. #endif
  18712. }
  18713. TEST(WebSocketTest, InvalidURL) {
  18714. // No scheme
  18715. ws::WebSocketClient ws1("localhost:8080/path");
  18716. EXPECT_FALSE(ws1.is_valid());
  18717. // No path
  18718. ws::WebSocketClient ws2("ws://localhost:8080");
  18719. EXPECT_FALSE(ws2.is_valid());
  18720. // Empty string
  18721. ws::WebSocketClient ws3("");
  18722. EXPECT_FALSE(ws3.is_valid());
  18723. // Missing host
  18724. ws::WebSocketClient ws4("ws://:8080/path");
  18725. EXPECT_FALSE(ws4.is_valid());
  18726. // Port number overflow — should not crash
  18727. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  18728. EXPECT_FALSE(ws5.is_valid());
  18729. // Port out of range
  18730. ws::WebSocketClient ws6("ws://localhost:99999/path");
  18731. EXPECT_FALSE(ws6.is_valid());
  18732. }
  18733. TEST(WebSocketTest, UnsupportedScheme) {
  18734. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  18735. ws::WebSocketClient ws1("http://localhost:8080/path");
  18736. EXPECT_FALSE(ws1.is_valid());
  18737. ws::WebSocketClient ws2("https://localhost:8080/path");
  18738. EXPECT_FALSE(ws2.is_valid());
  18739. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  18740. EXPECT_FALSE(ws3.is_valid());
  18741. #else
  18742. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  18743. std::invalid_argument);
  18744. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  18745. std::invalid_argument);
  18746. #endif
  18747. }
  18748. TEST(WebSocketTest, ConnectWhenInvalid) {
  18749. ws::WebSocketClient ws("not a valid url");
  18750. EXPECT_FALSE(ws.is_valid());
  18751. auto res = ws.connect();
  18752. EXPECT_FALSE(res);
  18753. EXPECT_EQ(Error::Connection, res.error());
  18754. EXPECT_EQ(-1, res.status());
  18755. }
  18756. TEST(WebSocketTest, ConnectRefusedReportsError) {
  18757. // Grab a port that is free, then close it again so nothing listens there
  18758. Server svr;
  18759. auto port = svr.bind_to_any_port(HOST);
  18760. svr.stop();
  18761. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18762. auto res = client.connect();
  18763. ASSERT_FALSE(res);
  18764. EXPECT_EQ(Error::Connection, res.error());
  18765. EXPECT_EQ(-1, res.status());
  18766. }
  18767. TEST(WebSocketTest, DefaultPort) {
  18768. ws::WebSocketClient ws1("ws://example.com/path");
  18769. EXPECT_TRUE(ws1.is_valid());
  18770. // ws:// defaults to port 80 (verified by successful parse)
  18771. #ifdef CPPHTTPLIB_SSL_ENABLED
  18772. ws::WebSocketClient ws2("wss://example.com/path");
  18773. EXPECT_TRUE(ws2.is_valid());
  18774. // wss:// defaults to port 443 (verified by successful parse)
  18775. #endif
  18776. }
  18777. TEST(WebSocketTest, IPv6LiteralAddress) {
  18778. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  18779. EXPECT_TRUE(ws1.is_valid());
  18780. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  18781. EXPECT_TRUE(ws2.is_valid());
  18782. }
  18783. TEST(WebSocketTest, ComplexPath) {
  18784. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  18785. EXPECT_TRUE(ws1.is_valid());
  18786. ws::WebSocketClient ws2("ws://localhost:8080/");
  18787. EXPECT_TRUE(ws2.is_valid());
  18788. }
  18789. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  18790. Server svr;
  18791. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18792. std::string msg;
  18793. while (ws.read(msg)) {}
  18794. });
  18795. auto port = svr.bind_to_any_port(HOST);
  18796. std::thread t([&]() { svr.listen_after_bind(); });
  18797. svr.wait_until_ready();
  18798. auto another_host = "example.com";
  18799. auto wrong_ip = "192.0.2.1";
  18800. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18801. client.set_hostname_addr_map({{another_host, wrong_ip}});
  18802. ASSERT_TRUE(client.connect());
  18803. EXPECT_TRUE(client.is_open());
  18804. client.close();
  18805. svr.stop();
  18806. t.join();
  18807. }
  18808. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  18809. Server svr;
  18810. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18811. std::string msg;
  18812. while (ws.read(msg)) {}
  18813. });
  18814. auto port = svr.bind_to_any_port(HOST);
  18815. std::thread t([&]() { svr.listen_after_bind(); });
  18816. svr.wait_until_ready();
  18817. auto wrong_ip = "192.0.2.1";
  18818. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18819. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  18820. client.set_connection_timeout(1);
  18821. client.set_read_timeout(1);
  18822. client.set_write_timeout(1);
  18823. EXPECT_FALSE(client.connect());
  18824. EXPECT_FALSE(client.is_open());
  18825. svr.stop();
  18826. t.join();
  18827. }
  18828. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  18829. // A mapped value that is not an IP literal must be resolved. HOST resolves
  18830. // from the hosts file, so this test needs no external DNS. "target.invalid"
  18831. // (RFC 6761) is only a map key and the Host header value.
  18832. auto host = "target.invalid";
  18833. Server svr;
  18834. std::string received_host;
  18835. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18836. received_host = req.get_header_value("Host");
  18837. std::string msg;
  18838. while (ws.read(msg)) {}
  18839. });
  18840. auto port = svr.bind_to_any_port(HOST);
  18841. std::thread t([&]() { svr.listen_after_bind(); });
  18842. // ASSERT_* below returns from the test body, which would leave t joinable
  18843. // and make ~thread call std::terminate.
  18844. auto se = detail::scope_exit([&] {
  18845. svr.stop();
  18846. if (t.joinable()) { t.join(); }
  18847. });
  18848. svr.wait_until_ready();
  18849. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  18850. std::to_string(port) + "/ws");
  18851. client.set_hostname_addr_map({{host, HOST}});
  18852. ASSERT_TRUE(client.connect());
  18853. EXPECT_TRUE(client.is_open());
  18854. client.close();
  18855. svr.stop();
  18856. t.join();
  18857. // The mapping only redirects the connection; the identity stays host_.
  18858. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  18859. }
  18860. class WebSocketIntegrationTest : public ::testing::Test {
  18861. protected:
  18862. void SetUp() override {
  18863. server_ = httplib::detail::make_unique<Server>();
  18864. setup_server();
  18865. start_server();
  18866. }
  18867. void TearDown() override {
  18868. server_->stop();
  18869. if (server_thread_.joinable()) { server_thread_.join(); }
  18870. }
  18871. void setup_server() {
  18872. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18873. std::string msg;
  18874. ws::ReadResult ret;
  18875. while ((ret = ws.read(msg))) {
  18876. if (ret == ws::Binary) {
  18877. ws.send(msg.data(), msg.size());
  18878. } else {
  18879. ws.send(msg);
  18880. }
  18881. }
  18882. });
  18883. server_->WebSocket("/ws-echo-string",
  18884. [](const Request &, ws::WebSocket &ws) {
  18885. std::string msg;
  18886. while (ws.read(msg)) {
  18887. ws.send("echo: " + msg);
  18888. }
  18889. });
  18890. server_->WebSocket(
  18891. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  18892. // Echo back request metadata
  18893. ws.send("path:" + req.path);
  18894. ws.send("header:" + req.get_header_value("X-Test-Header"));
  18895. std::string msg;
  18896. while (ws.read(msg)) {}
  18897. });
  18898. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  18899. std::string msg;
  18900. ws.read(msg); // wait for a message
  18901. ws.close();
  18902. });
  18903. server_->WebSocket("/ws-close-status",
  18904. [](const Request &, ws::WebSocket &ws) {
  18905. std::string msg;
  18906. ws.read(msg); // wait for a message
  18907. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  18908. });
  18909. server_->WebSocket(
  18910. "/ws-subprotocol",
  18911. [](const Request &, ws::WebSocket &ws) {
  18912. std::string msg;
  18913. while (ws.read(msg)) {
  18914. ws.send(msg);
  18915. }
  18916. },
  18917. [](const std::vector<std::string> &protocols) -> std::string {
  18918. for (const auto &p : protocols) {
  18919. if (p == "graphql-ws") { return p; }
  18920. }
  18921. return "";
  18922. });
  18923. }
  18924. void start_server() {
  18925. port_ = server_->bind_to_any_port(HOST);
  18926. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18927. server_->wait_until_ready();
  18928. }
  18929. std::unique_ptr<Server> server_;
  18930. std::thread server_thread_;
  18931. int port_ = 0;
  18932. };
  18933. TEST_F(WebSocketIntegrationTest, TextEcho) {
  18934. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18935. "/ws-echo");
  18936. ASSERT_TRUE(client.connect());
  18937. ASSERT_TRUE(client.is_open());
  18938. ASSERT_TRUE(client.send("Hello WebSocket"));
  18939. std::string msg;
  18940. EXPECT_EQ(ws::Text, client.read(msg));
  18941. EXPECT_EQ("Hello WebSocket", msg);
  18942. client.close();
  18943. }
  18944. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  18945. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18946. "/ws-echo");
  18947. ASSERT_TRUE(client.connect());
  18948. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  18949. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  18950. std::string msg;
  18951. EXPECT_EQ(ws::Binary, client.read(msg));
  18952. EXPECT_EQ(binary_data, msg);
  18953. client.close();
  18954. }
  18955. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  18956. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18957. "/ws-echo");
  18958. ASSERT_TRUE(client.connect());
  18959. for (int i = 0; i < 10; i++) {
  18960. auto text = "message " + std::to_string(i);
  18961. ASSERT_TRUE(client.send(text));
  18962. std::string msg;
  18963. ASSERT_TRUE(client.read(msg));
  18964. EXPECT_EQ(text, msg);
  18965. }
  18966. client.close();
  18967. }
  18968. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  18969. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18970. "/ws-close");
  18971. ASSERT_TRUE(client.connect());
  18972. // Send a message to trigger the server to close
  18973. ASSERT_TRUE(client.send("trigger close"));
  18974. // The server will close, so read should return false
  18975. std::string msg;
  18976. EXPECT_FALSE(client.read(msg));
  18977. EXPECT_FALSE(client.is_open());
  18978. }
  18979. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  18980. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18981. "/ws-echo");
  18982. ASSERT_TRUE(client.connect());
  18983. // 128KB message
  18984. std::string large_data(128 * 1024, 'X');
  18985. ASSERT_TRUE(client.send(large_data));
  18986. std::string msg;
  18987. ASSERT_TRUE(client.read(msg));
  18988. EXPECT_EQ(large_data, msg);
  18989. client.close();
  18990. }
  18991. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  18992. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18993. "/ws-echo");
  18994. ASSERT_TRUE(client.connect());
  18995. const int num_threads = 4;
  18996. std::vector<std::thread> threads;
  18997. std::atomic<int> send_count{0};
  18998. for (int t = 0; t < num_threads; t++) {
  18999. threads.emplace_back([&client, &send_count, t]() {
  19000. for (int i = 0; i < 5; i++) {
  19001. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19002. if (client.send(text)) { send_count++; }
  19003. }
  19004. });
  19005. }
  19006. for (auto &th : threads) {
  19007. th.join();
  19008. }
  19009. int received = 0;
  19010. std::string msg;
  19011. while (received < send_count.load()) {
  19012. if (!client.read(msg)) { break; }
  19013. received++;
  19014. }
  19015. EXPECT_EQ(send_count.load(), received);
  19016. client.close();
  19017. }
  19018. TEST_F(WebSocketIntegrationTest, ReadString) {
  19019. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19020. "/ws-echo-string");
  19021. ASSERT_TRUE(client.connect());
  19022. ASSERT_TRUE(client.send("hello"));
  19023. std::string msg;
  19024. ASSERT_TRUE(client.read(msg));
  19025. EXPECT_EQ("echo: hello", msg);
  19026. ASSERT_TRUE(client.send("world"));
  19027. ASSERT_TRUE(client.read(msg));
  19028. EXPECT_EQ("echo: world", msg);
  19029. client.close();
  19030. }
  19031. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19032. Headers headers = {{"X-Test-Header", "test-value"}};
  19033. ws::WebSocketClient client(
  19034. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19035. ASSERT_TRUE(client.connect());
  19036. std::string msg;
  19037. ASSERT_TRUE(client.read(msg));
  19038. EXPECT_EQ("path:/ws-request-info", msg);
  19039. ASSERT_TRUE(client.read(msg));
  19040. EXPECT_EQ("header:test-value", msg);
  19041. client.close();
  19042. }
  19043. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19044. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19045. "/ws-echo");
  19046. client.set_read_timeout(1, 0); // 1 second
  19047. ASSERT_TRUE(client.connect());
  19048. // Don't send anything — server echo handler waits for a message,
  19049. // so read() should time out and return false.
  19050. std::string msg;
  19051. EXPECT_FALSE(client.read(msg));
  19052. }
  19053. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  19054. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19055. "/ws-echo");
  19056. client.set_read_timeout(5, 0);
  19057. ASSERT_TRUE(client.connect());
  19058. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19059. // The server should reject it and close the connection.
  19060. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  19061. client.send(oversized);
  19062. // The server's read() should have failed due to payload limit,
  19063. // so our read() should return false (connection closed).
  19064. std::string msg;
  19065. EXPECT_FALSE(client.read(msg));
  19066. }
  19067. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  19068. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19069. "/ws-echo");
  19070. client.set_read_timeout(10, 0);
  19071. ASSERT_TRUE(client.connect());
  19072. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19073. // This should succeed.
  19074. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  19075. ASSERT_TRUE(client.send(at_limit));
  19076. std::string msg;
  19077. ASSERT_TRUE(client.read(msg));
  19078. EXPECT_EQ(at_limit.size(), msg.size());
  19079. client.close();
  19080. }
  19081. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  19082. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19083. "/nonexistent");
  19084. auto res = client.connect();
  19085. EXPECT_FALSE(res);
  19086. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19087. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  19088. EXPECT_FALSE(client.is_open());
  19089. }
  19090. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  19091. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19092. "/ws-echo");
  19093. ASSERT_TRUE(client.connect());
  19094. ASSERT_TRUE(client.send(""));
  19095. std::string msg;
  19096. EXPECT_EQ(ws::Text, client.read(msg));
  19097. EXPECT_EQ("", msg);
  19098. client.close();
  19099. }
  19100. TEST_F(WebSocketIntegrationTest, Reconnect) {
  19101. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19102. "/ws-echo");
  19103. // First connection
  19104. ASSERT_TRUE(client.connect());
  19105. ASSERT_TRUE(client.send("first"));
  19106. std::string msg;
  19107. ASSERT_TRUE(client.read(msg));
  19108. EXPECT_EQ("first", msg);
  19109. client.close();
  19110. EXPECT_FALSE(client.is_open());
  19111. // Reconnect using the same client object
  19112. ASSERT_TRUE(client.connect());
  19113. ASSERT_TRUE(client.is_open());
  19114. ASSERT_TRUE(client.send("second"));
  19115. ASSERT_TRUE(client.read(msg));
  19116. EXPECT_EQ("second", msg);
  19117. client.close();
  19118. }
  19119. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  19120. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19121. "/ws-close-status");
  19122. ASSERT_TRUE(client.connect());
  19123. // Trigger the server to close with GoingAway status
  19124. ASSERT_TRUE(client.send("trigger"));
  19125. // read() should return false after receiving the close frame
  19126. std::string msg;
  19127. EXPECT_FALSE(client.read(msg));
  19128. EXPECT_FALSE(client.is_open());
  19129. }
  19130. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  19131. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19132. "/ws-echo");
  19133. ASSERT_TRUE(client.connect());
  19134. client.close(ws::CloseStatus::GoingAway, "client leaving");
  19135. EXPECT_FALSE(client.is_open());
  19136. }
  19137. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  19138. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  19139. ws::WebSocketClient client(
  19140. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19141. ASSERT_TRUE(client.connect());
  19142. // Server should have selected graphql-ws
  19143. EXPECT_EQ("graphql-ws", client.subprotocol());
  19144. client.close();
  19145. }
  19146. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  19147. Headers headers;
  19148. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  19149. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  19150. ws::WebSocketClient client(
  19151. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19152. ASSERT_TRUE(client.connect());
  19153. // The offer on the second field line counts too, so graphql-ws is selected
  19154. EXPECT_EQ("graphql-ws", client.subprotocol());
  19155. client.close();
  19156. }
  19157. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  19158. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  19159. ws::WebSocketClient client(
  19160. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19161. ASSERT_TRUE(client.connect());
  19162. // Server should not have selected any subprotocol
  19163. EXPECT_TRUE(client.subprotocol().empty());
  19164. client.close();
  19165. }
  19166. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  19167. // Connect without requesting any subprotocol
  19168. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19169. "/ws-subprotocol");
  19170. ASSERT_TRUE(client.connect());
  19171. EXPECT_TRUE(client.subprotocol().empty());
  19172. client.close();
  19173. }
  19174. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  19175. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19176. "/ws-echo");
  19177. client.set_tcp_nodelay(true);
  19178. client.set_connection_timeout(3, 0);
  19179. bool socket_options_called = false;
  19180. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  19181. ASSERT_TRUE(client.connect());
  19182. ASSERT_TRUE(client.is_open());
  19183. EXPECT_TRUE(socket_options_called);
  19184. ASSERT_TRUE(client.send("hello"));
  19185. std::string msg;
  19186. auto result = client.read(msg);
  19187. EXPECT_EQ(result, ws::ReadResult::Text);
  19188. EXPECT_EQ(msg, "hello");
  19189. client.close();
  19190. }
  19191. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  19192. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19193. "/ws-echo");
  19194. client.set_connection_timeout(std::chrono::seconds(3));
  19195. client.set_write_timeout(std::chrono::seconds(3));
  19196. // A sub-second remainder exercises the seconds/microseconds split.
  19197. client.set_read_timeout(std::chrono::milliseconds(1500));
  19198. ASSERT_TRUE(client.connect());
  19199. auto start = std::chrono::steady_clock::now();
  19200. std::string msg;
  19201. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  19202. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19203. std::chrono::steady_clock::now() - start)
  19204. .count();
  19205. // Above 1s so that dropping the microseconds half of the split fails here,
  19206. // and well under the 300s default so that ignoring the setter fails too.
  19207. EXPECT_GE(elapsed, 1400);
  19208. EXPECT_LT(elapsed, 30000);
  19209. }
  19210. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  19211. Server svr;
  19212. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  19213. if (!req.has_header("Authorization")) {
  19214. res.status = StatusCode::Unauthorized_401;
  19215. res.set_content("Unauthorized", "text/plain");
  19216. return Server::HandlerResponse::Handled;
  19217. }
  19218. return Server::HandlerResponse::Unhandled;
  19219. });
  19220. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19221. std::string msg;
  19222. while (ws.read(msg)) {
  19223. ws.send(msg);
  19224. }
  19225. });
  19226. auto port = svr.bind_to_any_port("localhost");
  19227. std::thread t([&]() { svr.listen_after_bind(); });
  19228. svr.wait_until_ready();
  19229. // Without Authorization header - should be rejected before upgrade
  19230. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  19231. EXPECT_FALSE(client1.connect());
  19232. // With Authorization header - should succeed
  19233. Headers headers = {{"Authorization", "Bearer token123"}};
  19234. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  19235. headers);
  19236. ASSERT_TRUE(client2.connect());
  19237. ASSERT_TRUE(client2.send("hello"));
  19238. std::string msg;
  19239. ASSERT_TRUE(client2.read(msg));
  19240. EXPECT_EQ("hello", msg);
  19241. client2.close();
  19242. svr.stop();
  19243. t.join();
  19244. }
  19245. TEST(WebSocketTest, QueryStringInHandshake) {
  19246. Server svr;
  19247. std::mutex mtx;
  19248. std::string received_target;
  19249. std::string received_token;
  19250. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19251. {
  19252. std::lock_guard<std::mutex> lock(mtx);
  19253. received_target = req.target;
  19254. if (req.has_param("token")) {
  19255. received_token = req.get_param_value("token");
  19256. }
  19257. }
  19258. std::string msg;
  19259. while (ws.read(msg)) {
  19260. ws.send(msg);
  19261. }
  19262. });
  19263. auto port = svr.bind_to_any_port("localhost");
  19264. std::thread t([&]() { svr.listen_after_bind(); });
  19265. svr.wait_until_ready();
  19266. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  19267. "/ws?token=ABC&session=123");
  19268. ASSERT_TRUE(client.connect());
  19269. // Round-trip ensures the handler has run and captured the request.
  19270. ASSERT_TRUE(client.send("hello"));
  19271. std::string msg;
  19272. ASSERT_TRUE(client.read(msg));
  19273. EXPECT_EQ("hello", msg);
  19274. client.close();
  19275. {
  19276. std::lock_guard<std::mutex> lock(mtx);
  19277. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  19278. EXPECT_EQ("ABC", received_token);
  19279. }
  19280. svr.stop();
  19281. t.join();
  19282. }
  19283. // Run a handshake against a throwaway server and hand the request the server
  19284. // received back to the caller, so tests can assert on the headers the client
  19285. // actually put on the wire.
  19286. static void capture_websocket_handshake_request(
  19287. const Headers &client_headers,
  19288. std::function<void(const Request &, int port)> verify) {
  19289. Server svr;
  19290. std::mutex mtx;
  19291. Request received;
  19292. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19293. {
  19294. std::lock_guard<std::mutex> lock(mtx);
  19295. received = req;
  19296. }
  19297. std::string msg;
  19298. while (ws.read(msg)) {
  19299. ws.send(msg);
  19300. }
  19301. });
  19302. auto port = svr.bind_to_any_port("localhost");
  19303. std::thread t([&]() { svr.listen_after_bind(); });
  19304. auto se = detail::scope_exit([&] {
  19305. svr.stop();
  19306. t.join();
  19307. });
  19308. svr.wait_until_ready();
  19309. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  19310. client_headers);
  19311. ASSERT_TRUE(client.connect());
  19312. ASSERT_TRUE(client.send("hello"));
  19313. std::string msg;
  19314. ASSERT_TRUE(client.read(msg));
  19315. client.close();
  19316. {
  19317. std::lock_guard<std::mutex> lock(mtx);
  19318. verify(received, port);
  19319. }
  19320. }
  19321. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  19322. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  19323. // Non-default port must be present in the Host header. Default ports
  19324. // (80/443) are omitted; that logic is covered by
  19325. // MakeHostAndPortStringTest.
  19326. EXPECT_EQ("localhost:" + std::to_string(port),
  19327. req.get_header_value("Host"));
  19328. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  19329. req.get_header_value("User-Agent"));
  19330. EXPECT_FALSE(req.has_header("Accept"));
  19331. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  19332. EXPECT_FALSE(req.has_header("Content-Length"));
  19333. });
  19334. }
  19335. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  19336. capture_websocket_handshake_request(
  19337. {{"Host", "example.com"},
  19338. {"User-Agent", "custom-agent"},
  19339. {"X-Custom", "value"}},
  19340. [](const Request &req, int) {
  19341. EXPECT_EQ("example.com", req.get_header_value("Host"));
  19342. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  19343. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  19344. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  19345. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  19346. });
  19347. }
  19348. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  19349. capture_websocket_handshake_request(
  19350. {{"Upgrade", "bogus"},
  19351. {"Connection", "close"},
  19352. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  19353. {"Sec-WebSocket-Version", "8"}},
  19354. [](const Request &req, int) {
  19355. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  19356. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  19357. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  19358. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  19359. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  19360. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  19361. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  19362. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  19363. req.get_header_value("Sec-WebSocket-Key"));
  19364. });
  19365. }
  19366. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  19367. // A header the client refuses to send must abort the handshake before any
  19368. // part of it reaches the wire; a lone request line would otherwise sit in
  19369. // the peer's buffer as a truncated request.
  19370. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19371. ASSERT_NE(INVALID_SOCKET, srv);
  19372. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  19373. sockaddr_in addr{};
  19374. addr.sin_family = AF_INET;
  19375. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  19376. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19377. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19378. ASSERT_EQ(0, ::listen(srv, 1));
  19379. sockaddr_in bound{};
  19380. socklen_t bound_len = sizeof(bound);
  19381. ASSERT_EQ(
  19382. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  19383. auto port = ntohs(bound.sin_port);
  19384. ssize_t received = -1;
  19385. std::thread t([&] {
  19386. // Bound every blocking call so a regression fails the test with a bad
  19387. // value instead of hanging the suite.
  19388. fd_set rfds;
  19389. FD_ZERO(&rfds);
  19390. FD_SET(srv, &rfds);
  19391. timeval tv{5, 0};
  19392. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  19393. 0) {
  19394. return;
  19395. }
  19396. sockaddr_in cli_addr{};
  19397. socklen_t cli_len = sizeof(cli_addr);
  19398. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19399. if (cli == INVALID_SOCKET) { return; }
  19400. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  19401. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19402. char buf[4096];
  19403. received = ::recv(cli, buf, sizeof(buf), 0);
  19404. });
  19405. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  19406. // connect() has already shut the socket down by the time it returns false,
  19407. // so the peer sees EOF without waiting for the client to be destroyed.
  19408. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  19409. {{"X-Bad", "a\r\nInjected: 1"}});
  19410. EXPECT_FALSE(client.connect());
  19411. t.join();
  19412. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  19413. EXPECT_EQ(0, received);
  19414. }
  19415. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  19416. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  19417. // contains "upgrade" as a substring is a different token and must not
  19418. // start a WebSocket handshake.
  19419. auto make_request = [](const std::vector<std::string> &connection_values) {
  19420. Request req;
  19421. req.method = "GET";
  19422. req.headers.emplace("Upgrade", "websocket");
  19423. for (const auto &value : connection_values) {
  19424. req.headers.emplace("Connection", value);
  19425. }
  19426. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  19427. req.headers.emplace("Sec-WebSocket-Version", "13");
  19428. return req;
  19429. };
  19430. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  19431. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  19432. EXPECT_TRUE(
  19433. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  19434. EXPECT_TRUE(
  19435. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  19436. EXPECT_TRUE(
  19437. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  19438. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  19439. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  19440. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  19441. EXPECT_FALSE(
  19442. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  19443. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  19444. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  19445. }
  19446. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  19447. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  19448. // asks recipients to match each protocol-name case-insensitively, and RFC
  19449. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  19450. // client naming websocket alongside another protocol, or on a second field
  19451. // line, is offering websocket; a value that merely contains "websocket" as a
  19452. // substring is a different protocol name and is not.
  19453. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  19454. Request req;
  19455. req.method = "GET";
  19456. for (const auto &value : upgrade_values) {
  19457. req.headers.emplace("Upgrade", value);
  19458. }
  19459. req.headers.emplace("Connection", "Upgrade");
  19460. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  19461. req.headers.emplace("Sec-WebSocket-Version", "13");
  19462. return req;
  19463. };
  19464. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  19465. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  19466. EXPECT_TRUE(
  19467. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  19468. EXPECT_TRUE(
  19469. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  19470. EXPECT_TRUE(
  19471. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  19472. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  19473. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  19474. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  19475. EXPECT_FALSE(
  19476. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  19477. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  19478. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  19479. }
  19480. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  19481. Server svr;
  19482. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  19483. auto port = svr.bind_to_any_port("localhost");
  19484. std::thread t([&]() { svr.listen_after_bind(); });
  19485. auto se = detail::scope_exit([&] {
  19486. svr.stop();
  19487. t.join();
  19488. });
  19489. svr.wait_until_ready();
  19490. Headers headers = {{"Upgrade", "websocket"},
  19491. {"Connection", "notupgrade"},
  19492. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  19493. {"Sec-WebSocket-Version", "13"}};
  19494. Client cli("localhost", port);
  19495. auto res = cli.Get("/ws", headers);
  19496. // The route exists only as a WebSocket route, so a request that fails the
  19497. // handshake check falls through to ordinary routing.
  19498. ASSERT_TRUE(res);
  19499. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  19500. }
  19501. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  19502. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  19503. // Connection value is the only thing left for the client to reject.
  19504. Server svr;
  19505. svr.Get("/ws", [](const Request &req, Response &res) {
  19506. res.status = StatusCode::SwitchingProtocol_101;
  19507. res.set_header("Upgrade", "websocket");
  19508. res.set_header("Connection", "notupgrade");
  19509. res.set_header("Sec-WebSocket-Accept",
  19510. detail::websocket_accept_key(
  19511. req.get_header_value("Sec-WebSocket-Key")));
  19512. });
  19513. auto port = svr.bind_to_any_port("localhost");
  19514. std::thread t([&]() { svr.listen_after_bind(); });
  19515. auto se = detail::scope_exit([&] {
  19516. svr.stop();
  19517. t.join();
  19518. });
  19519. svr.wait_until_ready();
  19520. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19521. auto res = client.connect();
  19522. EXPECT_FALSE(res);
  19523. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19524. EXPECT_FALSE(client.is_open());
  19525. }
  19526. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  19527. // The socket path doubles as the URL host, so it must not contain '/'.
  19528. const char *shard = getenv("GTEST_SHARD_INDEX");
  19529. const std::string sock_path =
  19530. shard ? std::string("httplib-ws-") + shard + ".sock"
  19531. : std::string("httplib-ws.sock");
  19532. std::remove(sock_path.c_str());
  19533. Server svr;
  19534. std::mutex mtx;
  19535. std::string received_host;
  19536. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19537. {
  19538. std::lock_guard<std::mutex> lock(mtx);
  19539. received_host = req.get_header_value("Host");
  19540. }
  19541. std::string msg;
  19542. while (ws.read(msg)) {
  19543. ws.send(msg);
  19544. }
  19545. });
  19546. svr.set_address_family(AF_UNIX);
  19547. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  19548. auto se = detail::scope_exit([&] {
  19549. svr.stop();
  19550. t.join();
  19551. std::remove(sock_path.c_str());
  19552. });
  19553. svr.wait_until_ready();
  19554. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  19555. client.set_address_family(AF_UNIX);
  19556. ASSERT_TRUE(client.connect());
  19557. ASSERT_TRUE(client.send("hello"));
  19558. std::string msg;
  19559. ASSERT_TRUE(client.read(msg));
  19560. client.close();
  19561. {
  19562. std::lock_guard<std::mutex> lock(mtx);
  19563. // There is no host:port for a Unix socket, so the same "localhost"
  19564. // placeholder the HTTP client uses is expected.
  19565. EXPECT_EQ("localhost", received_host);
  19566. }
  19567. }
  19568. // Two threads must never parse WebSocket frames from the same stream.
  19569. // close() used to read the peer's Close reply with its own frame read, so it
  19570. // raced a reader thread that was in the middle of a payload: the payload loop
  19571. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  19572. // so bytes taken by close() were replaced with bytes from further along the
  19573. // stream. The message kept its length and silently changed content.
  19574. //
  19575. // The raw peer below sends a frame header plus part of the payload, waits for
  19576. // the handler to call close(), and only then sends the rest. Whichever thread
  19577. // would win the race for those bytes, the message must arrive intact, because
  19578. // close() must not touch the stream while read() owns it.
  19579. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  19580. #ifndef _WIN32
  19581. signal(SIGPIPE, SIG_IGN);
  19582. #endif
  19583. const size_t payload_len = 120; // fits the 7-bit length field
  19584. const size_t prefix_len = 8;
  19585. const int attempts = 8;
  19586. std::string expected(payload_len, '\0');
  19587. for (size_t i = 0; i < payload_len; i++) {
  19588. expected[i] = static_cast<char>('a' + i % 26);
  19589. }
  19590. std::atomic<bool> peer_stalled{false};
  19591. std::atomic<bool> handler_done{false};
  19592. std::mutex received_mutex;
  19593. std::vector<std::string> received;
  19594. // Bound every wait, so a regression fails the test instead of hanging the
  19595. // suite.
  19596. auto wait_for = [](const std::atomic<bool> &flag) {
  19597. for (int i = 0; i < 500 && !flag; i++) {
  19598. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19599. }
  19600. };
  19601. Server svr;
  19602. svr.set_websocket_ping_interval(0);
  19603. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  19604. std::thread reader([&]() {
  19605. std::string msg;
  19606. while (ws.read(msg)) {
  19607. std::lock_guard<std::mutex> guard(received_mutex);
  19608. received.push_back(msg);
  19609. }
  19610. });
  19611. // Wait until the peer stalls mid-payload, so the reader thread is parked
  19612. // inside read_websocket_frame() when close() runs.
  19613. wait_for(peer_stalled);
  19614. ws.close();
  19615. reader.join();
  19616. handler_done = true;
  19617. });
  19618. auto port = svr.bind_to_any_port("127.0.0.1");
  19619. std::thread t([&]() { svr.listen_after_bind(); });
  19620. auto se = detail::scope_exit([&] {
  19621. svr.stop();
  19622. t.join();
  19623. });
  19624. svr.wait_until_ready();
  19625. auto send_bytes = [](socket_t s, const std::string &data) {
  19626. #ifdef _WIN32
  19627. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  19628. #else
  19629. auto n = ::send(s, data.data(), data.size(), 0);
  19630. #endif
  19631. return n == static_cast<decltype(n)>(data.size());
  19632. };
  19633. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  19634. // Every length used here fits the 7-bit length field.
  19635. auto masked_header = [](uint8_t first_byte, size_t len) {
  19636. std::string h;
  19637. h += static_cast<char>(first_byte);
  19638. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  19639. h.append(4, '\0'); // mask key
  19640. return h;
  19641. };
  19642. for (int attempt = 0; attempt < attempts; attempt++) {
  19643. peer_stalled = false;
  19644. handler_done = false;
  19645. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  19646. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  19647. auto se_sock = detail::scope_exit([&] {
  19648. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  19649. });
  19650. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19651. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19652. sockaddr_in addr{};
  19653. addr.sin_family = AF_INET;
  19654. addr.sin_port = htons(static_cast<uint16_t>(port));
  19655. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19656. ASSERT_EQ(
  19657. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  19658. << "attempt " << attempt;
  19659. ASSERT_TRUE(send_bytes(sock,
  19660. "GET /ws HTTP/1.1\r\n"
  19661. "Host: 127.0.0.1\r\n"
  19662. "Upgrade: websocket\r\n"
  19663. "Connection: Upgrade\r\n"
  19664. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  19665. "Sec-WebSocket-Version: 13\r\n"
  19666. "\r\n"))
  19667. << "attempt " << attempt;
  19668. std::string response;
  19669. while (response.find("\r\n\r\n") == std::string::npos) {
  19670. char buf[512];
  19671. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  19672. if (n <= 0) { break; }
  19673. response.append(buf, static_cast<size_t>(n));
  19674. }
  19675. ASSERT_NE(std::string::npos, response.find(" 101 "))
  19676. << "attempt " << attempt;
  19677. // Send the header of a Binary message but only the first prefix_len bytes
  19678. // of its payload, leaving the reader thread stalled inside the payload.
  19679. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  19680. expected.substr(0, prefix_len)))
  19681. << "attempt " << attempt;
  19682. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19683. peer_stalled = true;
  19684. // Let close() send its Close frame and park in its own read before the
  19685. // rest of the payload arrives, so both threads are waiting for it.
  19686. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19687. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  19688. close_frame += static_cast<char>(0x03); // status 1000
  19689. close_frame += static_cast<char>(0xE8);
  19690. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  19691. << "attempt " << attempt;
  19692. // Closing the peer releases the reader thread even on the buggy path,
  19693. // where it waits for bytes another thread already consumed.
  19694. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19695. detail::close_socket(sock);
  19696. sock = INVALID_SOCKET;
  19697. wait_for(handler_done);
  19698. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  19699. }
  19700. std::lock_guard<std::mutex> guard(received_mutex);
  19701. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  19702. << "a message in flight when close() ran was dropped";
  19703. for (size_t i = 0; i < received.size(); i++) {
  19704. EXPECT_EQ(expected, received[i]) << "message " << i;
  19705. }
  19706. }
  19707. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19708. class WebSocketSSLIntegrationTest : public ::testing::Test {
  19709. protected:
  19710. void SetUp() override {
  19711. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  19712. SERVER_PRIVATE_KEY_FILE);
  19713. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19714. std::string msg;
  19715. ws::ReadResult ret;
  19716. while ((ret = ws.read(msg))) {
  19717. if (ret == ws::Binary) {
  19718. ws.send(msg.data(), msg.size());
  19719. } else {
  19720. ws.send(msg);
  19721. }
  19722. }
  19723. });
  19724. port_ = server_->bind_to_any_port(HOST);
  19725. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19726. server_->wait_until_ready();
  19727. }
  19728. void TearDown() override {
  19729. server_->stop();
  19730. if (server_thread_.joinable()) { server_thread_.join(); }
  19731. }
  19732. std::unique_ptr<SSLServer> server_;
  19733. std::thread server_thread_;
  19734. int port_ = 0;
  19735. };
  19736. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  19737. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19738. "/ws-echo");
  19739. client.enable_server_certificate_verification(false);
  19740. ASSERT_TRUE(client.connect());
  19741. ASSERT_TRUE(client.is_open());
  19742. ASSERT_TRUE(client.send("Hello WSS"));
  19743. std::string msg;
  19744. EXPECT_EQ(ws::Text, client.read(msg));
  19745. EXPECT_EQ("Hello WSS", msg);
  19746. client.close();
  19747. }
  19748. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  19749. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  19750. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  19751. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  19752. // client (without calling close() first) is the only path that runs
  19753. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  19754. // bug exactly.
  19755. //
  19756. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  19757. // when linked against an instrumented libssl; run under Valgrind to catch it
  19758. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  19759. // suite (the freed session otherwise stalls on the close handshake) — this test
  19760. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  19761. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  19762. {
  19763. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19764. "/ws-echo");
  19765. client.enable_server_certificate_verification(false);
  19766. client.set_read_timeout(2, 0);
  19767. client.set_write_timeout(2, 0);
  19768. ASSERT_TRUE(client.connect());
  19769. ASSERT_TRUE(client.is_open());
  19770. ASSERT_TRUE(client.send("still open"));
  19771. // Intentionally do NOT call client.close(): leaving scope runs
  19772. // shutdown_and_close() with the WebSocket still open, which must send the
  19773. // close frame while the TLS session is still alive.
  19774. }
  19775. }
  19776. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  19777. // shutdown_and_close() at the start of connect(), reproducing the same
  19778. // use-after-free within the test body rather than at scope exit. The second
  19779. // connect must succeed and echo, proving the close handshake ran over a live
  19780. // session. See the note above about memory-tool requirements.
  19781. TEST_F(WebSocketSSLIntegrationTest,
  19782. ReconnectWhileOpenSendsCloseOverLiveSession) {
  19783. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19784. "/ws-echo");
  19785. client.enable_server_certificate_verification(false);
  19786. client.set_read_timeout(2, 0);
  19787. client.set_write_timeout(2, 0);
  19788. ASSERT_TRUE(client.connect());
  19789. ASSERT_TRUE(client.is_open());
  19790. ASSERT_TRUE(client.send("still open"));
  19791. // Reconnect without closing first: connect() calls shutdown_and_close() on
  19792. // the still-open connection, which must not touch a freed TLS session.
  19793. ASSERT_TRUE(client.connect());
  19794. ASSERT_TRUE(client.is_open());
  19795. ASSERT_TRUE(client.send("after reconnect"));
  19796. std::string msg;
  19797. EXPECT_EQ(ws::Text, client.read(msg));
  19798. EXPECT_EQ("after reconnect", msg);
  19799. client.close();
  19800. }
  19801. #endif
  19802. #ifdef CPPHTTPLIB_SSL_ENABLED
  19803. class WebSocketSSLCATest : public ::testing::Test {
  19804. protected:
  19805. void SetUp() override {
  19806. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  19807. SERVER_PRIVATE_KEY_FILE);
  19808. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19809. std::string msg;
  19810. while (ws.read(msg)) {
  19811. ws.send(msg);
  19812. }
  19813. });
  19814. port_ = server_->bind_to_any_port("127.0.0.1");
  19815. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19816. server_->wait_until_ready();
  19817. }
  19818. void TearDown() override {
  19819. server_->stop();
  19820. if (server_thread_.joinable()) { server_thread_.join(); }
  19821. }
  19822. std::string url() const {
  19823. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  19824. }
  19825. std::unique_ptr<SSLServer> server_;
  19826. std::thread server_thread_;
  19827. int port_ = 0;
  19828. };
  19829. // A custom CA loaded as PEM verifies the server with full certificate
  19830. // verification enabled
  19831. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  19832. ws::WebSocketClient client(url());
  19833. std::string cert;
  19834. read_file(SERVER_CERT2_FILE, cert);
  19835. client.load_ca_cert_store(cert.c_str(), cert.size());
  19836. ASSERT_TRUE(client.connect());
  19837. ASSERT_TRUE(client.send("hello"));
  19838. std::string msg;
  19839. EXPECT_EQ(ws::Text, client.read(msg));
  19840. EXPECT_EQ("hello", msg);
  19841. client.close();
  19842. }
  19843. // A custom CA that does not cover the server must fail verification (the
  19844. // custom CA is exclusive; system certs are not loaded alongside it)
  19845. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  19846. ws::WebSocketClient client(url());
  19847. std::string cert;
  19848. read_file(CLIENT_CA_CERT_FILE, cert);
  19849. client.load_ca_cert_store(cert.c_str(), cert.size());
  19850. auto res = client.connect();
  19851. ASSERT_FALSE(res);
  19852. EXPECT_EQ(Error::SSLServerVerification, res.error());
  19853. EXPECT_EQ(-1, res.status());
  19854. EXPECT_NE(0u, res.ssl_backend_error());
  19855. }
  19856. // The same CA as a file path rather than PEM in memory
  19857. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  19858. ws::WebSocketClient client(url());
  19859. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19860. ASSERT_TRUE(client.connect());
  19861. ASSERT_TRUE(client.send("hello"));
  19862. std::string msg;
  19863. EXPECT_EQ(ws::Text, client.read(msg));
  19864. EXPECT_EQ("hello", msg);
  19865. client.close();
  19866. }
  19867. // ...and a CA file that does not cover the server still fails, so it is the
  19868. // path above that decides the outcome
  19869. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  19870. ws::WebSocketClient client(url());
  19871. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19872. ASSERT_FALSE(client.connect());
  19873. }
  19874. // Regression test: reconnecting with a native custom CA store used to reuse
  19875. // a store handle the previous TLS context had already freed (use-after-free
  19876. // under the OpenSSL backend). The context now lives as long as the client.
  19877. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  19878. ws::WebSocketClient client(url());
  19879. std::string cert;
  19880. read_file(SERVER_CERT2_FILE, cert);
  19881. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  19882. ASSERT_TRUE(client.connect());
  19883. client.close();
  19884. ASSERT_TRUE(client.connect());
  19885. ASSERT_TRUE(client.send("again"));
  19886. std::string msg;
  19887. EXPECT_EQ(ws::Text, client.read(msg));
  19888. EXPECT_EQ("again", msg);
  19889. client.close();
  19890. }
  19891. // Regression test: a certificate with a trusted chain but no identity match
  19892. // for the server IP must be rejected. The Mbed TLS backend used to skip
  19893. // verification entirely for IP hosts, so this connection succeeded there.
  19894. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  19895. // chain verification while the identity check must still fail.
  19896. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  19897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19898. ASSERT_TRUE(svr.is_valid());
  19899. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19900. std::string msg;
  19901. while (ws.read(msg)) {
  19902. ws.send(msg);
  19903. }
  19904. });
  19905. auto port = svr.bind_to_any_port("127.0.0.1");
  19906. auto t = std::thread([&]() { svr.listen_after_bind(); });
  19907. auto se = detail::scope_exit([&] {
  19908. svr.stop();
  19909. t.join();
  19910. });
  19911. svr.wait_until_ready();
  19912. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  19913. "/echo");
  19914. std::string cert;
  19915. read_file(SERVER_CERT_FILE, cert);
  19916. client.load_ca_cert_store(cert.c_str(), cert.size());
  19917. ASSERT_FALSE(client.connect());
  19918. }
  19919. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  19920. // SNI, so nothing binds the host name to the TLS session. These bind the
  19921. // server to "localhost" instead, the only shape that exercises the SNI and
  19922. // hostname-verification path with certificate verification left enabled.
  19923. class WebSocketSSLDnsHostTest : public ::testing::Test {
  19924. protected:
  19925. void Start(const char *cert_file) {
  19926. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  19927. SERVER_PRIVATE_KEY_FILE);
  19928. ASSERT_TRUE(server_->is_valid());
  19929. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19930. std::string msg;
  19931. while (ws.read(msg)) {
  19932. ws.send(msg);
  19933. }
  19934. });
  19935. port_ = server_->bind_to_any_port("localhost");
  19936. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19937. server_->wait_until_ready();
  19938. }
  19939. void TearDown() override {
  19940. if (server_) { server_->stop(); }
  19941. if (server_thread_.joinable()) { server_thread_.join(); }
  19942. }
  19943. std::string url() const {
  19944. return "wss://localhost:" + std::to_string(port_) + "/echo";
  19945. }
  19946. std::unique_ptr<SSLServer> server_;
  19947. std::thread server_thread_;
  19948. int port_ = 0;
  19949. };
  19950. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  19951. // out and the connection is usable
  19952. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  19953. Start(SERVER_CERT2_FILE);
  19954. ws::WebSocketClient client(url());
  19955. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19956. ASSERT_TRUE(client.connect());
  19957. ASSERT_TRUE(client.send("hello"));
  19958. std::string msg;
  19959. EXPECT_EQ(ws::Text, client.read(msg));
  19960. EXPECT_EQ("hello", msg);
  19961. client.close();
  19962. }
  19963. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  19964. // while the identity check must still reject "localhost"
  19965. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  19966. Start(SERVER_CERT_FILE);
  19967. ws::WebSocketClient client(url());
  19968. client.set_ca_cert_path(SERVER_CERT_FILE);
  19969. auto res = client.connect();
  19970. ASSERT_FALSE(res);
  19971. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  19972. EXPECT_EQ(-1, res.status());
  19973. }
  19974. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  19975. // disabled: the chain is still checked, only the identity check is skipped
  19976. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  19977. Start(SERVER_CERT_FILE);
  19978. ws::WebSocketClient client(url());
  19979. client.set_ca_cert_path(SERVER_CERT_FILE);
  19980. client.enable_server_hostname_verification(false);
  19981. ASSERT_TRUE(client.connect());
  19982. ASSERT_TRUE(client.send("hello"));
  19983. std::string msg;
  19984. EXPECT_EQ(ws::Text, client.read(msg));
  19985. EXPECT_EQ("hello", msg);
  19986. client.close();
  19987. }
  19988. // A CA that did not sign the server certificate fails the chain, even though
  19989. // the name would match
  19990. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  19991. Start(SERVER_CERT2_FILE);
  19992. ws::WebSocketClient client(url());
  19993. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19994. ASSERT_FALSE(client.connect());
  19995. }
  19996. // With verification disabled, neither the chain nor the name is checked
  19997. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  19998. Start(SERVER_CERT_FILE);
  19999. ws::WebSocketClient client(url());
  20000. client.enable_server_certificate_verification(false);
  20001. ASSERT_TRUE(client.connect());
  20002. ASSERT_TRUE(client.send("hello"));
  20003. std::string msg;
  20004. EXPECT_EQ(ws::Text, client.read(msg));
  20005. EXPECT_EQ("hello", msg);
  20006. client.close();
  20007. }
  20008. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  20009. protected:
  20010. void SetUp() override {
  20011. server_ = httplib::detail::make_unique<SSLServer>(
  20012. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20013. ASSERT_TRUE(server_->is_valid());
  20014. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20015. std::string msg;
  20016. while (ws.read(msg)) {
  20017. ws.send(msg);
  20018. }
  20019. });
  20020. port_ = server_->bind_to_any_port("localhost");
  20021. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20022. server_->wait_until_ready();
  20023. }
  20024. void TearDown() override {
  20025. server_->stop();
  20026. if (server_thread_.joinable()) { server_thread_.join(); }
  20027. }
  20028. std::string url() const {
  20029. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  20030. }
  20031. void ConnectWithClientCert(const std::string &client_cert_file,
  20032. const std::string &client_private_key_file,
  20033. const char *private_key_password) {
  20034. std::string cert_pem, key_pem;
  20035. read_file(client_cert_file, cert_pem);
  20036. read_file(client_private_key_file, key_pem);
  20037. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  20038. key_pem.c_str(), key_pem.size(),
  20039. private_key_password};
  20040. ws::WebSocketClient client(url(), pem);
  20041. ASSERT_TRUE(client.is_valid());
  20042. client.enable_server_certificate_verification(false);
  20043. ASSERT_TRUE(client.connect());
  20044. ASSERT_TRUE(client.send("hello"));
  20045. std::string msg;
  20046. EXPECT_EQ(ws::Text, client.read(msg));
  20047. EXPECT_EQ("hello", msg);
  20048. client.close();
  20049. }
  20050. std::unique_ptr<SSLServer> server_;
  20051. std::thread server_thread_;
  20052. int port_ = 0;
  20053. };
  20054. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  20055. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  20056. }
  20057. // Control for the tests above: the fixture's server really does require a
  20058. // client certificate, so it is the PEM the constructor installed that decides
  20059. // the outcome.
  20060. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  20061. ws::WebSocketClient client(url());
  20062. ASSERT_TRUE(client.is_valid());
  20063. client.enable_server_certificate_verification(false);
  20064. EXPECT_FALSE(client.connect());
  20065. }
  20066. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  20067. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  20068. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  20069. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  20070. }
  20071. #endif
  20072. #if !defined(_WIN32)
  20073. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  20074. auto secret_dir = std::string("./symlink_test_secret");
  20075. auto served_dir = std::string("./symlink_test_served");
  20076. auto secret_file = secret_dir + "/secret.txt";
  20077. auto symlink_path = served_dir + "/escape";
  20078. // Setup: create directories and files
  20079. mkdir(secret_dir.c_str(), 0755);
  20080. mkdir(served_dir.c_str(), 0755);
  20081. {
  20082. std::ofstream ofs(secret_file);
  20083. ofs << "SECRET_DATA";
  20084. }
  20085. // Create symlink using absolute path so it resolves correctly
  20086. #ifdef PATH_MAX
  20087. char abs_secret[PATH_MAX];
  20088. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  20089. #else
  20090. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  20091. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  20092. ASSERT_NE(nullptr, abs_secret);
  20093. #endif
  20094. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  20095. auto se = detail::scope_exit([&] {
  20096. unlink(symlink_path.c_str());
  20097. unlink(secret_file.c_str());
  20098. rmdir(served_dir.c_str());
  20099. rmdir(secret_dir.c_str());
  20100. });
  20101. Server svr;
  20102. svr.set_mount_point("/", served_dir);
  20103. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  20104. auto se2 = detail::scope_exit([&] {
  20105. svr.stop();
  20106. listen_thread.join();
  20107. });
  20108. svr.wait_until_ready();
  20109. Client cli("localhost", PORT);
  20110. // Symlink pointing outside base dir should be blocked
  20111. auto res = cli.Get("/escape/secret.txt");
  20112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20113. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  20114. }
  20115. #endif
  20116. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  20117. // A GET request with Content-Length to a static file handler must have its
  20118. // body drained before the keep-alive connection is reused. Otherwise the
  20119. // unread body bytes are interpreted as the next HTTP request.
  20120. //
  20121. // The body is sent AFTER receiving the first response (as in the original
  20122. // PoC) so that the stream_line_reader cannot buffer it together with the
  20123. // headers of the first request.
  20124. Server svr;
  20125. svr.set_mount_point("/", "./www");
  20126. std::atomic<int> smuggled_count(0);
  20127. svr.Get("/smuggled", [&](const Request &, Response &res) {
  20128. smuggled_count++;
  20129. res.set_content("oops", "text/plain");
  20130. });
  20131. auto port = svr.bind_to_any_port("localhost");
  20132. thread t = thread([&] { svr.listen_after_bind(); });
  20133. auto se = detail::scope_exit([&] {
  20134. svr.stop();
  20135. t.join();
  20136. });
  20137. svr.wait_until_ready();
  20138. auto error = Error::Success;
  20139. auto sock = detail::create_client_socket(
  20140. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  20141. /*connection_timeout_sec=*/2, 0,
  20142. /*read_timeout_sec=*/2, 0,
  20143. /*write_timeout_sec=*/2, 0, std::string(), error);
  20144. ASSERT_NE(INVALID_SOCKET, sock);
  20145. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20146. // The "smuggled" request will be sent as the body of the outer GET
  20147. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  20148. "Host: localhost\r\n"
  20149. "Connection: close\r\n"
  20150. "\r\n";
  20151. // Step 1: Send only the outer request headers (no body yet)
  20152. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  20153. "Host: localhost\r\n"
  20154. "Content-Length: " +
  20155. std::to_string(smuggled.size()) +
  20156. "\r\n"
  20157. "\r\n";
  20158. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  20159. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  20160. // Step 2: Read the first response (server serves file without reading body)
  20161. std::string first_response;
  20162. char buf[4096];
  20163. for (;;) {
  20164. auto n = recv(sock, buf, sizeof(buf), 0);
  20165. if (n <= 0) break;
  20166. first_response.append(buf, static_cast<size_t>(n));
  20167. // Stop once we have a complete response (headers + body)
  20168. auto hdr_end = first_response.find("\r\n\r\n");
  20169. if (hdr_end != std::string::npos) {
  20170. // Check for Content-Length to know when the body is complete
  20171. auto cl_pos = first_response.find("Content-Length:");
  20172. if (cl_pos != std::string::npos) {
  20173. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  20174. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  20175. auto cl = std::stoul(
  20176. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  20177. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  20178. } else {
  20179. break; // No Content-Length, assume headers-only response
  20180. }
  20181. }
  20182. }
  20183. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  20184. // Step 3: Now send the body, which looks like a new HTTP request.
  20185. // On a vulnerable server the keep-alive loop reads this as a second request.
  20186. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  20187. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  20188. // Step 4: Try to read a second response (should NOT exist after fix)
  20189. std::string second_response;
  20190. for (;;) {
  20191. auto n = recv(sock, buf, sizeof(buf), 0);
  20192. if (n <= 0) break;
  20193. second_response.append(buf, static_cast<size_t>(n));
  20194. }
  20195. // The smuggled request must NOT have been processed
  20196. EXPECT_EQ(0, smuggled_count.load());
  20197. }
  20198. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20199. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  20200. // must be rejected with 400 Bad Request.
  20201. Server svr;
  20202. svr.Post("/test", [&](const Request &, Response &res) {
  20203. res.set_content("ok", "text/plain");
  20204. });
  20205. thread t = thread([&] { svr.listen(HOST, PORT); });
  20206. auto se = detail::scope_exit([&] {
  20207. svr.stop();
  20208. t.join();
  20209. ASSERT_FALSE(svr.is_running());
  20210. });
  20211. svr.wait_until_ready();
  20212. // Exact "chunked"
  20213. {
  20214. auto req = "POST /test HTTP/1.1\r\n"
  20215. "Host: localhost\r\n"
  20216. "Content-Length: 5\r\n"
  20217. "Transfer-Encoding: chunked\r\n"
  20218. "Connection: close\r\n"
  20219. "\r\n"
  20220. "hello";
  20221. std::string response;
  20222. ASSERT_TRUE(send_request(1, req, &response));
  20223. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20224. response.substr(0, response.find("\r\n")));
  20225. }
  20226. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  20227. {
  20228. auto req = "POST /test HTTP/1.1\r\n"
  20229. "Host: localhost\r\n"
  20230. "Content-Length: 5\r\n"
  20231. "Transfer-Encoding: gzip, chunked\r\n"
  20232. "Connection: close\r\n"
  20233. "\r\n"
  20234. "hello";
  20235. std::string response;
  20236. ASSERT_TRUE(send_request(1, req, &response));
  20237. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20238. response.substr(0, response.find("\r\n")));
  20239. }
  20240. }
  20241. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  20242. Server svr;
  20243. svr.Post("/test", [&](const Request &, Response &res) {
  20244. res.set_content("ok", "text/plain");
  20245. });
  20246. thread t = thread([&] { svr.listen(HOST, PORT); });
  20247. auto se = detail::scope_exit([&] {
  20248. svr.stop();
  20249. t.join();
  20250. ASSERT_FALSE(svr.is_running());
  20251. });
  20252. svr.wait_until_ready();
  20253. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  20254. // length cannot be determined, so the server must answer 400 and close
  20255. // rather than treat the request as bodyless and leave the body in the
  20256. // socket for the next request to pick up.
  20257. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  20258. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  20259. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  20260. std::string response;
  20261. ASSERT_TRUE(send_request(1, req, &response));
  20262. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20263. response.substr(0, response.find("\r\n")))
  20264. << transfer_encoding;
  20265. }
  20266. // RFC 9110 5.3: the codings may also be split across several
  20267. // Transfer-Encoding lines, which combine in the order they were received.
  20268. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  20269. // just like the single-line "chunked, gzip" above.
  20270. {
  20271. auto req = "POST /test HTTP/1.1\r\n"
  20272. "Host: localhost\r\n"
  20273. "Transfer-Encoding: chunked\r\n"
  20274. "Transfer-Encoding: gzip\r\n"
  20275. "\r\n"
  20276. "0\r\n\r\n";
  20277. std::string response;
  20278. ASSERT_TRUE(send_request(1, req, &response));
  20279. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20280. response.substr(0, response.find("\r\n")));
  20281. }
  20282. // A sequence ending in chunked stays valid.
  20283. auto req = "POST /test HTTP/1.1\r\n"
  20284. "Host: localhost\r\n"
  20285. "Transfer-Encoding: gzip, chunked\r\n"
  20286. "Connection: close\r\n"
  20287. "\r\n"
  20288. "0\r\n\r\n";
  20289. std::string response;
  20290. ASSERT_TRUE(send_request(1, req, &response));
  20291. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  20292. // ...including when it is spread over several lines.
  20293. auto split_req = "POST /test HTTP/1.1\r\n"
  20294. "Host: localhost\r\n"
  20295. "Transfer-Encoding: gzip\r\n"
  20296. "Transfer-Encoding: chunked\r\n"
  20297. "Connection: close\r\n"
  20298. "\r\n"
  20299. "0\r\n\r\n";
  20300. std::string split_response;
  20301. ASSERT_TRUE(send_request(1, split_req, &split_response));
  20302. EXPECT_EQ("HTTP/1.1 200 OK",
  20303. split_response.substr(0, split_response.find("\r\n")));
  20304. }
  20305. // Regression for issue #2450: a DELETE without Content-Length on a
  20306. // keep-alive connection must not let the post-response drain consume the
  20307. // next request's bytes.
  20308. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  20309. Server svr;
  20310. std::atomic<int> delete_count(0);
  20311. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  20312. delete_count++;
  20313. res.status = StatusCode::NoContent_204;
  20314. });
  20315. auto port = svr.bind_to_any_port(HOST);
  20316. thread t = thread([&] { svr.listen_after_bind(); });
  20317. auto se = detail::scope_exit([&] {
  20318. svr.stop();
  20319. t.join();
  20320. });
  20321. svr.wait_until_ready();
  20322. auto error = Error::Success;
  20323. auto sock = detail::create_client_socket(
  20324. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20325. /*connection_timeout_sec=*/2, 0,
  20326. /*read_timeout_sec=*/2, 0,
  20327. /*write_timeout_sec=*/2, 0, std::string(), error);
  20328. ASSERT_NE(INVALID_SOCKET, sock);
  20329. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20330. auto send_request_and_read_response = [&](const std::string &req,
  20331. std::string &out) -> bool {
  20332. auto sent = send(sock, req.data(), req.size(), 0);
  20333. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  20334. char buf[4096];
  20335. for (;;) {
  20336. auto n = recv(sock, buf, sizeof(buf), 0);
  20337. if (n <= 0) { return !out.empty(); }
  20338. out.append(buf, static_cast<size_t>(n));
  20339. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  20340. }
  20341. };
  20342. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  20343. "Host: localhost\r\n"
  20344. "\r\n";
  20345. std::string resp1;
  20346. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  20347. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  20348. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  20349. "Host: localhost\r\n"
  20350. "Connection: close\r\n"
  20351. "\r\n";
  20352. std::string resp2;
  20353. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  20354. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  20355. EXPECT_EQ(2, delete_count.load());
  20356. }
  20357. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  20358. Server svr;
  20359. svr.Post("/ingest", [&](const Request &, Response &res,
  20360. const ContentReader &content_reader) {
  20361. auto consumed = content_reader([](const char *, size_t) { return false; });
  20362. EXPECT_FALSE(consumed);
  20363. res.status = StatusCode::Conflict_409;
  20364. res.set_header("Connection", "close");
  20365. });
  20366. auto port = svr.bind_to_any_port(HOST);
  20367. thread t = thread([&] { svr.listen_after_bind(); });
  20368. auto se = detail::scope_exit([&] {
  20369. svr.stop();
  20370. t.join();
  20371. });
  20372. svr.wait_until_ready();
  20373. auto error = Error::Success;
  20374. auto sock = detail::create_client_socket(
  20375. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20376. /*connection_timeout_sec=*/2, 0,
  20377. /*read_timeout_sec=*/1, 0,
  20378. /*write_timeout_sec=*/2, 0, std::string(), error);
  20379. ASSERT_NE(INVALID_SOCKET, sock);
  20380. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20381. std::string request = "POST /ingest HTTP/1.1\r\n"
  20382. "Host: localhost\r\n"
  20383. "Transfer-Encoding: chunked\r\n"
  20384. "\r\n"
  20385. "4\r\n"
  20386. "data\r\n";
  20387. auto sent = send(sock, request.data(), request.size(), 0);
  20388. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  20389. std::string response;
  20390. ssize_t received = 0;
  20391. do {
  20392. char buf[4096];
  20393. received = recv(sock, buf, sizeof(buf), 0);
  20394. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  20395. } while (received > 0);
  20396. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  20397. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  20398. EXPECT_EQ(0, received);
  20399. }
  20400. namespace no_proxy_test {
  20401. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  20402. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  20403. // calling listen().
  20404. class ScopedServer {
  20405. public:
  20406. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  20407. ~ScopedServer() {
  20408. svr_.stop();
  20409. if (th_.joinable()) { th_.join(); }
  20410. }
  20411. Server &svr() { return svr_; }
  20412. int port() const { return port_; }
  20413. void listen() {
  20414. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20415. svr_.wait_until_ready();
  20416. }
  20417. private:
  20418. Server svr_;
  20419. std::thread th_;
  20420. int port_ = 0;
  20421. };
  20422. class ProxyAndTargetServers {
  20423. public:
  20424. ProxyAndTargetServers() {
  20425. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  20426. proxy_hits_++;
  20427. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  20428. res.set_content("via-proxy", "text/plain");
  20429. });
  20430. target_.Get(".*", [this](const Request &req, Response &res) {
  20431. target_hits_++;
  20432. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  20433. res.set_content("direct", "text/plain");
  20434. });
  20435. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  20436. target_port_ = target_.bind_to_any_port("127.0.0.1");
  20437. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  20438. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  20439. proxy_mock_.wait_until_ready();
  20440. target_.wait_until_ready();
  20441. }
  20442. ~ProxyAndTargetServers() {
  20443. proxy_mock_.stop();
  20444. target_.stop();
  20445. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  20446. if (target_thread_.joinable()) { target_thread_.join(); }
  20447. }
  20448. Server &proxy_mock() { return proxy_mock_; }
  20449. Server &target() { return target_; }
  20450. int proxy_port() const { return proxy_port_; }
  20451. int target_port() const { return target_port_; }
  20452. int proxy_hits() const { return proxy_hits_.load(); }
  20453. int target_hits() const { return target_hits_.load(); }
  20454. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  20455. void reset_counters() {
  20456. proxy_hits_ = 0;
  20457. target_hits_ = 0;
  20458. last_had_proxy_authz_ = false;
  20459. }
  20460. private:
  20461. Server proxy_mock_;
  20462. Server target_;
  20463. std::thread proxy_thread_;
  20464. std::thread target_thread_;
  20465. int proxy_port_ = 0;
  20466. int target_port_ = 0;
  20467. std::atomic<int> proxy_hits_{0};
  20468. std::atomic<int> target_hits_{0};
  20469. std::atomic<bool> last_had_proxy_authz_{false};
  20470. };
  20471. inline std::unique_ptr<Client> make_client(const std::string &host,
  20472. ProxyAndTargetServers &s) {
  20473. auto cli = detail::make_unique<Client>(host, s.target_port());
  20474. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  20475. cli->set_proxy("127.0.0.1", s.proxy_port());
  20476. return cli;
  20477. }
  20478. } // namespace no_proxy_test
  20479. using no_proxy_test::make_client;
  20480. using no_proxy_test::ProxyAndTargetServers;
  20481. TEST(NoProxyTest, ExactHostnameBypasses) {
  20482. ProxyAndTargetServers s;
  20483. auto cli = make_client("example.com", s);
  20484. cli->set_no_proxy({"example.com"});
  20485. auto res = cli->Get("/");
  20486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20487. EXPECT_EQ(0, s.proxy_hits());
  20488. EXPECT_EQ(1, s.target_hits());
  20489. }
  20490. TEST(NoProxyTest, SubdomainBypasses) {
  20491. ProxyAndTargetServers s;
  20492. auto cli = make_client("foo.example.com", s);
  20493. cli->set_no_proxy({"example.com"});
  20494. auto res = cli->Get("/");
  20495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20496. EXPECT_EQ(0, s.proxy_hits());
  20497. EXPECT_EQ(1, s.target_hits());
  20498. }
  20499. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  20500. // Regression guard: "evilexample.com" must not be considered a subdomain
  20501. // of "example.com". Without the dot-boundary rule, a naive endsWith
  20502. // check would let traffic bypass the proxy and leak credentials direct
  20503. // to the attacker host.
  20504. ProxyAndTargetServers s;
  20505. auto cli = make_client("evilexample.com", s);
  20506. cli->set_no_proxy({"example.com"});
  20507. auto res = cli->Get("/");
  20508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20509. EXPECT_GE(s.proxy_hits(), 1);
  20510. EXPECT_EQ(0, s.target_hits());
  20511. }
  20512. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  20513. ProxyAndTargetServers s;
  20514. auto cli = make_client("example.com.evil.com", s);
  20515. cli->set_no_proxy({"example.com"});
  20516. auto res = cli->Get("/");
  20517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20518. EXPECT_GE(s.proxy_hits(), 1);
  20519. EXPECT_EQ(0, s.target_hits());
  20520. }
  20521. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  20522. ProxyAndTargetServers s;
  20523. auto cli = make_client("example.com", s);
  20524. cli->set_no_proxy({".example.com"});
  20525. auto res = cli->Get("/");
  20526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20527. EXPECT_EQ(0, s.proxy_hits());
  20528. EXPECT_EQ(1, s.target_hits());
  20529. }
  20530. TEST(NoProxyTest, CaseInsensitiveHostname) {
  20531. ProxyAndTargetServers s;
  20532. auto cli = make_client("Example.COM", s);
  20533. cli->set_no_proxy({"EXAMPLE.com"});
  20534. auto res = cli->Get("/");
  20535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20536. EXPECT_EQ(0, s.proxy_hits());
  20537. EXPECT_EQ(1, s.target_hits());
  20538. }
  20539. TEST(NoProxyTest, TrailingDotIsNormalized) {
  20540. ProxyAndTargetServers s;
  20541. auto cli = make_client("example.com.", s);
  20542. cli->set_no_proxy({"example.com"});
  20543. auto res = cli->Get("/");
  20544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20545. EXPECT_EQ(0, s.proxy_hits());
  20546. EXPECT_EQ(1, s.target_hits());
  20547. }
  20548. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  20549. // Trailing dots must be normalized on BOTH sides — host and entry.
  20550. // An implementation that only strips the host-side trailing dot would
  20551. // fail to match host "example.com" against entry "example.com." because
  20552. // a literal substring search would compare 11 chars against 12.
  20553. ProxyAndTargetServers s;
  20554. auto cli = make_client("example.com", s);
  20555. cli->set_no_proxy({"example.com."});
  20556. auto res = cli->Get("/");
  20557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20558. EXPECT_EQ(0, s.proxy_hits());
  20559. EXPECT_EQ(1, s.target_hits());
  20560. }
  20561. TEST(NoProxyTest, WildcardBypassesEverything) {
  20562. ProxyAndTargetServers s;
  20563. auto cli = make_client("anything.invalid.test", s);
  20564. cli->set_no_proxy({"*"});
  20565. auto res = cli->Get("/");
  20566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20567. EXPECT_EQ(0, s.proxy_hits());
  20568. EXPECT_EQ(1, s.target_hits());
  20569. }
  20570. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  20571. ProxyAndTargetServers s;
  20572. Client cli("127.0.0.1", s.target_port());
  20573. cli.set_proxy("127.0.0.1", s.proxy_port());
  20574. cli.set_no_proxy({"127.0.0.1"});
  20575. auto res = cli.Get("/");
  20576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20577. EXPECT_EQ(0, s.proxy_hits());
  20578. EXPECT_EQ(1, s.target_hits());
  20579. }
  20580. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  20581. ProxyAndTargetServers s;
  20582. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  20583. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  20584. cli.set_proxy("127.0.0.1", s.proxy_port());
  20585. cli.set_no_proxy({"::1"});
  20586. auto res = cli.Get("/");
  20587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20588. EXPECT_EQ(0, s.proxy_hits());
  20589. EXPECT_EQ(1, s.target_hits());
  20590. }
  20591. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  20592. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  20593. // must still be recognized as IPv6 for CIDR matching. Implementations
  20594. // that detect IPv6 only when the host begins with '[' would parse the
  20595. // host as a hostname and miss the match.
  20596. ProxyAndTargetServers s;
  20597. Client cli("fe80::1", s.target_port());
  20598. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20599. cli.set_proxy("127.0.0.1", s.proxy_port());
  20600. cli.set_no_proxy({"fe80::/10"});
  20601. auto res = cli.Get("/");
  20602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20603. EXPECT_EQ(0, s.proxy_hits());
  20604. EXPECT_EQ(1, s.target_hits());
  20605. }
  20606. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  20607. ProxyAndTargetServers s;
  20608. Client cli("::1", s.target_port());
  20609. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  20610. cli.set_proxy("127.0.0.1", s.proxy_port());
  20611. cli.set_no_proxy({"[::1]"});
  20612. auto res = cli.Get("/");
  20613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20614. EXPECT_EQ(0, s.proxy_hits());
  20615. EXPECT_EQ(1, s.target_hits());
  20616. }
  20617. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  20618. ProxyAndTargetServers s;
  20619. Client cli("fe80::1", s.target_port());
  20620. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20621. cli.set_proxy("127.0.0.1", s.proxy_port());
  20622. cli.set_no_proxy({"[fe80::]/10"});
  20623. auto res = cli.Get("/");
  20624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20625. EXPECT_EQ(0, s.proxy_hits());
  20626. EXPECT_EQ(1, s.target_hits());
  20627. }
  20628. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  20629. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  20630. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  20631. // tricks via address-family conversion.
  20632. ProxyAndTargetServers s;
  20633. Client cli("::ffff:127.0.0.1", s.target_port());
  20634. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  20635. cli.set_proxy("127.0.0.1", s.proxy_port());
  20636. cli.set_no_proxy({"127.0.0.1"});
  20637. auto res = cli.Get("/");
  20638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20639. EXPECT_GE(s.proxy_hits(), 1);
  20640. EXPECT_EQ(0, s.target_hits());
  20641. }
  20642. TEST(NoProxyTest, IPv4CidrMatch) {
  20643. ProxyAndTargetServers s;
  20644. Client cli("127.0.0.1", s.target_port());
  20645. cli.set_proxy("127.0.0.1", s.proxy_port());
  20646. cli.set_no_proxy({"127.0.0.0/8"});
  20647. auto res = cli.Get("/");
  20648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20649. EXPECT_EQ(0, s.proxy_hits());
  20650. EXPECT_EQ(1, s.target_hits());
  20651. }
  20652. TEST(NoProxyTest, IPv4CidrNonMatch) {
  20653. ProxyAndTargetServers s;
  20654. Client cli("127.0.0.1", s.target_port());
  20655. cli.set_proxy("127.0.0.1", s.proxy_port());
  20656. cli.set_no_proxy({"10.0.0.0/8"});
  20657. auto res = cli.Get("/");
  20658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20659. EXPECT_GE(s.proxy_hits(), 1);
  20660. EXPECT_EQ(0, s.target_hits());
  20661. }
  20662. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  20663. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  20664. // IPv4 target matches.
  20665. ProxyAndTargetServers s;
  20666. Client cli("127.0.0.1", s.target_port());
  20667. cli.set_proxy("127.0.0.1", s.proxy_port());
  20668. cli.set_no_proxy({"0.0.0.0/0"});
  20669. auto res = cli.Get("/");
  20670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20671. EXPECT_EQ(0, s.proxy_hits());
  20672. EXPECT_EQ(1, s.target_hits());
  20673. }
  20674. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  20675. ProxyAndTargetServers s;
  20676. Client cli("127.0.0.1", s.target_port());
  20677. cli.set_proxy("127.0.0.1", s.proxy_port());
  20678. cli.set_no_proxy({"127.0.0.1"});
  20679. auto res = cli.Get("/");
  20680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20681. EXPECT_EQ(0, s.proxy_hits());
  20682. EXPECT_EQ(1, s.target_hits());
  20683. }
  20684. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  20685. ProxyAndTargetServers s;
  20686. Client cli("127.0.0.1", s.target_port());
  20687. cli.set_proxy("127.0.0.1", s.proxy_port());
  20688. cli.set_no_proxy({"127.0.0.0/33"});
  20689. auto res = cli.Get("/");
  20690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20691. EXPECT_GE(s.proxy_hits(), 1);
  20692. EXPECT_EQ(0, s.target_hits());
  20693. }
  20694. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  20695. // Empty prefix after the slash must be rejected, not silently treated as /32.
  20696. ProxyAndTargetServers s;
  20697. Client cli("127.0.0.1", s.target_port());
  20698. cli.set_proxy("127.0.0.1", s.proxy_port());
  20699. cli.set_no_proxy({"127.0.0.1/"});
  20700. auto res = cli.Get("/");
  20701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20702. EXPECT_GE(s.proxy_hits(), 1);
  20703. EXPECT_EQ(0, s.target_hits());
  20704. }
  20705. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  20706. ProxyAndTargetServers s;
  20707. auto cli = make_client("internal.corp", s);
  20708. cli->set_proxy_basic_auth("u", "p");
  20709. cli->set_no_proxy({"internal.corp"});
  20710. auto res = cli->Get("/");
  20711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20712. EXPECT_EQ(1, s.target_hits());
  20713. EXPECT_EQ(0, s.proxy_hits());
  20714. EXPECT_FALSE(s.last_had_proxy_authz())
  20715. << "Proxy-Authorization must not be sent direct to the target";
  20716. }
  20717. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  20718. ProxyAndTargetServers s;
  20719. auto cli = make_client("public.example", s);
  20720. cli->set_proxy_basic_auth("u", "p");
  20721. cli->set_no_proxy({"internal.corp"}); // does not match
  20722. auto res = cli->Get("/");
  20723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20724. EXPECT_GE(s.proxy_hits(), 1);
  20725. EXPECT_TRUE(s.last_had_proxy_authz());
  20726. }
  20727. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  20728. ProxyAndTargetServers s;
  20729. auto cli = make_client("anything.test", s);
  20730. auto res = cli->Get("/");
  20731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20732. EXPECT_GE(s.proxy_hits(), 1);
  20733. EXPECT_EQ(0, s.target_hits());
  20734. }
  20735. TEST(NoProxyTest, PortSpecificEntryRejected) {
  20736. ProxyAndTargetServers s;
  20737. auto cli = make_client("example.com", s);
  20738. cli->set_no_proxy({"example.com:8080"});
  20739. auto res = cli->Get("/");
  20740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20741. EXPECT_GE(s.proxy_hits(), 1);
  20742. EXPECT_EQ(0, s.target_hits());
  20743. }
  20744. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  20745. ProxyAndTargetServers s;
  20746. auto cli = make_client("anything.test", s);
  20747. cli->set_no_proxy({"", " ", "\t"});
  20748. auto res = cli->Get("/");
  20749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20750. EXPECT_GE(s.proxy_hits(), 1);
  20751. EXPECT_EQ(0, s.target_hits());
  20752. }
  20753. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  20754. // An entry with leading/trailing whitespace must still match — env-style
  20755. // values are commonly pasted with stray spaces and an implementation
  20756. // that feeds the raw token directly to inet_pton would fail to match
  20757. // valid CIDRs because of the spaces.
  20758. ProxyAndTargetServers s;
  20759. Client cli("127.0.0.1", s.target_port());
  20760. cli.set_proxy("127.0.0.1", s.proxy_port());
  20761. cli.set_no_proxy({" 127.0.0.0/8 "});
  20762. auto res = cli.Get("/");
  20763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20764. EXPECT_EQ(0, s.proxy_hits());
  20765. EXPECT_EQ(1, s.target_hits());
  20766. }
  20767. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  20768. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  20769. // go direct and must NOT carry Proxy-Authorization.
  20770. std::atomic<int> proxy_hits{0};
  20771. std::atomic<int> target_hits{0};
  20772. std::atomic<bool> target_saw_authz{false};
  20773. no_proxy_test::ScopedServer proxy_mock, target;
  20774. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20775. proxy_hits++;
  20776. res.status = 302;
  20777. res.set_header("Location", "http://127.0.0.1:" +
  20778. std::to_string(target.port()) + "/landed");
  20779. });
  20780. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20781. target_hits++;
  20782. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  20783. res.set_content("direct", "text/plain");
  20784. });
  20785. proxy_mock.listen();
  20786. target.listen();
  20787. Client cli("public.example", target.port());
  20788. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20789. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20790. cli.set_proxy_basic_auth("u", "p");
  20791. cli.set_no_proxy({"127.0.0.1"});
  20792. cli.set_follow_location(true);
  20793. auto res = cli.Get("/redir");
  20794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20795. EXPECT_GE(proxy_hits.load(), 1);
  20796. EXPECT_GE(target_hits.load(), 1);
  20797. EXPECT_FALSE(target_saw_authz.load());
  20798. }
  20799. #ifdef CPPHTTPLIB_SSL_ENABLED
  20800. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  20801. // Direct origin replying 407 must not trigger the digest retry; otherwise
  20802. // proxy creds would be sent to the (possibly hostile) origin.
  20803. std::atomic<int> target_hits{0};
  20804. std::atomic<bool> target_saw_proxy_authz{false};
  20805. no_proxy_test::ScopedServer target;
  20806. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20807. target_hits++;
  20808. if (req.has_header("Proxy-Authorization")) {
  20809. target_saw_proxy_authz = true;
  20810. }
  20811. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20812. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  20813. "nonce=\"abc\", algorithm=MD5");
  20814. });
  20815. target.listen();
  20816. // The proxy address is set to the target's port: the bypass MUST kick in;
  20817. // if it doesn't, the test still routes "via proxy" to the same server and
  20818. // the Proxy-Authorization assertion below catches the leak.
  20819. Client cli("evil.example", target.port());
  20820. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  20821. cli.set_proxy("127.0.0.1", target.port());
  20822. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20823. cli.set_no_proxy({"evil.example"});
  20824. auto res = cli.Get("/x");
  20825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20826. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20827. EXPECT_EQ(1, target_hits.load());
  20828. EXPECT_FALSE(target_saw_proxy_authz.load());
  20829. }
  20830. #endif
  20831. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  20832. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  20833. std::atomic<int> proxy_hits{0};
  20834. std::atomic<int> bypass_hits{0};
  20835. std::atomic<bool> proxy_saw_c_url{false};
  20836. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  20837. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  20838. proxy_hits++;
  20839. if (req.path.find("/start") != std::string::npos) {
  20840. res.status = 302;
  20841. res.set_header("Location", "http://127.0.0.1:" +
  20842. std::to_string(bypass_server.port()) +
  20843. "/middle");
  20844. return;
  20845. }
  20846. if (req.path.find("/end") != std::string::npos) {
  20847. proxy_saw_c_url = true;
  20848. res.set_content("c-via-proxy", "text/plain");
  20849. return;
  20850. }
  20851. res.set_content("unexpected", "text/plain");
  20852. });
  20853. // public.example's "advertised" port is arbitrary (the request never lands
  20854. // there — it goes through the proxy), but use a dynamic value to stay
  20855. // friendly with sharded parallel runs.
  20856. int public_port = bypass_server.port();
  20857. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  20858. bypass_hits++;
  20859. res.status = 302;
  20860. res.set_header("Location", "http://public.example:" +
  20861. std::to_string(public_port) + "/end");
  20862. });
  20863. proxy_mock.listen();
  20864. bypass_server.listen();
  20865. Client cli("public.example", public_port);
  20866. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20867. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20868. cli.set_no_proxy({"127.0.0.1"});
  20869. cli.set_follow_location(true);
  20870. auto res = cli.Get("/start");
  20871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20872. EXPECT_EQ(StatusCode::OK_200, res->status);
  20873. EXPECT_EQ("c-via-proxy", res->body);
  20874. EXPECT_GE(proxy_hits.load(), 2);
  20875. EXPECT_GE(bypass_hits.load(), 1);
  20876. EXPECT_TRUE(proxy_saw_c_url.load());
  20877. }
  20878. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  20879. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  20880. // request reconnects to the correct endpoint.
  20881. std::atomic<int> proxy_hits{0};
  20882. std::atomic<int> target_hits{0};
  20883. no_proxy_test::ScopedServer proxy_mock, target;
  20884. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20885. proxy_hits++;
  20886. res.set_content("via-proxy", "text/plain");
  20887. });
  20888. target.svr().Get(".*", [&](const Request &, Response &res) {
  20889. target_hits++;
  20890. res.set_content("direct", "text/plain");
  20891. });
  20892. proxy_mock.listen();
  20893. target.listen();
  20894. Client cli("public.example", target.port());
  20895. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20896. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20897. cli.set_keep_alive(true);
  20898. auto res1 = cli.Get("/a");
  20899. ASSERT_TRUE(res1);
  20900. EXPECT_EQ("via-proxy", res1->body);
  20901. EXPECT_EQ(1, proxy_hits.load());
  20902. EXPECT_EQ(0, target_hits.load());
  20903. cli.set_no_proxy({"public.example"});
  20904. auto res2 = cli.Get("/b");
  20905. ASSERT_TRUE(res2);
  20906. EXPECT_EQ("direct", res2->body);
  20907. EXPECT_EQ(1, proxy_hits.load());
  20908. EXPECT_EQ(1, target_hits.load());
  20909. }
  20910. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  20911. namespace proxy_tunnel_test {
  20912. // SSLServer counterpart to no_proxy_test::ScopedServer.
  20913. class ScopedSSLServer {
  20914. public:
  20915. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  20916. port_ = svr_.bind_to_any_port("127.0.0.1");
  20917. }
  20918. ~ScopedSSLServer() {
  20919. svr_.stop();
  20920. if (th_.joinable()) { th_.join(); }
  20921. }
  20922. SSLServer &svr() { return svr_; }
  20923. int port() const { return port_; }
  20924. void listen() {
  20925. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20926. svr_.wait_until_ready();
  20927. }
  20928. private:
  20929. SSLServer svr_;
  20930. std::thread th_;
  20931. int port_ = 0;
  20932. };
  20933. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  20934. class ScopedConnectProxy {
  20935. public:
  20936. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  20937. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  20938. if (listen_fd_ < 0) { return; }
  20939. int yes = 1;
  20940. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  20941. sockaddr_in a{};
  20942. a.sin_family = AF_INET;
  20943. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20944. a.sin_port = 0;
  20945. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  20946. return;
  20947. }
  20948. socklen_t alen = sizeof(a);
  20949. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  20950. 0) {
  20951. return;
  20952. }
  20953. port_ = ntohs(a.sin_port);
  20954. if (::listen(listen_fd_, 1) != 0) { return; }
  20955. th_ = std::thread([this] { run(); });
  20956. }
  20957. ~ScopedConnectProxy() {
  20958. stop_ = true;
  20959. if (listen_fd_ >= 0) {
  20960. ::shutdown(listen_fd_, SHUT_RDWR);
  20961. ::close(listen_fd_);
  20962. }
  20963. if (th_.joinable()) { th_.join(); }
  20964. }
  20965. int port() const { return port_; }
  20966. int connect_hits() const { return connect_hits_.load(); }
  20967. private:
  20968. void run() {
  20969. while (!stop_.load()) {
  20970. fd_set rfds;
  20971. FD_ZERO(&rfds);
  20972. FD_SET(listen_fd_, &rfds);
  20973. timeval tv{0, 100 * 1000};
  20974. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  20975. if (sel <= 0) { continue; }
  20976. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  20977. if (client_fd < 0) { continue; }
  20978. std::string req;
  20979. char buf[2048];
  20980. while (req.find("\r\n\r\n") == std::string::npos) {
  20981. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  20982. if (n <= 0) { break; }
  20983. req.append(buf, static_cast<size_t>(n));
  20984. }
  20985. if (req.compare(0, 7, "CONNECT") != 0) {
  20986. ::close(client_fd);
  20987. continue;
  20988. }
  20989. connect_hits_++;
  20990. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  20991. ::send(client_fd, ok, std::strlen(ok), 0);
  20992. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  20993. sockaddr_in o{};
  20994. o.sin_family = AF_INET;
  20995. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20996. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  20997. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  20998. 0) {
  20999. ::close(client_fd);
  21000. ::close(origin_fd);
  21001. continue;
  21002. }
  21003. auto forward = [](int from, int to) {
  21004. char b[8192];
  21005. for (;;) {
  21006. ssize_t n = ::recv(from, b, sizeof(b), 0);
  21007. if (n <= 0) { break; }
  21008. ssize_t off = 0;
  21009. while (off < n) {
  21010. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  21011. if (s <= 0) {
  21012. off = n;
  21013. break;
  21014. }
  21015. off += s;
  21016. }
  21017. }
  21018. ::shutdown(to, SHUT_WR);
  21019. };
  21020. std::thread t1([&] { forward(client_fd, origin_fd); });
  21021. std::thread t2([&] { forward(origin_fd, client_fd); });
  21022. t1.join();
  21023. t2.join();
  21024. ::close(client_fd);
  21025. ::close(origin_fd);
  21026. }
  21027. }
  21028. int forward_port_ = -1;
  21029. int listen_fd_ = -1;
  21030. int port_ = 0;
  21031. std::thread th_;
  21032. std::atomic<bool> stop_{false};
  21033. std::atomic<int> connect_hits_{0};
  21034. };
  21035. } // namespace proxy_tunnel_test
  21036. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  21037. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  21038. // retry; otherwise proxy creds would be sent to the origin.
  21039. std::atomic<int> origin_hits{0};
  21040. std::atomic<bool> origin_saw_proxy_authz{false};
  21041. proxy_tunnel_test::ScopedSSLServer origin;
  21042. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  21043. origin_hits++;
  21044. if (req.has_header("Proxy-Authorization")) {
  21045. origin_saw_proxy_authz = true;
  21046. }
  21047. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21048. res.set_header("Proxy-Authenticate",
  21049. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  21050. "algorithm=MD5");
  21051. });
  21052. origin.listen();
  21053. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  21054. ASSERT_NE(0, proxy.port());
  21055. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  21056. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  21057. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  21058. // and answer with its own status, making this test flaky.
  21059. SSLClient cli("127.0.0.1", origin.port());
  21060. cli.enable_server_certificate_verification(false);
  21061. cli.set_proxy("127.0.0.1", proxy.port());
  21062. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21063. auto res = cli.Get("/x");
  21064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21065. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21066. EXPECT_EQ(1, origin_hits.load());
  21067. EXPECT_FALSE(origin_saw_proxy_authz.load());
  21068. EXPECT_EQ(1, proxy.connect_hits());
  21069. }
  21070. #endif