test.cc 790 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611
  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(GetHeaderValueTest, DefaultValue) {
  1369. Headers headers = {{"Dummy", "Dummy"}};
  1370. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1371. EXPECT_STREQ("text/plain", val);
  1372. }
  1373. TEST(GetHeaderValueTest, DefaultValueInt) {
  1374. Headers headers = {{"Dummy", "Dummy"}};
  1375. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1376. EXPECT_EQ(100ull, val);
  1377. }
  1378. TEST(GetHeaderValueTest, RegularValue) {
  1379. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1380. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1381. EXPECT_STREQ("text/html", val);
  1382. }
  1383. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1384. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1385. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1386. EXPECT_STREQ("text/html", val);
  1387. }
  1388. TEST(GetHeaderValueTest, SetContent) {
  1389. Response res;
  1390. res.set_content("html", "text/html");
  1391. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1392. res.set_content("text", "text/plain");
  1393. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1394. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1395. }
  1396. TEST(GetHeaderValueTest, RegularValueInt) {
  1397. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1398. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1399. EXPECT_EQ(100ull, val);
  1400. }
  1401. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1402. Headers headers = {{"Content-Length", "x"}};
  1403. auto is_invalid_value = false;
  1404. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1405. is_invalid_value);
  1406. EXPECT_EQ(0ull, val);
  1407. EXPECT_TRUE(is_invalid_value);
  1408. }
  1409. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1410. // An all-digit value that overflows size_t must be reported as invalid, not
  1411. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1412. // a large length to a small one on 32-bit builds, leaving the framing length
  1413. // wrong while is_invalid_value stayed false.
  1414. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1415. auto is_invalid_value = false;
  1416. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1417. is_invalid_value);
  1418. EXPECT_TRUE(is_invalid_value);
  1419. // A well-formed length is unaffected.
  1420. Headers ok = {{"Content-Length", "1234"}};
  1421. is_invalid_value = false;
  1422. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1423. is_invalid_value);
  1424. EXPECT_EQ(1234ull, val);
  1425. EXPECT_FALSE(is_invalid_value);
  1426. }
  1427. TEST(GetHeaderValueTest, Range) {
  1428. {
  1429. Headers headers = {make_range_header({{1, -1}})};
  1430. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1431. EXPECT_STREQ("bytes=1-", val);
  1432. }
  1433. {
  1434. Headers headers = {make_range_header({{-1, 1}})};
  1435. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1436. EXPECT_STREQ("bytes=-1", val);
  1437. }
  1438. {
  1439. Headers headers = {make_range_header({{1, 10}})};
  1440. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1441. EXPECT_STREQ("bytes=1-10", val);
  1442. }
  1443. {
  1444. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1445. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1446. EXPECT_STREQ("bytes=1-10, 100-", val);
  1447. }
  1448. {
  1449. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1450. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1451. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1452. }
  1453. {
  1454. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1455. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1456. EXPECT_STREQ("bytes=0-0, -1", val);
  1457. }
  1458. }
  1459. TEST(BearerTokenAuthTest, SchemeValidation) {
  1460. // A value shorter than "Bearer " must not throw from the fixed-length
  1461. // substr, and a non-Bearer scheme must not be reported as a token.
  1462. struct {
  1463. const char *value;
  1464. const char *expected;
  1465. } cases[] = {
  1466. {"x", ""},
  1467. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1468. {"Bearer abc123", "abc123"},
  1469. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1470. };
  1471. for (const auto &c : cases) {
  1472. Request req;
  1473. req.set_header("Authorization", c.value);
  1474. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1475. }
  1476. }
  1477. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1478. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1479. // to depend on the standard library (libstdc++ handed back duplicates in
  1480. // reverse insertion order, libc++ in insertion order).
  1481. Request req;
  1482. req.set_header("Accept-Encoding", "gzip");
  1483. req.set_header("Accept-Encoding", "deflate");
  1484. req.set_header("Accept-Encoding", "br");
  1485. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1486. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1487. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1488. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1489. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1490. }
  1491. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1492. Request req;
  1493. req.set_header("X-Test", "only");
  1494. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1495. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1496. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1497. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1498. }
  1499. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1500. Headers headers;
  1501. headers.emplace("Host", "example.com");
  1502. headers.emplace("Accept-Encoding", "gzip");
  1503. headers.emplace("User-Agent", "test");
  1504. headers.emplace("Accept-Encoding", "deflate");
  1505. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1506. "Accept-Encoding=deflate ",
  1507. entries_to_string(headers));
  1508. }
  1509. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1510. Headers headers = {{"Content-Type", "text/html"},
  1511. {"CONTENT-TYPE", "text/xml"}};
  1512. EXPECT_EQ(2U, headers.count("content-type"));
  1513. auto it = headers.find("content-type");
  1514. ASSERT_TRUE(it != headers.end());
  1515. EXPECT_EQ("text/html", it->second);
  1516. }
  1517. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1518. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1519. // drop only those fields and leave everything positioned between them.
  1520. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1521. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1522. auto rng = headers.equal_range("a");
  1523. headers.erase(rng.first, rng.second);
  1524. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1525. }
  1526. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1527. Headers headers = {
  1528. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1529. EXPECT_EQ(3U, headers.erase("A"));
  1530. EXPECT_EQ(0U, headers.count("A"));
  1531. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1532. }
  1533. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1534. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1535. headers.emplace_front("Host", "example.com");
  1536. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1537. entries_to_string(headers));
  1538. }
  1539. TEST(ParseHeaderValueTest, Range) {
  1540. {
  1541. Ranges ranges;
  1542. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1543. EXPECT_TRUE(ret);
  1544. EXPECT_EQ(1u, ranges.size());
  1545. EXPECT_EQ(1u, ranges[0].first);
  1546. EXPECT_EQ(-1, ranges[0].second);
  1547. }
  1548. {
  1549. Ranges ranges;
  1550. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1551. EXPECT_TRUE(ret);
  1552. EXPECT_EQ(1u, ranges.size());
  1553. EXPECT_EQ(-1, ranges[0].first);
  1554. EXPECT_EQ(1u, ranges[0].second);
  1555. }
  1556. {
  1557. Ranges ranges;
  1558. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1559. EXPECT_TRUE(ret);
  1560. EXPECT_EQ(1u, ranges.size());
  1561. EXPECT_EQ(1u, ranges[0].first);
  1562. EXPECT_EQ(10u, ranges[0].second);
  1563. }
  1564. {
  1565. Ranges ranges;
  1566. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1567. EXPECT_FALSE(ret);
  1568. }
  1569. {
  1570. Ranges ranges;
  1571. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1572. EXPECT_TRUE(ret);
  1573. EXPECT_EQ(2u, ranges.size());
  1574. EXPECT_EQ(1u, ranges[0].first);
  1575. EXPECT_EQ(10u, ranges[0].second);
  1576. EXPECT_EQ(100u, ranges[1].first);
  1577. EXPECT_EQ(-1, ranges[1].second);
  1578. }
  1579. {
  1580. Ranges ranges;
  1581. auto ret =
  1582. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1583. EXPECT_TRUE(ret);
  1584. EXPECT_EQ(3u, ranges.size());
  1585. EXPECT_EQ(1u, ranges[0].first);
  1586. EXPECT_EQ(10u, ranges[0].second);
  1587. EXPECT_EQ(100u, ranges[1].first);
  1588. EXPECT_EQ(200u, ranges[1].second);
  1589. EXPECT_EQ(300u, ranges[2].first);
  1590. EXPECT_EQ(400u, ranges[2].second);
  1591. }
  1592. {
  1593. Ranges ranges;
  1594. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1595. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1596. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1597. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1598. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1599. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1600. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1601. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1602. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1603. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1604. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1605. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1606. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1607. EXPECT_TRUE(ranges.empty());
  1608. }
  1609. }
  1610. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1611. Request req;
  1612. req.set_header("Accept-Encoding", "gzip");
  1613. Response res;
  1614. res.set_header("Content-Type", "text/plain");
  1615. auto ret = detail::encoding_type(req, res);
  1616. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1617. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1618. #else
  1619. EXPECT_TRUE(ret == detail::EncodingType::None);
  1620. #endif
  1621. }
  1622. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1623. Request req;
  1624. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1625. Response res;
  1626. res.set_header("Content-Type", "text/plain");
  1627. auto ret = detail::encoding_type(req, res);
  1628. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1629. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1630. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1631. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1632. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1633. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1634. #else
  1635. EXPECT_TRUE(ret == detail::EncodingType::None);
  1636. #endif
  1637. }
  1638. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1639. Request req;
  1640. req.set_header("Accept-Encoding",
  1641. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1642. Response res;
  1643. res.set_header("Content-Type", "text/plain");
  1644. auto ret = detail::encoding_type(req, res);
  1645. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1646. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1647. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1648. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1649. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1650. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1651. #else
  1652. EXPECT_TRUE(ret == detail::EncodingType::None);
  1653. #endif
  1654. }
  1655. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1656. // All supported encodings rejected with q=0 should return None
  1657. Request req;
  1658. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1659. Response res;
  1660. res.set_header("Content-Type", "text/plain");
  1661. auto ret = detail::encoding_type(req, res);
  1662. EXPECT_TRUE(ret == detail::EncodingType::None);
  1663. }
  1664. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1665. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1666. Request req;
  1667. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1668. Response res;
  1669. res.set_header("Content-Type", "text/plain");
  1670. auto ret = detail::encoding_type(req, res);
  1671. EXPECT_TRUE(ret == detail::EncodingType::None);
  1672. }
  1673. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1674. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1675. Request req;
  1676. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1677. Response res;
  1678. res.set_header("Content-Type", "text/plain");
  1679. auto ret = detail::encoding_type(req, res);
  1680. EXPECT_TRUE(ret == detail::EncodingType::None);
  1681. }
  1682. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1683. // RFC 7231: Accept-Encoding values are case-insensitive
  1684. Request req;
  1685. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1686. Response res;
  1687. res.set_header("Content-Type", "text/plain");
  1688. auto ret = detail::encoding_type(req, res);
  1689. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1690. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1691. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1692. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1693. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1694. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1695. #else
  1696. EXPECT_TRUE(ret == detail::EncodingType::None);
  1697. #endif
  1698. }
  1699. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1700. // q value should determine priority, not hardcoded order
  1701. Request req;
  1702. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1703. Response res;
  1704. res.set_header("Content-Type", "text/plain");
  1705. auto ret = detail::encoding_type(req, res);
  1706. // gzip has highest q=1.0, so it should be selected even though
  1707. // br and zstd are also supported
  1708. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1709. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1710. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1711. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1712. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1713. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1714. #else
  1715. EXPECT_TRUE(ret == detail::EncodingType::None);
  1716. #endif
  1717. }
  1718. TEST(BufferStreamTest, read) {
  1719. detail::BufferStream strm1;
  1720. Stream &strm = strm1;
  1721. EXPECT_EQ(5, strm.write("hello"));
  1722. char buf[512];
  1723. EXPECT_EQ(2, strm.read(buf, 2));
  1724. EXPECT_EQ('h', buf[0]);
  1725. EXPECT_EQ('e', buf[1]);
  1726. EXPECT_EQ(2, strm.read(buf, 2));
  1727. EXPECT_EQ('l', buf[0]);
  1728. EXPECT_EQ('l', buf[1]);
  1729. EXPECT_EQ(1, strm.read(buf, 1));
  1730. EXPECT_EQ('o', buf[0]);
  1731. EXPECT_EQ(0, strm.read(buf, 1));
  1732. }
  1733. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1734. auto host = "www.httpwatch.com";
  1735. auto ip = hosted_at(host);
  1736. EXPECT_EQ("23.96.13.243", ip);
  1737. std::vector<std::string> addrs;
  1738. hosted_at(host, addrs);
  1739. EXPECT_EQ(1u, addrs.size());
  1740. }
  1741. #if 0 // It depends on each test environment...
  1742. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1743. auto host = "www.youtube.com";
  1744. std::vector<std::string> addrs;
  1745. hosted_at(host, addrs);
  1746. EXPECT_EQ(20u, addrs.size());
  1747. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1748. EXPECT_TRUE(it != addrs.end());
  1749. }
  1750. #endif
  1751. class ChunkedEncodingTest : public ::testing::Test {
  1752. protected:
  1753. ChunkedEncodingTest()
  1754. : cli_(HOST, PORT)
  1755. #ifdef CPPHTTPLIB_SSL_ENABLED
  1756. ,
  1757. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1758. #endif
  1759. {
  1760. cli_.set_connection_timeout(2);
  1761. #ifdef CPPHTTPLIB_SSL_ENABLED
  1762. cli_.enable_server_certificate_verification(false);
  1763. #endif
  1764. }
  1765. virtual void SetUp() {
  1766. read_file("./image.jpg", image_data_);
  1767. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1768. res.set_content("Hello World!", "text/plain");
  1769. });
  1770. svr_.Get(
  1771. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1772. res.set_chunked_content_provider(
  1773. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1774. size_t remaining = image_data_.size() - offset;
  1775. if (remaining == 0) {
  1776. sink.done();
  1777. } else {
  1778. constexpr size_t CHUNK_SIZE = 1024;
  1779. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1780. sink.write(&image_data_[offset], send_size);
  1781. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1782. }
  1783. return true;
  1784. });
  1785. });
  1786. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1787. svr_.wait_until_ready();
  1788. }
  1789. virtual void TearDown() {
  1790. svr_.stop();
  1791. if (!request_threads_.empty()) {
  1792. std::this_thread::sleep_for(std::chrono::seconds(1));
  1793. for (auto &t : request_threads_) {
  1794. t.join();
  1795. }
  1796. }
  1797. t_.join();
  1798. }
  1799. #ifdef CPPHTTPLIB_SSL_ENABLED
  1800. SSLClient cli_;
  1801. SSLServer svr_;
  1802. #else
  1803. Client cli_;
  1804. Server svr_;
  1805. #endif
  1806. thread t_;
  1807. std::vector<thread> request_threads_;
  1808. std::string image_data_;
  1809. };
  1810. TEST_F(ChunkedEncodingTest, NormalGet) {
  1811. auto res = cli_.Get("/chunked");
  1812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1813. std::string out;
  1814. read_file("./image.jpg", out);
  1815. EXPECT_EQ(StatusCode::OK_200, res->status);
  1816. EXPECT_EQ(out, res->body);
  1817. }
  1818. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1819. std::string body;
  1820. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1821. body.append(data, data_length);
  1822. return true;
  1823. });
  1824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1825. std::string out;
  1826. read_file("./image.jpg", out);
  1827. EXPECT_EQ(StatusCode::OK_200, res->status);
  1828. EXPECT_EQ(out, body);
  1829. }
  1830. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1831. std::string body;
  1832. auto res = cli_.Get(
  1833. "/chunked",
  1834. [&](const Response &response) {
  1835. EXPECT_EQ(StatusCode::OK_200, response.status);
  1836. return true;
  1837. },
  1838. [&](const char *data, size_t data_length) {
  1839. body.append(data, data_length);
  1840. return true;
  1841. });
  1842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1843. std::string out;
  1844. read_file("./image.jpg", out);
  1845. EXPECT_EQ(StatusCode::OK_200, res->status);
  1846. EXPECT_EQ(out, body);
  1847. }
  1848. TEST(RangeTest, FromHTTPBin_Online) {
  1849. auto host = "httpbingo.org";
  1850. auto path = std::string{"/range/32"};
  1851. #ifdef CPPHTTPLIB_SSL_ENABLED
  1852. auto port = 443;
  1853. SSLClient cli(host, port);
  1854. #else
  1855. auto port = 80;
  1856. Client cli(host, port);
  1857. #endif
  1858. cli.set_connection_timeout(5);
  1859. {
  1860. auto res = cli.Get(path);
  1861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1862. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1863. EXPECT_EQ(StatusCode::OK_200, res->status);
  1864. }
  1865. {
  1866. Headers headers = {make_range_header({{1, -1}})};
  1867. auto res = cli.Get(path, headers);
  1868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1869. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1870. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1871. }
  1872. {
  1873. Headers headers = {make_range_header({{1, 10}})};
  1874. auto res = cli.Get(path, headers);
  1875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1876. EXPECT_EQ("bcdefghijk", res->body);
  1877. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1878. }
  1879. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1880. // entire resource, while the original httpbin returned 200. Both are
  1881. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1882. {
  1883. Headers headers = {make_range_header({{0, 31}})};
  1884. auto res = cli.Get(path, headers);
  1885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1886. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1887. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1888. res->status == StatusCode::PartialContent_206);
  1889. }
  1890. {
  1891. Headers headers = {make_range_header({{0, -1}})};
  1892. auto res = cli.Get(path, headers);
  1893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1894. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1895. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1896. res->status == StatusCode::PartialContent_206);
  1897. }
  1898. // go-httpbin returns 206 with clamped range for over-range requests,
  1899. // while the original httpbin returned 416. Both behaviors are observed
  1900. // in real servers, so we only verify the request succeeds.
  1901. {
  1902. Headers headers = {make_range_header({{0, 32}})};
  1903. auto res = cli.Get(path, headers);
  1904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1905. }
  1906. }
  1907. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1908. auto host = "unresolvableaddress.local";
  1909. auto path = std::string{"/"};
  1910. #ifdef CPPHTTPLIB_SSL_ENABLED
  1911. auto port = 443;
  1912. SSLClient cli(host, port);
  1913. #else
  1914. auto port = 80;
  1915. Client cli(host, port);
  1916. #endif
  1917. cli.set_connection_timeout(1);
  1918. {
  1919. auto res = cli.Get(path);
  1920. ASSERT_FALSE(res);
  1921. }
  1922. std::this_thread::sleep_for(std::chrono::seconds(8));
  1923. }
  1924. #if defined(__linux__) && defined(__GLIBC__) && \
  1925. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1926. // Forward declaration: in split builds split.py strips `inline` and moves the
  1927. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1928. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1929. // against the symbol in both header-only and split builds.
  1930. namespace httplib {
  1931. namespace detail {
  1932. int getaddrinfo_with_timeout(const char *node, const char *service,
  1933. const struct addrinfo *hints,
  1934. struct addrinfo **res, time_t timeout_sec);
  1935. } // namespace detail
  1936. } // namespace httplib
  1937. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1938. //
  1939. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1940. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1941. // gai_suspend() call hits the connection timeout the function calls
  1942. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1943. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1944. // still alive and still references the now-destroyed stack frame.
  1945. //
  1946. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1947. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1948. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1949. // and runs them in a container.
  1950. namespace {
  1951. bool should_run_issue_2431_tests() {
  1952. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1953. return v && *v && std::string(v) != "0";
  1954. }
  1955. std::string unique_unresolvable_host(int n) {
  1956. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1957. // glibc still asks the configured nameserver — which is exactly the path
  1958. // we want to exercise. A unique label per call avoids the resolver cache.
  1959. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1960. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1961. std::to_string(n) + ".invalid";
  1962. }
  1963. } // namespace
  1964. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1965. if (!should_run_issue_2431_tests()) {
  1966. GTEST_SKIP()
  1967. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1968. }
  1969. for (int i = 0; i < 8; ++i) {
  1970. struct addrinfo hints;
  1971. memset(&hints, 0, sizeof(hints));
  1972. hints.ai_family = AF_UNSPEC;
  1973. hints.ai_socktype = SOCK_STREAM;
  1974. auto host = unique_unresolvable_host(i);
  1975. struct addrinfo *result = nullptr;
  1976. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1977. &result, /*timeout_sec=*/1);
  1978. if (rc == 0 && result) { freeaddrinfo(result); }
  1979. }
  1980. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1981. // stack region they still believe holds their gaicb.
  1982. std::this_thread::sleep_for(std::chrono::seconds(3));
  1983. }
  1984. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1985. if (!should_run_issue_2431_tests()) {
  1986. GTEST_SKIP()
  1987. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1988. }
  1989. std::atomic<bool> stop{false};
  1990. std::vector<std::thread> threads;
  1991. for (int t = 0; t < 8; ++t) {
  1992. threads.emplace_back([t, &stop] {
  1993. int i = 0;
  1994. while (!stop.load(std::memory_order_relaxed)) {
  1995. struct addrinfo hints;
  1996. memset(&hints, 0, sizeof(hints));
  1997. hints.ai_family = AF_UNSPEC;
  1998. hints.ai_socktype = SOCK_STREAM;
  1999. auto host = unique_unresolvable_host(t * 100000 + i++);
  2000. struct addrinfo *result = nullptr;
  2001. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2002. &result, /*timeout_sec=*/1);
  2003. if (rc == 0 && result) { freeaddrinfo(result); }
  2004. }
  2005. });
  2006. }
  2007. std::this_thread::sleep_for(std::chrono::seconds(8));
  2008. stop.store(true, std::memory_order_relaxed);
  2009. for (auto &th : threads) {
  2010. th.join();
  2011. }
  2012. std::this_thread::sleep_for(std::chrono::seconds(3));
  2013. }
  2014. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2015. if (!should_run_issue_2431_tests()) {
  2016. GTEST_SKIP()
  2017. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2018. }
  2019. std::atomic<bool> stop{false};
  2020. std::vector<std::thread> threads;
  2021. for (int t = 0; t < 8; ++t) {
  2022. threads.emplace_back([t, &stop] {
  2023. int i = 0;
  2024. while (!stop.load(std::memory_order_relaxed)) {
  2025. auto host = unique_unresolvable_host(t * 100000 + i++);
  2026. Client cli(host, 80);
  2027. cli.set_connection_timeout(1, 0);
  2028. cli.set_read_timeout(1, 0);
  2029. cli.set_write_timeout(1, 0);
  2030. (void)cli.Get("/");
  2031. }
  2032. });
  2033. }
  2034. std::this_thread::sleep_for(std::chrono::seconds(8));
  2035. stop.store(true, std::memory_order_relaxed);
  2036. for (auto &th : threads) {
  2037. th.join();
  2038. }
  2039. std::this_thread::sleep_for(std::chrono::seconds(3));
  2040. }
  2041. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2042. TEST(ConnectionErrorTest, InvalidHost) {
  2043. auto host = "-abcde.com";
  2044. #ifdef CPPHTTPLIB_SSL_ENABLED
  2045. auto port = 443;
  2046. SSLClient cli(host, port);
  2047. #else
  2048. auto port = 80;
  2049. Client cli(host, port);
  2050. #endif
  2051. cli.set_connection_timeout(std::chrono::seconds(2));
  2052. auto res = cli.Get("/");
  2053. ASSERT_TRUE(!res);
  2054. EXPECT_EQ(Error::Connection, res.error());
  2055. }
  2056. TEST(ConnectionErrorTest, InvalidHost2) {
  2057. auto host = "httpcan.org/";
  2058. #ifdef CPPHTTPLIB_SSL_ENABLED
  2059. SSLClient cli(host);
  2060. #else
  2061. Client cli(host);
  2062. #endif
  2063. cli.set_connection_timeout(std::chrono::seconds(2));
  2064. auto res = cli.Get("/");
  2065. ASSERT_TRUE(!res);
  2066. EXPECT_EQ(Error::Connection, res.error());
  2067. }
  2068. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2069. auto host = "httpcan.org/";
  2070. #ifdef CPPHTTPLIB_SSL_ENABLED
  2071. SSLClient cli(host);
  2072. #else
  2073. Client cli(host);
  2074. #endif
  2075. cli.set_connection_timeout(std::chrono::seconds(2));
  2076. auto res = cli.Get("/");
  2077. ASSERT_TRUE(!res);
  2078. stringstream s;
  2079. s << "error code: " << res.error();
  2080. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2081. }
  2082. TEST(ConnectionErrorTest, InvalidPort) {
  2083. auto host = "localhost";
  2084. auto port = 44380;
  2085. #ifdef CPPHTTPLIB_SSL_ENABLED
  2086. SSLClient cli(host, port);
  2087. #else
  2088. Client cli(host, port);
  2089. #endif
  2090. cli.set_connection_timeout(std::chrono::seconds(2));
  2091. auto res = cli.Get("/");
  2092. ASSERT_TRUE(!res);
  2093. EXPECT_TRUE(Error::Connection == res.error() ||
  2094. Error::ConnectionTimeout == res.error());
  2095. }
  2096. TEST(ConnectionErrorTest, Timeout_Online) {
  2097. auto host = "google.com";
  2098. #ifdef CPPHTTPLIB_SSL_ENABLED
  2099. auto port = 44380;
  2100. SSLClient cli(host, port);
  2101. #else
  2102. auto port = 8080;
  2103. Client cli(host, port);
  2104. #endif
  2105. cli.set_connection_timeout(std::chrono::seconds(2));
  2106. // only probe one address type so that the error reason
  2107. // correlates to the timed-out IPv4, not the unsupported
  2108. // IPv6 connection attempt
  2109. cli.set_address_family(AF_INET);
  2110. auto res = cli.Get("/");
  2111. ASSERT_TRUE(!res);
  2112. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2113. }
  2114. TEST(CancelTest, NoCancel_Online) {
  2115. auto host = "httpbingo.org";
  2116. auto path = std::string{"/range/32"};
  2117. #ifdef CPPHTTPLIB_SSL_ENABLED
  2118. auto port = 443;
  2119. SSLClient cli(host, port);
  2120. #else
  2121. auto port = 80;
  2122. Client cli(host, port);
  2123. #endif
  2124. cli.set_connection_timeout(std::chrono::seconds(5));
  2125. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2127. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2128. EXPECT_EQ(StatusCode::OK_200, res->status);
  2129. }
  2130. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2131. // Use /bytes with a large payload so that the DownloadProgress callback
  2132. // (which only fires for Content-Length responses) is invoked before the
  2133. // entire body is received, giving cancellation a chance to fire.
  2134. auto host = "httpbingo.org";
  2135. auto path = std::string{"/bytes/524288"};
  2136. #ifdef CPPHTTPLIB_SSL_ENABLED
  2137. auto port = 443;
  2138. SSLClient cli(host, port);
  2139. #else
  2140. auto port = 80;
  2141. Client cli(host, port);
  2142. #endif
  2143. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2144. cli.set_connection_timeout(std::chrono::seconds(5));
  2145. ASSERT_TRUE(!res);
  2146. EXPECT_EQ(Error::Canceled, res.error());
  2147. }
  2148. TEST(CancelTest, WithCancelLargePayload_Online) {
  2149. auto host = "httpbingo.org";
  2150. auto path = std::string{"/bytes/524288"};
  2151. #ifdef CPPHTTPLIB_SSL_ENABLED
  2152. auto port = 443;
  2153. SSLClient cli(host, port);
  2154. #else
  2155. auto port = 80;
  2156. Client cli(host, port);
  2157. #endif
  2158. cli.set_connection_timeout(std::chrono::seconds(5));
  2159. uint32_t count = 0;
  2160. auto res =
  2161. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2162. ASSERT_TRUE(!res);
  2163. EXPECT_EQ(Error::Canceled, res.error());
  2164. }
  2165. TEST(CancelTest, NoCancelPost) {
  2166. Server svr;
  2167. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2168. res.set_content("Hello World!", "text/plain");
  2169. });
  2170. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2171. auto se = detail::scope_exit([&] {
  2172. svr.stop();
  2173. thread.join();
  2174. ASSERT_FALSE(svr.is_running());
  2175. });
  2176. svr.wait_until_ready();
  2177. Client cli(HOST, PORT);
  2178. cli.set_connection_timeout(std::chrono::seconds(5));
  2179. auto res =
  2180. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2181. "application/json", [](uint64_t, uint64_t) { return true; });
  2182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2183. EXPECT_EQ("Hello World!", res->body);
  2184. EXPECT_EQ(StatusCode::OK_200, res->status);
  2185. }
  2186. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2187. Server svr;
  2188. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2189. res.set_content("Hello World!", "text/plain");
  2190. });
  2191. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2192. auto se = detail::scope_exit([&] {
  2193. svr.stop();
  2194. thread.join();
  2195. ASSERT_FALSE(svr.is_running());
  2196. });
  2197. svr.wait_until_ready();
  2198. Client cli(HOST, PORT);
  2199. cli.set_connection_timeout(std::chrono::seconds(5));
  2200. auto res =
  2201. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2202. "application/json", [](uint64_t, uint64_t) { return false; });
  2203. ASSERT_TRUE(!res);
  2204. EXPECT_EQ(Error::Canceled, res.error());
  2205. }
  2206. TEST(CancelTest, WithCancelLargePayloadPost) {
  2207. Server svr;
  2208. svr.set_payload_max_length(200 * 1024 * 1024);
  2209. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2210. res.set_content(LARGE_DATA, "text/plain");
  2211. });
  2212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2213. auto se = detail::scope_exit([&] {
  2214. svr.stop();
  2215. thread.join();
  2216. ASSERT_FALSE(svr.is_running());
  2217. });
  2218. svr.wait_until_ready();
  2219. Client cli(HOST, PORT);
  2220. cli.set_payload_max_length(200 * 1024 * 1024);
  2221. cli.set_connection_timeout(std::chrono::seconds(5));
  2222. auto res =
  2223. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2224. "application/json", [](uint64_t, uint64_t) { return false; });
  2225. ASSERT_TRUE(!res);
  2226. EXPECT_EQ(Error::Canceled, res.error());
  2227. }
  2228. TEST(CancelTest, NoCancelPut) {
  2229. Server svr;
  2230. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2231. res.set_content("Hello World!", "text/plain");
  2232. });
  2233. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2234. auto se = detail::scope_exit([&] {
  2235. svr.stop();
  2236. thread.join();
  2237. ASSERT_FALSE(svr.is_running());
  2238. });
  2239. svr.wait_until_ready();
  2240. Client cli(HOST, PORT);
  2241. cli.set_connection_timeout(std::chrono::seconds(5));
  2242. auto res =
  2243. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2244. "application/json", [](uint64_t, uint64_t) { return true; });
  2245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2246. EXPECT_EQ("Hello World!", res->body);
  2247. EXPECT_EQ(StatusCode::OK_200, res->status);
  2248. }
  2249. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2250. Server svr;
  2251. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2252. res.set_content("Hello World!", "text/plain");
  2253. });
  2254. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2255. auto se = detail::scope_exit([&] {
  2256. svr.stop();
  2257. thread.join();
  2258. ASSERT_FALSE(svr.is_running());
  2259. });
  2260. svr.wait_until_ready();
  2261. Client cli(HOST, PORT);
  2262. cli.set_connection_timeout(std::chrono::seconds(5));
  2263. auto res =
  2264. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2265. "application/json", [](uint64_t, uint64_t) { return false; });
  2266. ASSERT_TRUE(!res);
  2267. EXPECT_EQ(Error::Canceled, res.error());
  2268. }
  2269. TEST(CancelTest, WithCancelLargePayloadPut) {
  2270. Server svr;
  2271. svr.set_payload_max_length(200 * 1024 * 1024);
  2272. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2273. res.set_content(LARGE_DATA, "text/plain");
  2274. });
  2275. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2276. auto se = detail::scope_exit([&] {
  2277. svr.stop();
  2278. thread.join();
  2279. ASSERT_FALSE(svr.is_running());
  2280. });
  2281. svr.wait_until_ready();
  2282. Client cli(HOST, PORT);
  2283. cli.set_payload_max_length(200 * 1024 * 1024);
  2284. cli.set_connection_timeout(std::chrono::seconds(5));
  2285. auto res =
  2286. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2287. "application/json", [](uint64_t, uint64_t) { return false; });
  2288. ASSERT_TRUE(!res);
  2289. EXPECT_EQ(Error::Canceled, res.error());
  2290. }
  2291. TEST(CancelTest, NoCancelPatch) {
  2292. Server svr;
  2293. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2294. res.set_content("Hello World!", "text/plain");
  2295. });
  2296. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2297. auto se = detail::scope_exit([&] {
  2298. svr.stop();
  2299. thread.join();
  2300. ASSERT_FALSE(svr.is_running());
  2301. });
  2302. svr.wait_until_ready();
  2303. Client cli(HOST, PORT);
  2304. cli.set_connection_timeout(std::chrono::seconds(5));
  2305. auto res =
  2306. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2307. "application/json", [](uint64_t, uint64_t) { return true; });
  2308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2309. EXPECT_EQ("Hello World!", res->body);
  2310. EXPECT_EQ(StatusCode::OK_200, res->status);
  2311. }
  2312. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2313. Server svr;
  2314. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2315. res.set_content("Hello World!", "text/plain");
  2316. });
  2317. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2318. auto se = detail::scope_exit([&] {
  2319. svr.stop();
  2320. thread.join();
  2321. ASSERT_FALSE(svr.is_running());
  2322. });
  2323. svr.wait_until_ready();
  2324. Client cli(HOST, PORT);
  2325. cli.set_connection_timeout(std::chrono::seconds(5));
  2326. auto res =
  2327. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2328. "application/json", [](uint64_t, uint64_t) { return false; });
  2329. ASSERT_TRUE(!res);
  2330. EXPECT_EQ(Error::Canceled, res.error());
  2331. }
  2332. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2333. Server svr;
  2334. svr.set_payload_max_length(200 * 1024 * 1024);
  2335. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2336. res.set_content(LARGE_DATA, "text/plain");
  2337. });
  2338. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2339. auto se = detail::scope_exit([&] {
  2340. svr.stop();
  2341. thread.join();
  2342. ASSERT_FALSE(svr.is_running());
  2343. });
  2344. svr.wait_until_ready();
  2345. Client cli(HOST, PORT);
  2346. cli.set_payload_max_length(200 * 1024 * 1024);
  2347. cli.set_connection_timeout(std::chrono::seconds(5));
  2348. auto res =
  2349. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2350. "application/json", [](uint64_t, uint64_t) { return false; });
  2351. ASSERT_TRUE(!res);
  2352. EXPECT_EQ(Error::Canceled, res.error());
  2353. }
  2354. TEST(CancelTest, NoCancelDelete) {
  2355. Server svr;
  2356. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2357. res.set_content("Hello World!", "text/plain");
  2358. });
  2359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2360. auto se = detail::scope_exit([&] {
  2361. svr.stop();
  2362. thread.join();
  2363. ASSERT_FALSE(svr.is_running());
  2364. });
  2365. svr.wait_until_ready();
  2366. Client cli(HOST, PORT);
  2367. cli.set_connection_timeout(std::chrono::seconds(5));
  2368. auto res =
  2369. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2370. "application/json", [](uint64_t, uint64_t) { return true; });
  2371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2372. EXPECT_EQ("Hello World!", res->body);
  2373. EXPECT_EQ(StatusCode::OK_200, res->status);
  2374. }
  2375. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2376. Server svr;
  2377. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2378. res.set_content("Hello World!", "text/plain");
  2379. });
  2380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2381. auto se = detail::scope_exit([&] {
  2382. svr.stop();
  2383. thread.join();
  2384. ASSERT_FALSE(svr.is_running());
  2385. });
  2386. svr.wait_until_ready();
  2387. Client cli(HOST, PORT);
  2388. cli.set_connection_timeout(std::chrono::seconds(5));
  2389. auto res =
  2390. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2391. "application/json", [](uint64_t, uint64_t) { return false; });
  2392. ASSERT_TRUE(!res);
  2393. EXPECT_EQ(Error::Canceled, res.error());
  2394. }
  2395. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2396. Server svr;
  2397. svr.set_payload_max_length(200 * 1024 * 1024);
  2398. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2399. res.set_content(LARGE_DATA, "text/plain");
  2400. });
  2401. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2402. auto se = detail::scope_exit([&] {
  2403. svr.stop();
  2404. thread.join();
  2405. ASSERT_FALSE(svr.is_running());
  2406. });
  2407. svr.wait_until_ready();
  2408. Client cli(HOST, PORT);
  2409. cli.set_payload_max_length(200 * 1024 * 1024);
  2410. cli.set_connection_timeout(std::chrono::seconds(5));
  2411. auto res =
  2412. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2413. "application/json", [](uint64_t, uint64_t) { return false; });
  2414. ASSERT_TRUE(!res);
  2415. EXPECT_EQ(Error::Canceled, res.error());
  2416. }
  2417. static std::string remove_whitespace(const std::string &input) {
  2418. std::string output;
  2419. output.reserve(input.size());
  2420. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2421. [](unsigned char c) { return !std::isspace(c); });
  2422. return output;
  2423. }
  2424. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2425. auto host = "httpbingo.org";
  2426. auto path = std::string{"/basic-auth/hello/world"};
  2427. #ifdef CPPHTTPLIB_SSL_ENABLED
  2428. auto port = 443;
  2429. SSLClient cli(host, port);
  2430. #else
  2431. auto port = 80;
  2432. Client cli(host, port);
  2433. #endif
  2434. {
  2435. auto res = cli.Get(path);
  2436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2437. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2438. }
  2439. {
  2440. auto res = cli.Get(
  2441. path, Headers{make_basic_authentication_header("hello", "world")});
  2442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2443. auto body = remove_whitespace(res->body);
  2444. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2445. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2446. EXPECT_EQ(StatusCode::OK_200, res->status);
  2447. }
  2448. {
  2449. cli.set_basic_auth("hello", "world");
  2450. auto res = cli.Get(path);
  2451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2452. auto body = remove_whitespace(res->body);
  2453. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2454. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2455. EXPECT_EQ(StatusCode::OK_200, res->status);
  2456. }
  2457. {
  2458. cli.set_basic_auth("hello", "bad");
  2459. auto res = cli.Get(path);
  2460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2461. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2462. }
  2463. {
  2464. cli.set_basic_auth("bad", "world");
  2465. auto res = cli.Get(path);
  2466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2467. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2468. }
  2469. }
  2470. #ifdef CPPHTTPLIB_SSL_ENABLED
  2471. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2472. auto host = "httpbingo.org";
  2473. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2474. auto paths = std::vector<std::string>{
  2475. "/digest-auth/auth/hello/world/MD5",
  2476. "/digest-auth/auth/hello/world/SHA-256",
  2477. };
  2478. auto port = 443;
  2479. SSLClient cli(host, port);
  2480. {
  2481. auto res = cli.Get(unauth_path);
  2482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2483. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2484. }
  2485. {
  2486. cli.set_digest_auth("hello", "world");
  2487. for (const auto &path : paths) {
  2488. auto res = cli.Get(path.c_str());
  2489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2490. auto body = remove_whitespace(res->body);
  2491. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2492. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2493. EXPECT_EQ(StatusCode::OK_200, res->status);
  2494. }
  2495. cli.set_digest_auth("hello", "bad");
  2496. for (const auto &path : paths) {
  2497. auto res = cli.Get(path.c_str());
  2498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2499. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2500. }
  2501. }
  2502. }
  2503. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2504. // comma-separated list of challenges, and each challenge may itself carry a
  2505. // comma-separated auth-param list, so a server can legally offer Basic
  2506. // before Digest, either as two field lines or packed into one. Runs one 401
  2507. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2508. // value() joins them in receipt order) and checks that the retry carries a
  2509. // well-formed Digest Authorization header naming expected_realm.
  2510. static void
  2511. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2512. const std::string &expected_realm) {
  2513. std::atomic<int> hits{0};
  2514. Server svr;
  2515. svr.Get("/x", [&](const Request &req, Response &res) {
  2516. if (++hits == 1) {
  2517. res.status = StatusCode::Unauthorized_401;
  2518. for (const auto &challenge : challenges) {
  2519. res.set_header("WWW-Authenticate", challenge);
  2520. }
  2521. } else {
  2522. auto authorization = req.get_header_value("Authorization");
  2523. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2524. EXPECT_NE(std::string::npos,
  2525. authorization.find("realm=\"" + expected_realm + "\""));
  2526. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2527. res.set_content("ok", "text/plain");
  2528. }
  2529. });
  2530. auto port = svr.bind_to_any_port(HOST);
  2531. std::thread t([&]() { svr.listen_after_bind(); });
  2532. auto se = detail::scope_exit([&] {
  2533. svr.stop();
  2534. t.join();
  2535. });
  2536. svr.wait_until_ready();
  2537. Client cli(HOST, port);
  2538. cli.set_digest_auth("hello", "world");
  2539. auto res = cli.Get("/x");
  2540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2541. EXPECT_EQ(2, hits.load());
  2542. }
  2543. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2544. static const char *kDigestChallenge =
  2545. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2546. "algorithm=MD5";
  2547. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2548. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2549. "testrealm");
  2550. }
  2551. // Same challenge list with the schemes in the opposite order, to make sure
  2552. // the fix above didn't just special-case "Basic first".
  2553. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2554. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2555. "testrealm");
  2556. }
  2557. // A comma inside a quoted auth-param value must not be mistaken for the
  2558. // separator between two challenges (or two auth-params).
  2559. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2560. run_digest_challenge_list_test(
  2561. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2562. "algorithm=MD5"},
  2563. "test,realm");
  2564. }
  2565. #endif
  2566. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2567. auto host = "google.com";
  2568. auto another_host = "example.com";
  2569. auto wrong_ip = "0.0.0.0";
  2570. #ifdef CPPHTTPLIB_SSL_ENABLED
  2571. SSLClient cli(host);
  2572. #else
  2573. Client cli(host);
  2574. #endif
  2575. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2576. auto res = cli.Get("/");
  2577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2578. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2579. }
  2580. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2581. auto host = "google.com";
  2582. auto wrong_ip = "0.0.0.0";
  2583. #ifdef CPPHTTPLIB_SSL_ENABLED
  2584. SSLClient cli(host);
  2585. #else
  2586. Client cli(host);
  2587. #endif
  2588. cli.set_hostname_addr_map({{host, wrong_ip}});
  2589. auto res = cli.Get("/");
  2590. ASSERT_TRUE(!res);
  2591. EXPECT_EQ(Error::Connection, res.error());
  2592. }
  2593. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2594. // A mapped value that is not an IP literal must be resolved. "localhost"
  2595. // resolves from the hosts file, so this test needs no external DNS.
  2596. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2597. auto host = "target.invalid";
  2598. Server svr;
  2599. std::string received_host;
  2600. svr.Get("/hi", [&](const Request &req, Response &res) {
  2601. received_host = req.get_header_value("Host");
  2602. res.set_content("Hello World!", "text/plain");
  2603. });
  2604. auto port = svr.bind_to_any_port(HOST);
  2605. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2606. auto se = detail::scope_exit([&] {
  2607. svr.stop();
  2608. thread.join();
  2609. ASSERT_FALSE(svr.is_running());
  2610. });
  2611. svr.wait_until_ready();
  2612. Client cli(host, port);
  2613. cli.set_hostname_addr_map({{host, HOST}});
  2614. auto res = cli.Get("/hi");
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::OK_200, res->status);
  2617. // The mapping only redirects the connection; the identity stays host_.
  2618. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2619. }
  2620. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2621. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2622. auto host = "target.invalid";
  2623. Server svr;
  2624. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2625. res.set_content("Hello World!", "text/plain");
  2626. });
  2627. auto port = svr.bind_to_any_port("127.0.0.1");
  2628. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2629. auto se = detail::scope_exit([&] {
  2630. svr.stop();
  2631. thread.join();
  2632. ASSERT_FALSE(svr.is_running());
  2633. });
  2634. svr.wait_until_ready();
  2635. Client cli(host, port);
  2636. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2637. auto res = cli.Get("/hi");
  2638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2639. EXPECT_EQ(StatusCode::OK_200, res->status);
  2640. }
  2641. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2642. // An empty mapped value must leave host_ as the connection target. Without
  2643. // that guard the empty value would become the host argument, getaddrinfo
  2644. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2645. // loopback - silently connecting somewhere the caller never asked for.
  2646. // The server listens on loopback, so such a fallback would succeed and is
  2647. // therefore observable as a failure of this test.
  2648. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2649. Server svr;
  2650. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2651. res.set_content("Hello World!", "text/plain");
  2652. });
  2653. auto port = svr.bind_to_any_port(HOST);
  2654. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2655. auto se = detail::scope_exit([&] {
  2656. svr.stop();
  2657. thread.join();
  2658. ASSERT_FALSE(svr.is_running());
  2659. });
  2660. svr.wait_until_ready();
  2661. Client cli(blackhole, port);
  2662. cli.set_hostname_addr_map({{blackhole, ""}});
  2663. cli.set_connection_timeout(1);
  2664. auto res = cli.Get("/hi");
  2665. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2666. }
  2667. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2668. auto host = "httpbingo.org";
  2669. auto path = std::string{"/absolute-redirect/3"};
  2670. #ifdef CPPHTTPLIB_SSL_ENABLED
  2671. SSLClient cli(host);
  2672. #else
  2673. Client cli(host);
  2674. #endif
  2675. cli.set_follow_location(true);
  2676. auto res = cli.Get(path);
  2677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2678. EXPECT_EQ(StatusCode::OK_200, res->status);
  2679. }
  2680. TEST(RedirectTest, Redirect_Online) {
  2681. auto host = "httpbingo.org";
  2682. auto path = std::string{"/redirect/3"};
  2683. #ifdef CPPHTTPLIB_SSL_ENABLED
  2684. SSLClient cli(host);
  2685. #else
  2686. Client cli(host);
  2687. #endif
  2688. cli.set_follow_location(true);
  2689. auto res = cli.Get(path);
  2690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2691. EXPECT_EQ(StatusCode::OK_200, res->status);
  2692. }
  2693. TEST(RelativeRedirectTest, Redirect_Online) {
  2694. auto host = "httpbingo.org";
  2695. auto path = std::string{"/relative-redirect/3"};
  2696. #ifdef CPPHTTPLIB_SSL_ENABLED
  2697. SSLClient cli(host);
  2698. #else
  2699. Client cli(host);
  2700. #endif
  2701. cli.set_follow_location(true);
  2702. auto res = cli.Get(path);
  2703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2704. EXPECT_EQ(StatusCode::OK_200, res->status);
  2705. }
  2706. TEST(TooManyRedirectTest, Redirect_Online) {
  2707. auto host = "httpbingo.org";
  2708. auto path = std::string{"/redirect/21"};
  2709. #ifdef CPPHTTPLIB_SSL_ENABLED
  2710. SSLClient cli(host);
  2711. #else
  2712. Client cli(host);
  2713. #endif
  2714. cli.set_follow_location(true);
  2715. auto res = cli.Get(path);
  2716. ASSERT_TRUE(!res);
  2717. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2718. }
  2719. #ifdef CPPHTTPLIB_SSL_ENABLED
  2720. TEST(YahooRedirectTest, Redirect_Online) {
  2721. Client cli("yahoo.com");
  2722. auto res = cli.Get("/");
  2723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2724. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2725. cli.set_follow_location(true);
  2726. res = cli.Get("/");
  2727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2728. EXPECT_EQ(StatusCode::OK_200, res->status);
  2729. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2730. }
  2731. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2732. #define REDIR_HOST "httpbingo.org"
  2733. #define REDIR_PATH "/redirect-to"
  2734. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2735. SSLClient cli(REDIR_HOST);
  2736. cli.set_follow_location(true);
  2737. auto res =
  2738. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2740. EXPECT_EQ(StatusCode::OK_200, res->status);
  2741. }
  2742. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2743. SSLClient cli(REDIR_HOST);
  2744. cli.set_follow_location(true);
  2745. Params params;
  2746. params.emplace("url", "http://example.com");
  2747. params.emplace("status_code", "302");
  2748. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2750. EXPECT_EQ(StatusCode::OK_200, res->status);
  2751. }
  2752. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2753. SSLClient cli(REDIR_HOST);
  2754. cli.set_follow_location(true);
  2755. Params params;
  2756. params.emplace("url", "http://example.com");
  2757. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2759. EXPECT_EQ(StatusCode::OK_200, res->status);
  2760. }
  2761. TEST(UrlWithSpace, Redirect_Online) {
  2762. SSLClient cli("edge.forgecdn.net");
  2763. cli.set_follow_location(true);
  2764. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2766. EXPECT_EQ(StatusCode::OK_200, res->status);
  2767. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2768. }
  2769. #endif
  2770. #if !defined(_WIN32) && !defined(_WIN64)
  2771. TEST(ReceiveSignals, Signal) {
  2772. auto setupSignalHandlers = []() {
  2773. struct sigaction act;
  2774. sigemptyset(&act.sa_mask);
  2775. act.sa_flags = SA_SIGINFO;
  2776. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2777. switch (sig) {
  2778. case SIGINT:
  2779. default: break;
  2780. }
  2781. };
  2782. ::sigaction(SIGINT, &act, nullptr);
  2783. };
  2784. Server svr;
  2785. int port = 0;
  2786. auto thread = std::thread([&]() {
  2787. setupSignalHandlers();
  2788. port = svr.bind_to_any_port(HOST);
  2789. svr.listen_after_bind();
  2790. });
  2791. auto se = detail::scope_exit([&] {
  2792. svr.stop();
  2793. thread.join();
  2794. ASSERT_FALSE(svr.is_running());
  2795. });
  2796. svr.wait_until_ready();
  2797. ASSERT_TRUE(svr.is_running());
  2798. pthread_kill(thread.native_handle(), SIGINT);
  2799. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2800. ASSERT_TRUE(svr.is_running());
  2801. }
  2802. #endif
  2803. TEST(RedirectToDifferentPort, Redirect) {
  2804. Server svr1;
  2805. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2806. res.set_content("Hello World!", "text/plain");
  2807. });
  2808. int svr1_port = 0;
  2809. auto thread1 = std::thread([&]() {
  2810. svr1_port = svr1.bind_to_any_port(HOST);
  2811. svr1.listen_after_bind();
  2812. });
  2813. Server svr2;
  2814. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2815. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2816. });
  2817. int svr2_port = 0;
  2818. auto thread2 = std::thread([&]() {
  2819. svr2_port = svr2.bind_to_any_port(HOST);
  2820. svr2.listen_after_bind();
  2821. });
  2822. auto se = detail::scope_exit([&] {
  2823. svr2.stop();
  2824. thread2.join();
  2825. svr1.stop();
  2826. thread1.join();
  2827. ASSERT_FALSE(svr2.is_running());
  2828. ASSERT_FALSE(svr1.is_running());
  2829. });
  2830. svr1.wait_until_ready();
  2831. svr2.wait_until_ready();
  2832. Client cli("localhost", svr2_port);
  2833. cli.set_follow_location(true);
  2834. auto res = cli.Get("/2");
  2835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2836. EXPECT_EQ(StatusCode::OK_200, res->status);
  2837. EXPECT_EQ("Hello World!", res->body);
  2838. }
  2839. static void
  2840. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2841. Server svr1;
  2842. std::string captured_authorization;
  2843. svr1.Get("/target", [&](const Request &req, Response &res) {
  2844. captured_authorization = req.get_header_value("Authorization");
  2845. res.set_content("OK", "text/plain");
  2846. });
  2847. int svr1_port = 0;
  2848. auto thread1 = std::thread([&]() {
  2849. svr1_port = svr1.bind_to_any_port(HOST);
  2850. svr1.listen_after_bind();
  2851. });
  2852. Server svr2;
  2853. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2854. res.set_redirect(
  2855. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2856. });
  2857. int svr2_port = 0;
  2858. auto thread2 = std::thread([&]() {
  2859. svr2_port = svr2.bind_to_any_port(HOST);
  2860. svr2.listen_after_bind();
  2861. });
  2862. auto se = detail::scope_exit([&] {
  2863. svr2.stop();
  2864. thread2.join();
  2865. svr1.stop();
  2866. thread1.join();
  2867. ASSERT_FALSE(svr2.is_running());
  2868. ASSERT_FALSE(svr1.is_running());
  2869. });
  2870. svr1.wait_until_ready();
  2871. svr2.wait_until_ready();
  2872. Client cli("localhost", svr2_port);
  2873. cli.set_follow_location(true);
  2874. set_auth(cli);
  2875. auto res = cli.Get("/redir");
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2879. EXPECT_TRUE(captured_authorization.empty());
  2880. }
  2881. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2882. TestDoNotForwardCredentialsOnRedirect(
  2883. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2884. }
  2885. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2886. TestDoNotForwardCredentialsOnRedirect(
  2887. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2888. }
  2889. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2890. Server svr1;
  2891. std::string captured_cookie;
  2892. bool target_hit = false;
  2893. svr1.Get("/target", [&](const Request &req, Response &res) {
  2894. captured_cookie = req.get_header_value("Cookie");
  2895. target_hit = true;
  2896. res.set_content("OK", "text/plain");
  2897. });
  2898. int svr1_port = 0;
  2899. auto thread1 = std::thread([&]() {
  2900. svr1_port = svr1.bind_to_any_port(HOST);
  2901. svr1.listen_after_bind();
  2902. });
  2903. Server svr2;
  2904. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2905. res.set_redirect(
  2906. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2907. });
  2908. int svr2_port = 0;
  2909. auto thread2 = std::thread([&]() {
  2910. svr2_port = svr2.bind_to_any_port(HOST);
  2911. svr2.listen_after_bind();
  2912. });
  2913. auto se = detail::scope_exit([&] {
  2914. svr2.stop();
  2915. thread2.join();
  2916. svr1.stop();
  2917. thread1.join();
  2918. ASSERT_FALSE(svr2.is_running());
  2919. ASSERT_FALSE(svr1.is_running());
  2920. });
  2921. svr1.wait_until_ready();
  2922. svr2.wait_until_ready();
  2923. Client cli("localhost", svr2_port);
  2924. cli.set_follow_location(true);
  2925. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2926. auto res = cli.Get("/redir", headers);
  2927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2928. EXPECT_EQ(StatusCode::OK_200, res->status);
  2929. EXPECT_TRUE(target_hit);
  2930. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2931. EXPECT_TRUE(captured_cookie.empty());
  2932. }
  2933. TEST(RedirectToSamePort, ForwardCookie) {
  2934. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2935. // header so that ordinary session flows keep working.
  2936. Server svr;
  2937. std::string captured_cookie;
  2938. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2939. res.set_redirect("/target", 302);
  2940. });
  2941. svr.Get("/target", [&](const Request &req, Response &res) {
  2942. captured_cookie = req.get_header_value("Cookie");
  2943. res.set_content("OK", "text/plain");
  2944. });
  2945. auto port = svr.bind_to_any_port(HOST);
  2946. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2947. auto se = detail::scope_exit([&] {
  2948. svr.stop();
  2949. thread.join();
  2950. ASSERT_FALSE(svr.is_running());
  2951. });
  2952. svr.wait_until_ready();
  2953. Client cli(HOST, port);
  2954. cli.set_follow_location(true);
  2955. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2956. auto res = cli.Get("/redir", headers);
  2957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2958. EXPECT_EQ(StatusCode::OK_200, res->status);
  2959. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2960. }
  2961. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2962. Server svr;
  2963. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2964. // Port number that overflows int — should not crash
  2965. res.set_redirect("http://localhost:99999999999999999999/target");
  2966. });
  2967. auto port = svr.bind_to_any_port(HOST);
  2968. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2969. auto se = detail::scope_exit([&] {
  2970. svr.stop();
  2971. thread.join();
  2972. ASSERT_FALSE(svr.is_running());
  2973. });
  2974. svr.wait_until_ready();
  2975. Client cli(HOST, port);
  2976. cli.set_follow_location(true);
  2977. auto res = cli.Get("/redir");
  2978. // Should fail gracefully, not crash (no valid response due to bad port)
  2979. EXPECT_FALSE(res);
  2980. }
  2981. TEST(RedirectFromPageWithContent, Redirect) {
  2982. Server svr;
  2983. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2984. res.set_content("___", "text/plain");
  2985. res.set_redirect("/2");
  2986. });
  2987. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2988. res.set_content("Hello World!", "text/plain");
  2989. });
  2990. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2991. auto se = detail::scope_exit([&] {
  2992. svr.stop();
  2993. th.join();
  2994. ASSERT_FALSE(svr.is_running());
  2995. });
  2996. svr.wait_until_ready();
  2997. {
  2998. Client cli("localhost", PORT);
  2999. cli.set_follow_location(true);
  3000. std::string body;
  3001. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3002. body.append(data, data_length);
  3003. return true;
  3004. });
  3005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3006. EXPECT_EQ(StatusCode::OK_200, res->status);
  3007. EXPECT_EQ("Hello World!", body);
  3008. }
  3009. {
  3010. Client cli("localhost", PORT);
  3011. std::string body;
  3012. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3013. body.append(data, data_length);
  3014. return true;
  3015. });
  3016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3017. EXPECT_EQ(StatusCode::Found_302, res->status);
  3018. EXPECT_EQ("___", body);
  3019. }
  3020. }
  3021. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3022. Server svr;
  3023. auto port_str = std::to_string(PORT);
  3024. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3025. auto expected_host = "[::1]:" + port_str;
  3026. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3027. res.set_content("___", "text/plain");
  3028. // res.set_redirect("/2");
  3029. res.set_redirect(redirect_url);
  3030. });
  3031. svr.Get("/2", [&](const Request &req, Response &res) {
  3032. auto host_header = req.headers.find("Host");
  3033. ASSERT_TRUE(host_header != req.headers.end());
  3034. EXPECT_EQ(expected_host, host_header->second);
  3035. res.set_content("Hello World!", "text/plain");
  3036. });
  3037. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3038. auto se = detail::scope_exit([&] {
  3039. svr.stop();
  3040. th.join();
  3041. ASSERT_FALSE(svr.is_running());
  3042. });
  3043. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3044. // actually starts anything, so the condition !svr.is_running() will
  3045. // always remain true, and the loop never stops.
  3046. // This basically counts how many milliseconds have passed since the
  3047. // call to svr.listen(), and if after 5 seconds nothing started yet
  3048. // aborts the test.
  3049. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3050. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3051. ASSERT_LT(milliseconds, 5000U);
  3052. }
  3053. {
  3054. Client cli("::1", PORT);
  3055. cli.set_follow_location(true);
  3056. std::string body;
  3057. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3058. body.append(data, data_length);
  3059. return true;
  3060. });
  3061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3062. EXPECT_EQ(StatusCode::OK_200, res->status);
  3063. EXPECT_EQ("Hello World!", body);
  3064. }
  3065. {
  3066. Client cli("::1", PORT);
  3067. std::string body;
  3068. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3069. body.append(data, data_length);
  3070. return true;
  3071. });
  3072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3073. EXPECT_EQ(StatusCode::Found_302, res->status);
  3074. EXPECT_EQ("___", body);
  3075. }
  3076. }
  3077. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3078. Server svr;
  3079. svr.Get("/foo", [](const Request &req, Response &res) {
  3080. auto a = req.params.find("a");
  3081. if (a != req.params.end()) {
  3082. res.set_content((*a).second, "text/plain");
  3083. res.status = StatusCode::OK_200;
  3084. } else {
  3085. res.status = StatusCode::BadRequest_400;
  3086. }
  3087. });
  3088. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3089. auto se = detail::scope_exit([&] {
  3090. svr.stop();
  3091. thread.join();
  3092. ASSERT_FALSE(svr.is_running());
  3093. });
  3094. svr.wait_until_ready();
  3095. {
  3096. Client cli(HOST, PORT);
  3097. cli.set_path_encode(false);
  3098. auto res = cli.Get("/foo?a=explicitly+encoded");
  3099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3100. EXPECT_EQ(StatusCode::OK_200, res->status);
  3101. // This expects it back with a space, as the `+` won't have been
  3102. // url-encoded, and server-side the params get decoded turning `+`
  3103. // into spaces.
  3104. EXPECT_EQ("explicitly encoded", res->body);
  3105. }
  3106. }
  3107. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3108. // When path encoding is disabled the client must transmit the supplied
  3109. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3110. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3111. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3112. // than a space (0x20). Assert on the raw wire target to catch this.
  3113. Server svr;
  3114. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3115. svr.Get("/foo", [&](const Request &req, Response &res) {
  3116. EXPECT_EQ(expected_target, req.target);
  3117. res.status = StatusCode::OK_200;
  3118. });
  3119. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3120. auto se = detail::scope_exit([&] {
  3121. svr.stop();
  3122. thread.join();
  3123. ASSERT_FALSE(svr.is_running());
  3124. });
  3125. svr.wait_until_ready();
  3126. {
  3127. Client cli(HOST, PORT);
  3128. cli.set_path_encode(false);
  3129. auto res = cli.Get(expected_target.c_str());
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. }
  3133. }
  3134. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3135. // `open_stream()` used to skip the path encoding that the buffered send
  3136. // path applies, so the same `path` produced different bytes in the request
  3137. // line depending on which API was used. Assert the two agree.
  3138. Server svr;
  3139. std::string target;
  3140. svr.Get(".*", [&](const Request &req, Response &res) {
  3141. target = req.target;
  3142. res.status = StatusCode::OK_200;
  3143. });
  3144. auto port = svr.bind_to_any_port(HOST);
  3145. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3146. auto se = detail::scope_exit([&] {
  3147. svr.stop();
  3148. thread.join();
  3149. ASSERT_FALSE(svr.is_running());
  3150. });
  3151. svr.wait_until_ready();
  3152. struct {
  3153. const char *path;
  3154. const char *expected;
  3155. } cases[] = {
  3156. {"/a b?x=1", "/a%20b?x=1"},
  3157. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3158. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3159. };
  3160. for (const auto &c : cases) {
  3161. Client cli(HOST, port);
  3162. target.clear();
  3163. auto res = cli.Get(c.path);
  3164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3165. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3166. auto buffered_target = target;
  3167. target.clear();
  3168. auto handle = cli.open_stream("GET", c.path);
  3169. EXPECT_TRUE(handle.is_valid())
  3170. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3171. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3172. }
  3173. }
  3174. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3175. // The `set_path_encode(false)` contract — transmit the supplied target
  3176. // verbatim — must hold for the streaming API too.
  3177. Server svr;
  3178. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3179. std::string target;
  3180. svr.Get("/foo", [&](const Request &req, Response &res) {
  3181. target = req.target;
  3182. res.status = StatusCode::OK_200;
  3183. });
  3184. auto port = svr.bind_to_any_port(HOST);
  3185. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3186. auto se = detail::scope_exit([&] {
  3187. svr.stop();
  3188. thread.join();
  3189. ASSERT_FALSE(svr.is_running());
  3190. });
  3191. svr.wait_until_ready();
  3192. {
  3193. Client cli(HOST, port);
  3194. cli.set_path_encode(false);
  3195. auto handle = cli.open_stream("GET", expected_target);
  3196. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3197. EXPECT_EQ(expected_target, target);
  3198. }
  3199. }
  3200. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3201. // With path encoding enabled a CR/LF in the target is percent-encoded
  3202. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3203. // write_request_line still backstops `set_path_encode(false)`, which is
  3204. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3205. Server svr;
  3206. // Captured before routing: the decoded path contains a newline, which a
  3207. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3208. std::string target;
  3209. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3210. target = req.target;
  3211. res.status = StatusCode::OK_200;
  3212. return Server::HandlerResponse::Handled;
  3213. });
  3214. auto port = svr.bind_to_any_port(HOST);
  3215. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3216. auto se = detail::scope_exit([&] {
  3217. svr.stop();
  3218. thread.join();
  3219. ASSERT_FALSE(svr.is_running());
  3220. });
  3221. svr.wait_until_ready();
  3222. {
  3223. Client cli(HOST, port);
  3224. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3225. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3226. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3227. }
  3228. }
  3229. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3230. // Nothing may reach the wire: a raw CR/LF target would split the request
  3231. // line and inject headers.
  3232. Server svr;
  3233. // Pre-routing so that "not called" means nothing reached the server at all,
  3234. // rather than merely failing to match a handler pattern.
  3235. auto handler_called = false;
  3236. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3237. handler_called = true;
  3238. res.status = StatusCode::OK_200;
  3239. return Server::HandlerResponse::Handled;
  3240. });
  3241. auto port = svr.bind_to_any_port(HOST);
  3242. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3243. auto se = detail::scope_exit([&] {
  3244. svr.stop();
  3245. thread.join();
  3246. ASSERT_FALSE(svr.is_running());
  3247. });
  3248. svr.wait_until_ready();
  3249. {
  3250. Client cli(HOST, port);
  3251. cli.set_path_encode(false);
  3252. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3253. EXPECT_FALSE(handle.is_valid());
  3254. EXPECT_EQ(Error::Write, handle.error);
  3255. EXPECT_FALSE(handler_called);
  3256. }
  3257. }
  3258. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3259. // Which of the two branches runs is decided by whether the query component
  3260. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3261. // an empty query and must still fall back to building one from
  3262. // `req.params`, while a non-empty query must win over `req.params`.
  3263. Server svr;
  3264. std::string target;
  3265. svr.Get("/foo", [&](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. {
  3278. // Trailing `?` -> empty query component -> `req.params` is used.
  3279. Client cli(HOST, port);
  3280. Request req;
  3281. req.method = "GET";
  3282. req.path = "/foo?";
  3283. req.params.emplace("a", "1");
  3284. target.clear();
  3285. auto res = cli.send(req);
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ("/foo?a=1", target);
  3288. }
  3289. {
  3290. // Non-empty query in `req.path` -> `req.params` is not appended.
  3291. Client cli(HOST, port);
  3292. Request req;
  3293. req.method = "GET";
  3294. req.path = "/foo?b=2";
  3295. req.params.emplace("a", "1");
  3296. target.clear();
  3297. auto res = cli.send(req);
  3298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3299. EXPECT_EQ("/foo?b=2", target);
  3300. }
  3301. }
  3302. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3303. Server svr;
  3304. svr.Get("/", [](const Request &req, Response &) {
  3305. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3306. });
  3307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3308. auto se = detail::scope_exit([&] {
  3309. svr.stop();
  3310. thread.join();
  3311. ASSERT_FALSE(svr.is_running());
  3312. });
  3313. svr.wait_until_ready();
  3314. {
  3315. Client cli(HOST, PORT);
  3316. cli.set_path_encode(false);
  3317. auto res = cli.Get("/?something=%0A");
  3318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3319. EXPECT_EQ(StatusCode::OK_200, res->status);
  3320. }
  3321. }
  3322. TEST(BindServerTest, BindDualStack) {
  3323. Server svr;
  3324. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3325. res.set_content("Hello World!", "text/plain");
  3326. });
  3327. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3328. auto se = detail::scope_exit([&] {
  3329. svr.stop();
  3330. thread.join();
  3331. ASSERT_FALSE(svr.is_running());
  3332. });
  3333. svr.wait_until_ready();
  3334. {
  3335. Client cli("127.0.0.1", PORT);
  3336. auto res = cli.Get("/1");
  3337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3338. EXPECT_EQ(StatusCode::OK_200, res->status);
  3339. EXPECT_EQ("Hello World!", res->body);
  3340. }
  3341. {
  3342. Client cli("::1", PORT);
  3343. auto res = cli.Get("/1");
  3344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3345. EXPECT_EQ(StatusCode::OK_200, res->status);
  3346. EXPECT_EQ("Hello World!", res->body);
  3347. }
  3348. }
  3349. TEST(BindServerTest, BindAndListenSeparately) {
  3350. Server svr;
  3351. int port = svr.bind_to_any_port("0.0.0.0");
  3352. ASSERT_TRUE(svr.is_valid());
  3353. ASSERT_TRUE(port > 0);
  3354. svr.stop();
  3355. }
  3356. // Reports whether anything is still listening on a loopback port. A plain
  3357. // connect() is used instead of a Client request because a socket left bound by
  3358. // mistake accepts the connection into its backlog and never answers, which
  3359. // would hang the test instead of failing it.
  3360. static bool is_loopback_port_accepting(int port) {
  3361. sockaddr_in addr{};
  3362. addr.sin_family = AF_INET;
  3363. addr.sin_port = htons(static_cast<uint16_t>(port));
  3364. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3365. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3366. EXPECT_NE(sock, INVALID_SOCKET);
  3367. if (sock == INVALID_SOCKET) { return false; }
  3368. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3369. static_cast<socklen_t>(sizeof(addr)));
  3370. detail::close_socket(sock);
  3371. return ret == 0;
  3372. }
  3373. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3374. Server svr;
  3375. auto port = svr.bind_to_any_port("127.0.0.1");
  3376. ASSERT_TRUE(port > 0);
  3377. svr.stop();
  3378. // bind_to_any_port() already called listen(2), so until stop() closed the
  3379. // descriptor the port kept accepting connections into the backlog. ASSERT
  3380. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3381. // below blocks forever in the accept loop.
  3382. ASSERT_FALSE(is_loopback_port_accepting(port));
  3383. // Nothing is left to accept on, so listen_after_bind() must report failure
  3384. // instead of returning success without ever serving.
  3385. EXPECT_FALSE(svr.listen_after_bind());
  3386. // The failed listen marks the server decommissioned, so a waiter returns
  3387. // instead of spinning forever.
  3388. svr.wait_until_ready();
  3389. }
  3390. #ifdef CPPHTTPLIB_SSL_ENABLED
  3391. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3392. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3393. CLIENT_CA_CERT_DIR);
  3394. int port = svr.bind_to_any_port("0.0.0.0");
  3395. ASSERT_TRUE(svr.is_valid());
  3396. ASSERT_TRUE(port > 0);
  3397. svr.stop();
  3398. }
  3399. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3400. // or a rejected CustomRoute() registration would not stop the server binding.
  3401. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3403. CLIENT_CA_CERT_DIR);
  3404. ASSERT_TRUE(svr.is_valid());
  3405. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3406. EXPECT_FALSE(svr.is_valid());
  3407. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3408. }
  3409. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3410. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3411. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3412. int port = svr.bind_to_any_port("0.0.0.0");
  3413. ASSERT_TRUE(svr.is_valid());
  3414. ASSERT_TRUE(port > 0);
  3415. svr.stop();
  3416. }
  3417. TEST(BindServerTest, UpdateCertsPem) {
  3418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3419. int port = svr.bind_to_any_port("0.0.0.0");
  3420. ASSERT_TRUE(svr.is_valid());
  3421. ASSERT_TRUE(port > 0);
  3422. // Read PEM files
  3423. std::string cert_pem, key_pem, ca_pem;
  3424. read_file(SERVER_CERT_FILE, cert_pem);
  3425. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3426. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3427. // Update server certificates using PEM API
  3428. ASSERT_TRUE(
  3429. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3430. ASSERT_TRUE(svr.is_valid());
  3431. svr.stop();
  3432. }
  3433. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3434. // Start server with client CA (enables client auth)
  3435. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3436. ASSERT_TRUE(svr.is_valid());
  3437. bool handler_called = false;
  3438. svr.Get("/test", [&](const Request &req, Response &res) {
  3439. handler_called = true;
  3440. // Verify client certificate is present
  3441. auto cert = req.peer_cert();
  3442. EXPECT_TRUE(static_cast<bool>(cert));
  3443. res.set_content("ok", "text/plain");
  3444. });
  3445. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3446. auto se = detail::scope_exit([&] {
  3447. svr.stop();
  3448. t.join();
  3449. ASSERT_FALSE(svr.is_running());
  3450. });
  3451. svr.wait_until_ready();
  3452. // Read PEM files
  3453. std::string cert_pem, key_pem, ca_pem;
  3454. read_file(SERVER_CERT_FILE, cert_pem);
  3455. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3456. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3457. // Update server certificates and client CA using PEM API while server running
  3458. ASSERT_TRUE(
  3459. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3460. // Connect with client certificate
  3461. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3462. cli.enable_server_certificate_verification(false);
  3463. cli.set_connection_timeout(30);
  3464. auto res = cli.Get("/test");
  3465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3466. ASSERT_EQ(StatusCode::OK_200, res->status);
  3467. ASSERT_TRUE(handler_called);
  3468. EXPECT_EQ("ok", res->body);
  3469. }
  3470. #endif
  3471. TEST(ErrorHandlerTest, ContentLength) {
  3472. Server svr;
  3473. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3474. res.status = StatusCode::OK_200;
  3475. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3476. "text/html"); // <= Content-Length still 13
  3477. });
  3478. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3479. res.set_content("Hello World!\n", "text/plain");
  3480. res.status = 524;
  3481. });
  3482. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3483. auto se = detail::scope_exit([&] {
  3484. svr.stop();
  3485. thread.join();
  3486. ASSERT_FALSE(svr.is_running());
  3487. });
  3488. svr.wait_until_ready();
  3489. {
  3490. Client cli(HOST, PORT);
  3491. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3493. EXPECT_EQ(StatusCode::OK_200, res->status);
  3494. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3495. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3496. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3497. }
  3498. }
  3499. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3500. TEST(ExceptionTest, WithoutExceptionHandler) {
  3501. Server svr;
  3502. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3503. throw std::runtime_error("exception...");
  3504. });
  3505. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3506. throw std::runtime_error("exception\r\n...");
  3507. });
  3508. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3509. auto se = detail::scope_exit([&] {
  3510. svr.stop();
  3511. listen_thread.join();
  3512. ASSERT_FALSE(svr.is_running());
  3513. });
  3514. svr.wait_until_ready();
  3515. Client cli("localhost", PORT);
  3516. {
  3517. auto res = cli.Get("/exception");
  3518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3519. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3520. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3521. }
  3522. {
  3523. auto res = cli.Get("/unknown");
  3524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3525. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3526. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3527. }
  3528. }
  3529. TEST(ExceptionTest, WithExceptionHandler) {
  3530. Server svr;
  3531. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3532. std::exception_ptr ep) {
  3533. EXPECT_FALSE(ep == nullptr);
  3534. try {
  3535. std::rethrow_exception(ep);
  3536. } catch (std::exception &e) {
  3537. EXPECT_EQ("abc", std::string(e.what()));
  3538. } catch (...) {}
  3539. res.status = StatusCode::InternalServerError_500;
  3540. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3541. "text/html"); // <= Content-Length still 13 at this point
  3542. });
  3543. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3544. res.set_content("Hello World!\n", "text/plain");
  3545. throw std::runtime_error("abc");
  3546. });
  3547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3548. auto se = detail::scope_exit([&] {
  3549. svr.stop();
  3550. thread.join();
  3551. ASSERT_FALSE(svr.is_running());
  3552. });
  3553. svr.wait_until_ready();
  3554. for (size_t i = 0; i < 10; i++) {
  3555. Client cli(HOST, PORT);
  3556. for (size_t j = 0; j < 100; j++) {
  3557. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3559. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3560. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3561. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3562. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3563. }
  3564. cli.set_keep_alive(true);
  3565. for (size_t j = 0; j < 100; j++) {
  3566. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3568. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3569. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3570. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3571. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3572. }
  3573. }
  3574. }
  3575. TEST(ExceptionTest, AndErrorHandler) {
  3576. Server svr;
  3577. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3578. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3579. });
  3580. svr.set_exception_handler(
  3581. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3582. EXPECT_FALSE(ep == nullptr);
  3583. try {
  3584. std::rethrow_exception(ep);
  3585. } catch (std::exception &e) {
  3586. res.set_content(e.what(), "text/html");
  3587. } catch (...) {}
  3588. res.status = StatusCode::InternalServerError_500;
  3589. });
  3590. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3591. throw std::runtime_error("EXCEPTION");
  3592. });
  3593. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3594. res.set_content("ERROR", "text/html");
  3595. res.status = StatusCode::InternalServerError_500;
  3596. });
  3597. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3598. auto se = detail::scope_exit([&] {
  3599. svr.stop();
  3600. thread.join();
  3601. ASSERT_FALSE(svr.is_running());
  3602. });
  3603. svr.wait_until_ready();
  3604. Client cli(HOST, PORT);
  3605. {
  3606. auto res = cli.Get("/exception");
  3607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3608. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3609. EXPECT_EQ("EXCEPTION", res->body);
  3610. }
  3611. {
  3612. auto res = cli.Get("/error");
  3613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3614. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3615. EXPECT_EQ("ERROR", res->body);
  3616. }
  3617. {
  3618. auto res = cli.Get("/invalid");
  3619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3620. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3621. EXPECT_EQ("NOT_FOUND", res->body);
  3622. }
  3623. }
  3624. #endif
  3625. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3626. // process_request() wraps only routing() in a try/catch, so an exception from
  3627. // any other user callback used to unwind into the task queue - which does not
  3628. // catch - and terminate the process. Each test below runs the server on a
  3629. // single worker thread: a guard that catches the exception but still loses the
  3630. // thread would otherwise be hidden by a spare worker serving the follow-up
  3631. // request. Note that a regression here aborts the whole test binary rather
  3632. // than failing one test.
  3633. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3634. Server svr;
  3635. svr.new_task_queue = [] { return new ThreadPool(1); };
  3636. std::atomic<int> reported{0};
  3637. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3638. if (err == Error::UserCallbackException) { reported++; }
  3639. });
  3640. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3641. res.set_content_provider(
  3642. 1024, "text/plain",
  3643. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3644. sink.write("hello", 5);
  3645. throw std::runtime_error("from the content provider");
  3646. });
  3647. });
  3648. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3649. res.set_content("ok", "text/plain");
  3650. });
  3651. auto port = svr.bind_to_any_port(HOST);
  3652. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3653. auto se = detail::scope_exit([&] {
  3654. svr.stop();
  3655. listen_thread.join();
  3656. ASSERT_FALSE(svr.is_running());
  3657. });
  3658. svr.wait_until_ready();
  3659. {
  3660. Client cli(HOST, port);
  3661. cli.set_read_timeout(5, 0);
  3662. EXPECT_FALSE(cli.Get("/throw"));
  3663. }
  3664. EXPECT_TRUE(svr.is_running());
  3665. EXPECT_EQ(1, reported.load());
  3666. // A request on a fresh connection is still served.
  3667. {
  3668. Client cli(HOST, port);
  3669. auto res = cli.Get("/ok");
  3670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3671. EXPECT_EQ(StatusCode::OK_200, res->status);
  3672. EXPECT_EQ("ok", res->body);
  3673. }
  3674. }
  3675. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3676. Server svr;
  3677. svr.new_task_queue = [] { return new ThreadPool(1); };
  3678. std::atomic<bool> should_throw{true};
  3679. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3680. res.set_content("hi", "text/plain");
  3681. });
  3682. svr.set_post_routing_handler(
  3683. [&](const Request & /*req*/, Response & /*res*/) {
  3684. if (should_throw) {
  3685. throw std::runtime_error("from the post-routing handler");
  3686. }
  3687. });
  3688. auto port = svr.bind_to_any_port(HOST);
  3689. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3690. auto se = detail::scope_exit([&] {
  3691. svr.stop();
  3692. listen_thread.join();
  3693. ASSERT_FALSE(svr.is_running());
  3694. });
  3695. svr.wait_until_ready();
  3696. {
  3697. Client cli(HOST, port);
  3698. cli.set_read_timeout(5, 0);
  3699. EXPECT_FALSE(cli.Get("/hi"));
  3700. }
  3701. EXPECT_TRUE(svr.is_running());
  3702. should_throw = false;
  3703. {
  3704. Client cli(HOST, port);
  3705. auto res = cli.Get("/hi");
  3706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3707. EXPECT_EQ(StatusCode::OK_200, res->status);
  3708. EXPECT_EQ("hi", res->body);
  3709. }
  3710. }
  3711. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3712. // The guard reports the caught exception through the error logger, which is
  3713. // a user callback too. A logger that throws has to be contained as well, or
  3714. // the process would terminate from inside the catch.
  3715. Server svr;
  3716. svr.new_task_queue = [] { return new ThreadPool(1); };
  3717. std::atomic<int> reported{0};
  3718. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3719. if (err == Error::UserCallbackException) {
  3720. reported++;
  3721. throw std::runtime_error("from the error logger");
  3722. }
  3723. });
  3724. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3725. res.set_content_provider(
  3726. 1024, "text/plain",
  3727. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3728. sink.write("hello", 5);
  3729. throw std::runtime_error("from the content provider");
  3730. });
  3731. });
  3732. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3733. res.set_content("ok", "text/plain");
  3734. });
  3735. auto port = svr.bind_to_any_port(HOST);
  3736. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3737. auto se = detail::scope_exit([&] {
  3738. svr.stop();
  3739. listen_thread.join();
  3740. ASSERT_FALSE(svr.is_running());
  3741. });
  3742. svr.wait_until_ready();
  3743. {
  3744. Client cli(HOST, port);
  3745. cli.set_read_timeout(5, 0);
  3746. EXPECT_FALSE(cli.Get("/throw"));
  3747. }
  3748. EXPECT_TRUE(svr.is_running());
  3749. EXPECT_EQ(1, reported.load());
  3750. {
  3751. Client cli(HOST, port);
  3752. auto res = cli.Get("/ok");
  3753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3754. EXPECT_EQ(StatusCode::OK_200, res->status);
  3755. EXPECT_EQ("ok", res->body);
  3756. }
  3757. }
  3758. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3759. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3760. // so the exception unwinds through the ws::WebSocket object on its way to
  3761. // the guard. None of the HTTP cases above cross that.
  3762. Server svr;
  3763. svr.new_task_queue = [] { return new ThreadPool(1); };
  3764. std::atomic<int> reported{0};
  3765. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3766. if (err == Error::UserCallbackException) { reported++; }
  3767. });
  3768. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3769. throw std::runtime_error("from the WebSocket handler");
  3770. });
  3771. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3772. res.set_content("ok", "text/plain");
  3773. });
  3774. auto port = svr.bind_to_any_port(HOST);
  3775. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3776. auto se = detail::scope_exit([&] {
  3777. svr.stop();
  3778. listen_thread.join();
  3779. ASSERT_FALSE(svr.is_running());
  3780. });
  3781. svr.wait_until_ready();
  3782. {
  3783. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3784. "/ws");
  3785. auto res = client.connect();
  3786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3787. // The server dropped the connection instead of dying.
  3788. std::string msg;
  3789. EXPECT_FALSE(client.read(msg));
  3790. client.close();
  3791. }
  3792. EXPECT_TRUE(svr.is_running());
  3793. EXPECT_EQ(1, reported.load());
  3794. {
  3795. Client cli(HOST, port);
  3796. auto res = cli.Get("/ok");
  3797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3798. EXPECT_EQ(StatusCode::OK_200, res->status);
  3799. EXPECT_EQ("ok", res->body);
  3800. }
  3801. }
  3802. #ifdef CPPHTTPLIB_SSL_ENABLED
  3803. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3804. // SSLServer::process_and_close_socket() is a separate overload with its own
  3805. // guard, so it is exercised on its own.
  3806. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3807. ASSERT_TRUE(svr.is_valid());
  3808. svr.new_task_queue = [] { return new ThreadPool(1); };
  3809. std::atomic<int> reported{0};
  3810. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3811. if (err == Error::UserCallbackException) { reported++; }
  3812. });
  3813. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3814. res.set_content_provider(
  3815. 1024, "text/plain",
  3816. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3817. sink.write("hello", 5);
  3818. throw std::runtime_error("from the content provider");
  3819. });
  3820. });
  3821. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3822. res.set_content("ok", "text/plain");
  3823. });
  3824. auto port = svr.bind_to_any_port(HOST);
  3825. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3826. auto se = detail::scope_exit([&] {
  3827. svr.stop();
  3828. listen_thread.join();
  3829. ASSERT_FALSE(svr.is_running());
  3830. });
  3831. svr.wait_until_ready();
  3832. {
  3833. SSLClient cli(HOST, port);
  3834. cli.enable_server_certificate_verification(false);
  3835. cli.set_read_timeout(5, 0);
  3836. EXPECT_FALSE(cli.Get("/throw"));
  3837. }
  3838. EXPECT_TRUE(svr.is_running());
  3839. EXPECT_EQ(1, reported.load());
  3840. {
  3841. SSLClient cli(HOST, port);
  3842. cli.enable_server_certificate_verification(false);
  3843. auto res = cli.Get("/ok");
  3844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3845. EXPECT_EQ(StatusCode::OK_200, res->status);
  3846. EXPECT_EQ("ok", res->body);
  3847. }
  3848. }
  3849. #endif
  3850. #endif
  3851. TEST(NoContentTest, ContentLength) {
  3852. Server svr;
  3853. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3854. res.status = StatusCode::NoContent_204;
  3855. });
  3856. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3857. auto se = detail::scope_exit([&] {
  3858. svr.stop();
  3859. thread.join();
  3860. ASSERT_FALSE(svr.is_running());
  3861. });
  3862. svr.wait_until_ready();
  3863. {
  3864. Client cli(HOST, PORT);
  3865. auto res = cli.Get("/hi");
  3866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3867. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3868. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3869. }
  3870. }
  3871. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3872. #ifdef CPPHTTPLIB_SSL_ENABLED
  3873. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3874. ASSERT_TRUE(svr.is_valid());
  3875. #else
  3876. Server svr;
  3877. #endif
  3878. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3879. if (req.path == "/routing_handler") {
  3880. res.set_header("PRE_ROUTING", "on");
  3881. res.set_content("Routing Handler", "text/plain");
  3882. return httplib::Server::HandlerResponse::Handled;
  3883. }
  3884. return httplib::Server::HandlerResponse::Unhandled;
  3885. });
  3886. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3887. res.set_content("Error", "text/html");
  3888. });
  3889. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3890. if (req.path == "/routing_handler") {
  3891. res.set_header("POST_ROUTING", "on");
  3892. }
  3893. });
  3894. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3895. res.set_content("Hello World!\n", "text/plain");
  3896. });
  3897. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3898. auto se = detail::scope_exit([&] {
  3899. svr.stop();
  3900. thread.join();
  3901. ASSERT_FALSE(svr.is_running());
  3902. });
  3903. svr.wait_until_ready();
  3904. {
  3905. #ifdef CPPHTTPLIB_SSL_ENABLED
  3906. SSLClient cli(HOST, PORT);
  3907. cli.enable_server_certificate_verification(false);
  3908. #else
  3909. Client cli(HOST, PORT);
  3910. #endif
  3911. auto res = cli.Get("/routing_handler");
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. EXPECT_EQ("Routing Handler", res->body);
  3915. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3916. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3917. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3918. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3919. }
  3920. {
  3921. #ifdef CPPHTTPLIB_SSL_ENABLED
  3922. SSLClient cli(HOST, PORT);
  3923. cli.enable_server_certificate_verification(false);
  3924. #else
  3925. Client cli(HOST, PORT);
  3926. #endif
  3927. auto res = cli.Get("/hi");
  3928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3929. EXPECT_EQ(StatusCode::OK_200, res->status);
  3930. EXPECT_EQ("Hello World!\n", res->body);
  3931. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3932. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3933. }
  3934. {
  3935. #ifdef CPPHTTPLIB_SSL_ENABLED
  3936. SSLClient cli(HOST, PORT);
  3937. cli.enable_server_certificate_verification(false);
  3938. #else
  3939. Client cli(HOST, PORT);
  3940. #endif
  3941. auto res = cli.Get("/aaa");
  3942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3943. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3944. EXPECT_EQ("Error", res->body);
  3945. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3946. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3947. }
  3948. }
  3949. TEST(RequestHandlerTest, PreRequestHandler) {
  3950. auto route_path = "/user/:user";
  3951. Server svr;
  3952. svr.Get("/hi", [](const Request &, Response &res) {
  3953. res.set_content("hi", "text/plain");
  3954. });
  3955. svr.Get(route_path, [](const Request &req, Response &res) {
  3956. res.set_content(req.path_params.at("user"), "text/plain");
  3957. });
  3958. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3959. if (req.matched_route == route_path) {
  3960. auto user = req.path_params.at("user");
  3961. if (user != "john") {
  3962. res.status = StatusCode::Forbidden_403;
  3963. res.set_content("error", "text/html");
  3964. return Server::HandlerResponse::Handled;
  3965. }
  3966. }
  3967. return Server::HandlerResponse::Unhandled;
  3968. });
  3969. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3970. auto se = detail::scope_exit([&] {
  3971. svr.stop();
  3972. thread.join();
  3973. ASSERT_FALSE(svr.is_running());
  3974. });
  3975. svr.wait_until_ready();
  3976. Client cli(HOST, PORT);
  3977. {
  3978. auto res = cli.Get("/hi");
  3979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3980. EXPECT_EQ(StatusCode::OK_200, res->status);
  3981. EXPECT_EQ("hi", res->body);
  3982. }
  3983. {
  3984. auto res = cli.Get("/user/john");
  3985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3986. EXPECT_EQ(StatusCode::OK_200, res->status);
  3987. EXPECT_EQ("john", res->body);
  3988. }
  3989. {
  3990. auto res = cli.Get("/user/invalid-user");
  3991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3992. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3993. EXPECT_EQ("error", res->body);
  3994. }
  3995. }
  3996. // The pre-request handler must run before the request body is read, so a
  3997. // rejected request never forces the server to buffer a (potentially large)
  3998. // body. Here the posted body is larger than the payload limit: if the body
  3999. // were read first the server would answer 413, but because the pre-request
  4000. // handler runs first it answers 403 and the body is never read.
  4001. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4002. Server svr;
  4003. svr.set_payload_max_length(8);
  4004. auto handler_ran = false;
  4005. svr.Post("/reject", [&](const Request &req, Response &res) {
  4006. handler_ran = true;
  4007. res.set_content(req.body, "text/plain");
  4008. });
  4009. svr.Post("/accept", [](const Request &req, Response &res) {
  4010. res.set_content(req.body, "text/plain");
  4011. });
  4012. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4013. if (req.matched_route == "/reject") {
  4014. res.status = StatusCode::Forbidden_403;
  4015. res.set_content("denied", "text/plain");
  4016. return Server::HandlerResponse::Handled;
  4017. }
  4018. return Server::HandlerResponse::Unhandled;
  4019. });
  4020. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4021. auto se = detail::scope_exit([&] {
  4022. svr.stop();
  4023. thread.join();
  4024. ASSERT_FALSE(svr.is_running());
  4025. });
  4026. svr.wait_until_ready();
  4027. Client cli(HOST, PORT);
  4028. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4029. // rejects with 403 before the body is read, so 413 is never reached.
  4030. {
  4031. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4033. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4034. EXPECT_EQ("denied", res->body);
  4035. EXPECT_FALSE(handler_ran);
  4036. }
  4037. // An approved route still reads the body and enforces the payload limit.
  4038. {
  4039. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4041. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4042. }
  4043. }
  4044. TEST(UserDataTest, BasicOperations) {
  4045. httplib::UserData ud;
  4046. // Initially empty
  4047. EXPECT_FALSE(ud.has("key"));
  4048. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4049. // set and get
  4050. ud.set("key", 42);
  4051. EXPECT_TRUE(ud.has("key"));
  4052. auto *p = ud.get<int>("key");
  4053. ASSERT_NE(nullptr, p);
  4054. EXPECT_EQ(42, *p);
  4055. // Type mismatch → nullptr
  4056. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4057. // Overwrite with different type
  4058. ud.set("key", std::string("hello"));
  4059. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4060. auto *s = ud.get<std::string>("key");
  4061. ASSERT_NE(nullptr, s);
  4062. EXPECT_EQ("hello", *s);
  4063. // erase
  4064. ud.erase("key");
  4065. EXPECT_FALSE(ud.has("key"));
  4066. // clear
  4067. ud.set("a", 1);
  4068. ud.set("b", 2);
  4069. ud.clear();
  4070. EXPECT_FALSE(ud.has("a"));
  4071. EXPECT_FALSE(ud.has("b"));
  4072. }
  4073. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4074. struct AuthCtx {
  4075. std::string user_id;
  4076. };
  4077. Server svr;
  4078. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4079. res.user_data.set("auth", AuthCtx{"alice"});
  4080. return Server::HandlerResponse::Unhandled;
  4081. });
  4082. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4083. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4084. ASSERT_NE(nullptr, ctx);
  4085. res.set_content("Hello " + ctx->user_id, "text/plain");
  4086. });
  4087. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4088. auto se = detail::scope_exit([&] {
  4089. svr.stop();
  4090. thread.join();
  4091. ASSERT_FALSE(svr.is_running());
  4092. });
  4093. svr.wait_until_ready();
  4094. Client cli(HOST, PORT);
  4095. auto res = cli.Get("/me");
  4096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4097. EXPECT_EQ(StatusCode::OK_200, res->status);
  4098. EXPECT_EQ("Hello alice", res->body);
  4099. }
  4100. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4101. struct RoleCtx {
  4102. std::string role;
  4103. };
  4104. Server svr;
  4105. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4106. res.user_data.set("role", RoleCtx{"admin"});
  4107. return Server::HandlerResponse::Unhandled;
  4108. });
  4109. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4110. auto *ctx = res.user_data.get<RoleCtx>("role");
  4111. ASSERT_NE(nullptr, ctx);
  4112. res.set_content(ctx->role, "text/plain");
  4113. });
  4114. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4115. auto se = detail::scope_exit([&] {
  4116. svr.stop();
  4117. thread.join();
  4118. ASSERT_FALSE(svr.is_running());
  4119. });
  4120. svr.wait_until_ready();
  4121. Client cli(HOST, PORT);
  4122. auto res = cli.Get("/role");
  4123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4124. EXPECT_EQ(StatusCode::OK_200, res->status);
  4125. EXPECT_EQ("admin", res->body);
  4126. }
  4127. TEST(InvalidFormatTest, StatusCode) {
  4128. Server svr;
  4129. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4130. res.set_content("Hello World!\n", "text/plain");
  4131. res.status = 9999; // Status should be a three-digit code...
  4132. });
  4133. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4134. auto se = detail::scope_exit([&] {
  4135. svr.stop();
  4136. thread.join();
  4137. ASSERT_FALSE(svr.is_running());
  4138. });
  4139. svr.wait_until_ready();
  4140. {
  4141. Client cli(HOST, PORT);
  4142. auto res = cli.Get("/hi");
  4143. ASSERT_FALSE(res);
  4144. }
  4145. }
  4146. TEST(URLFragmentTest, WithFragment) {
  4147. Server svr;
  4148. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4149. EXPECT_TRUE(req.target == "/hi");
  4150. });
  4151. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4152. auto se = detail::scope_exit([&] {
  4153. svr.stop();
  4154. thread.join();
  4155. ASSERT_FALSE(svr.is_running());
  4156. });
  4157. svr.wait_until_ready();
  4158. {
  4159. Client cli(HOST, PORT);
  4160. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4161. EXPECT_TRUE(res);
  4162. EXPECT_EQ(StatusCode::OK_200, res->status);
  4163. res = cli.Get("/hi%23key1=val1=key2=val2");
  4164. EXPECT_TRUE(res);
  4165. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4166. }
  4167. }
  4168. TEST(HeaderWriter, SetHeaderWriter) {
  4169. Server svr;
  4170. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4171. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4172. return detail::write_headers(strm, hdrs);
  4173. });
  4174. svr.Get("/hi", [](const Request &req, Response &res) {
  4175. auto it = req.headers.find("CustomClientHeader");
  4176. EXPECT_TRUE(it != req.headers.end());
  4177. EXPECT_EQ(it->second, "CustomClientValue");
  4178. res.set_content("Hello World!\n", "text/plain");
  4179. });
  4180. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4181. auto se = detail::scope_exit([&] {
  4182. svr.stop();
  4183. thread.join();
  4184. ASSERT_FALSE(svr.is_running());
  4185. });
  4186. svr.wait_until_ready();
  4187. {
  4188. Client cli(HOST, PORT);
  4189. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4190. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4191. return detail::write_headers(strm, hdrs);
  4192. });
  4193. auto res = cli.Get("/hi");
  4194. EXPECT_TRUE(res);
  4195. EXPECT_EQ(StatusCode::OK_200, res->status);
  4196. auto it = res->headers.find("CustomServerHeader");
  4197. EXPECT_TRUE(it != res->headers.end());
  4198. EXPECT_EQ(it->second, "CustomServerValue");
  4199. }
  4200. }
  4201. class ServerTest : public ::testing::Test {
  4202. protected:
  4203. ServerTest()
  4204. : cli_(HOST, PORT)
  4205. #ifdef CPPHTTPLIB_SSL_ENABLED
  4206. ,
  4207. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4208. #endif
  4209. {
  4210. #ifdef CPPHTTPLIB_SSL_ENABLED
  4211. cli_.enable_server_certificate_verification(false);
  4212. #endif
  4213. // Allow LARGE_DATA (100MB) responses
  4214. cli_.set_payload_max_length(200 * 1024 * 1024);
  4215. }
  4216. virtual void SetUp() {
  4217. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4218. svr_.set_payload_max_length(200 * 1024 * 1024);
  4219. svr_.set_mount_point("/", "./www");
  4220. svr_.set_mount_point("/mount", "./www2");
  4221. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4222. svr_.Get("/hi",
  4223. [&](const Request & /*req*/, Response &res) {
  4224. res.set_content("Hello World!", "text/plain");
  4225. })
  4226. .Get("/file_content",
  4227. [&](const Request & /*req*/, Response &res) {
  4228. res.set_file_content("./www/dir/test.html");
  4229. })
  4230. .Get("/file_content_with_content_type",
  4231. [&](const Request & /*req*/, Response &res) {
  4232. res.set_file_content("./www/file", "text/plain");
  4233. })
  4234. .Get("/invalid_file_content",
  4235. [&](const Request & /*req*/, Response &res) {
  4236. res.set_file_content("./www/dir/invalid_file_path");
  4237. })
  4238. .Get("/http_response_splitting",
  4239. [&](const Request & /*req*/, Response &res) {
  4240. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4241. EXPECT_EQ(0U, res.headers.size());
  4242. EXPECT_FALSE(res.has_header("a"));
  4243. res.set_header("a", "1\nSet-Cookie: a=1");
  4244. EXPECT_EQ(0U, res.headers.size());
  4245. EXPECT_FALSE(res.has_header("a"));
  4246. res.set_header("a", "1\rSet-Cookie: a=1");
  4247. EXPECT_EQ(0U, res.headers.size());
  4248. EXPECT_FALSE(res.has_header("a"));
  4249. res.set_header("a\r\nb", "0");
  4250. EXPECT_EQ(0U, res.headers.size());
  4251. EXPECT_FALSE(res.has_header("a"));
  4252. res.set_header("a\rb", "0");
  4253. EXPECT_EQ(0U, res.headers.size());
  4254. EXPECT_FALSE(res.has_header("a"));
  4255. res.set_header("a\nb", "0");
  4256. EXPECT_EQ(0U, res.headers.size());
  4257. EXPECT_FALSE(res.has_header("a"));
  4258. res.set_redirect("1\r\nSet-Cookie: a=1");
  4259. EXPECT_EQ(0U, res.headers.size());
  4260. EXPECT_FALSE(res.has_header("Location"));
  4261. })
  4262. .Get("/slow",
  4263. [&](const Request & /*req*/, Response &res) {
  4264. std::this_thread::sleep_for(std::chrono::seconds(4));
  4265. res.set_content("slow", "text/plain");
  4266. })
  4267. #if 0
  4268. .Post("/slowpost",
  4269. [&](const Request & /*req*/, Response &res) {
  4270. std::this_thread::sleep_for(std::chrono::seconds(2));
  4271. res.set_content("slow", "text/plain");
  4272. })
  4273. #endif
  4274. .Get("/remote_addr",
  4275. [&](const Request &req, Response &res) {
  4276. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4277. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4278. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4279. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4280. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4281. #endif
  4282. res.set_content(req.remote_addr, "text/plain");
  4283. })
  4284. .Get("/local_addr",
  4285. [&](const Request &req, Response &res) {
  4286. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4287. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4288. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4289. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4290. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4291. #endif
  4292. auto local_addr = req.local_addr;
  4293. auto local_port = std::to_string(req.local_port);
  4294. res.set_content(local_addr.append(":").append(local_port),
  4295. "text/plain");
  4296. })
  4297. .Get("/endwith%",
  4298. [&](const Request & /*req*/, Response &res) {
  4299. res.set_content("Hello World!", "text/plain");
  4300. })
  4301. .Get("/a\\+\\+b",
  4302. [&](const Request &req, Response &res) {
  4303. ASSERT_TRUE(req.has_param("a +b"));
  4304. auto val = req.get_param_value("a +b");
  4305. res.set_content(val, "text/plain");
  4306. })
  4307. .Get("/", [&](const Request & /*req*/,
  4308. Response &res) { res.set_redirect("/hi"); })
  4309. .Post("/1",
  4310. [](const Request & /*req*/, Response &res) {
  4311. res.set_redirect("/2", StatusCode::SeeOther_303);
  4312. })
  4313. .Get("/2",
  4314. [](const Request & /*req*/, Response &res) {
  4315. res.set_content("redirected.", "text/plain");
  4316. res.status = StatusCode::OK_200;
  4317. })
  4318. .Post("/person",
  4319. [&](const Request &req, Response &res) {
  4320. if (req.has_param("name") && req.has_param("note")) {
  4321. persons_[req.get_param_value("name")] =
  4322. req.get_param_value("note");
  4323. } else {
  4324. res.status = StatusCode::BadRequest_400;
  4325. }
  4326. })
  4327. .Put("/person",
  4328. [&](const Request &req, Response &res) {
  4329. if (req.has_param("name") && req.has_param("note")) {
  4330. persons_[req.get_param_value("name")] =
  4331. req.get_param_value("note");
  4332. } else {
  4333. res.status = StatusCode::BadRequest_400;
  4334. }
  4335. })
  4336. .Get("/person/(.*)",
  4337. [&](const Request &req, Response &res) {
  4338. string name = req.matches[1];
  4339. if (persons_.find(name) != persons_.end()) {
  4340. auto note = persons_[name];
  4341. res.set_content(note, "text/plain");
  4342. } else {
  4343. res.status = StatusCode::NotFound_404;
  4344. }
  4345. })
  4346. .Delete("/person",
  4347. [&](const Request &req, Response &res) {
  4348. if (req.has_param("name")) {
  4349. string name = req.get_param_value("name");
  4350. if (persons_.find(name) != persons_.end()) {
  4351. persons_.erase(name);
  4352. res.set_content("DELETED", "text/plain");
  4353. } else {
  4354. res.status = StatusCode::NotFound_404;
  4355. }
  4356. } else {
  4357. res.status = StatusCode::BadRequest_400;
  4358. }
  4359. })
  4360. .Post("/x-www-form-urlencoded-json",
  4361. [&](const Request &req, Response &res) {
  4362. auto json = req.get_param_value("json");
  4363. ASSERT_EQ(JSON_DATA, json);
  4364. res.set_content(json, "appliation/json");
  4365. res.status = StatusCode::OK_200;
  4366. })
  4367. .Get("/streamed-chunked",
  4368. [&](const Request & /*req*/, Response &res) {
  4369. res.set_chunked_content_provider(
  4370. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4371. sink.os << "123";
  4372. sink.os << "456";
  4373. sink.os << "789";
  4374. sink.done();
  4375. return true;
  4376. });
  4377. })
  4378. .Get("/streamed-chunked-with-prohibited-trailer",
  4379. [&](const Request & /*req*/, Response &res) {
  4380. auto i = new int(0);
  4381. // Declare both a prohibited trailer (Content-Length) and an
  4382. // allowed one
  4383. res.set_header("Trailer", "Content-Length, X-Allowed");
  4384. res.set_chunked_content_provider(
  4385. "text/plain",
  4386. [i](size_t /*offset*/, DataSink &sink) {
  4387. switch (*i) {
  4388. case 0: sink.os << "123"; break;
  4389. case 1: sink.os << "456"; break;
  4390. case 2: sink.os << "789"; break;
  4391. case 3: {
  4392. sink.done_with_trailer(
  4393. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4394. } break;
  4395. }
  4396. (*i)++;
  4397. return true;
  4398. },
  4399. [i](bool success) {
  4400. EXPECT_TRUE(success);
  4401. delete i;
  4402. });
  4403. })
  4404. .Get("/streamed-chunked2",
  4405. [&](const Request & /*req*/, Response &res) {
  4406. auto i = new int(0);
  4407. res.set_chunked_content_provider(
  4408. "text/plain",
  4409. [i](size_t /*offset*/, DataSink &sink) {
  4410. switch (*i) {
  4411. case 0: sink.os << "123"; break;
  4412. case 1: sink.os << "456"; break;
  4413. case 2: sink.os << "789"; break;
  4414. case 3: sink.done(); break;
  4415. }
  4416. (*i)++;
  4417. return true;
  4418. },
  4419. [i](bool success) {
  4420. EXPECT_TRUE(success);
  4421. delete i;
  4422. });
  4423. })
  4424. .Get("/streamed-chunked-with-trailer",
  4425. [&](const Request & /*req*/, Response &res) {
  4426. auto i = new int(0);
  4427. res.set_header("Trailer", "Dummy1, Dummy2");
  4428. res.set_chunked_content_provider(
  4429. "text/plain",
  4430. [i](size_t /*offset*/, DataSink &sink) {
  4431. switch (*i) {
  4432. case 0: sink.os << "123"; break;
  4433. case 1: sink.os << "456"; break;
  4434. case 2: sink.os << "789"; break;
  4435. case 3: {
  4436. sink.done_with_trailer(
  4437. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4438. } break;
  4439. }
  4440. (*i)++;
  4441. return true;
  4442. },
  4443. [i](bool success) {
  4444. EXPECT_TRUE(success);
  4445. delete i;
  4446. });
  4447. })
  4448. .Get("/streamed",
  4449. [&](const Request & /*req*/, Response &res) {
  4450. res.set_content_provider(
  4451. 6, "text/plain",
  4452. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4453. sink.os << (offset < 3 ? "a" : "b");
  4454. return true;
  4455. });
  4456. })
  4457. .Get("/streamed-without-length",
  4458. [&](const Request & /*req*/, Response &res) {
  4459. auto data = new std::string("abcdefg");
  4460. res.set_content_provider(
  4461. "text/plain",
  4462. [data](size_t offset, DataSink &sink) {
  4463. if (offset < data->size()) {
  4464. sink.os << data->substr(offset);
  4465. }
  4466. sink.done();
  4467. return true;
  4468. },
  4469. [data](bool success) {
  4470. EXPECT_TRUE(success);
  4471. delete data;
  4472. });
  4473. })
  4474. .Get("/streamed-with-range",
  4475. [&](const Request &req, Response &res) {
  4476. auto data = new std::string("abcdefg");
  4477. // An explicit status keeps the server from picking the 206 it
  4478. // would otherwise choose for a ranged request, so the response
  4479. // is not a partial representation.
  4480. auto status = req.get_param_value("status");
  4481. if (status == "200") {
  4482. res.status = StatusCode::OK_200;
  4483. } else if (status == "403") {
  4484. res.status = StatusCode::Forbidden_403;
  4485. }
  4486. res.set_content_provider(
  4487. data->size(), "text/plain",
  4488. [data](size_t offset, size_t length, DataSink &sink) {
  4489. size_t DATA_CHUNK_SIZE = 4;
  4490. const auto &d = *data;
  4491. auto out_len =
  4492. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4493. auto ret =
  4494. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4495. EXPECT_TRUE(ret);
  4496. return true;
  4497. },
  4498. [data, &req](bool success) {
  4499. EXPECT_EQ(success, !req.has_param("error"));
  4500. delete data;
  4501. });
  4502. })
  4503. .Get("/streamed-cancel",
  4504. [&](const Request & /*req*/, Response &res) {
  4505. res.set_content_provider(
  4506. size_t(-1), "text/plain",
  4507. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4508. sink.os << "data_chunk";
  4509. return true;
  4510. });
  4511. })
  4512. .Get("/regex-with-delimiter",
  4513. [&](const Request &req, Response & /*res*/) {
  4514. ASSERT_TRUE(req.has_param("key"));
  4515. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4516. })
  4517. .Get("/with-range",
  4518. [&](const Request & /*req*/, Response &res) {
  4519. res.set_content("abcdefg", "text/plain");
  4520. })
  4521. .Get("/test-start-time",
  4522. [&](const Request &req, Response & /*res*/) {
  4523. EXPECT_NE(req.start_time_,
  4524. std::chrono::steady_clock::time_point::min());
  4525. })
  4526. .Get("/with-range-customized-response",
  4527. [&](const Request & /*req*/, Response &res) {
  4528. res.status = StatusCode::BadRequest_400;
  4529. res.set_content(JSON_DATA, "application/json");
  4530. })
  4531. .Post("/chunked",
  4532. [&](const Request &req, Response & /*res*/) {
  4533. EXPECT_EQ(req.body, "dechunked post body");
  4534. })
  4535. .Post("/large-chunked",
  4536. [&](const Request &req, Response & /*res*/) {
  4537. std::string expected(6 * 30 * 1024u, 'a');
  4538. EXPECT_EQ(req.body, expected);
  4539. })
  4540. .Post("/multipart",
  4541. [&](const Request &req, Response & /*res*/) {
  4542. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4543. req.form.get_field_count("text2") +
  4544. req.form.get_field_count("file3") +
  4545. req.form.get_field_count("file4"));
  4546. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4547. req.form.get_file_count("file2"));
  4548. ASSERT_TRUE(!req.form.has_file("???"));
  4549. ASSERT_TRUE(!req.form.has_field("???"));
  4550. ASSERT_TRUE(req.body.empty());
  4551. {
  4552. const auto &text = req.form.get_field("text1");
  4553. EXPECT_EQ("text default", text);
  4554. }
  4555. {
  4556. const auto &text = req.form.get_field("text2");
  4557. EXPECT_EQ("aωb", text);
  4558. }
  4559. {
  4560. const auto &file = req.form.get_file("file1");
  4561. EXPECT_EQ("hello.txt", file.filename);
  4562. EXPECT_EQ("text/plain", file.content_type);
  4563. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4564. }
  4565. {
  4566. const auto &file = req.form.get_file("file2");
  4567. EXPECT_EQ("world.json", file.filename);
  4568. EXPECT_EQ("application/json", file.content_type);
  4569. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4570. }
  4571. {
  4572. const auto &text = req.form.get_field("file3");
  4573. EXPECT_EQ(0u, text.size());
  4574. }
  4575. {
  4576. const auto &text = req.form.get_field("file4");
  4577. EXPECT_EQ(0u, text.size());
  4578. }
  4579. })
  4580. .Post("/multipart/multi_file_values",
  4581. [&](const Request &req, Response & /*res*/) {
  4582. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4583. req.form.get_field_count("multi_text1"));
  4584. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4585. ASSERT_TRUE(!req.form.has_file("???"));
  4586. ASSERT_TRUE(!req.form.has_field("???"));
  4587. ASSERT_TRUE(req.body.empty());
  4588. {
  4589. const auto &text = req.form.get_field("text");
  4590. EXPECT_EQ("default text", text);
  4591. }
  4592. {
  4593. const auto &text1_values = req.form.get_fields("multi_text1");
  4594. EXPECT_EQ(2u, text1_values.size());
  4595. EXPECT_EQ("aaaaa", text1_values[0]);
  4596. EXPECT_EQ("bbbbb", text1_values[1]);
  4597. }
  4598. {
  4599. const auto &file1_values = req.form.get_files("multi_file1");
  4600. EXPECT_EQ(2u, file1_values.size());
  4601. auto file1 = file1_values[0];
  4602. EXPECT_EQ(file1.filename, "hello.txt");
  4603. EXPECT_EQ(file1.content_type, "text/plain");
  4604. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4605. auto file2 = file1_values[1];
  4606. EXPECT_EQ(file2.filename, "world.json");
  4607. EXPECT_EQ(file2.content_type, "application/json");
  4608. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4609. }
  4610. })
  4611. .Post("/empty",
  4612. [&](const Request &req, Response &res) {
  4613. EXPECT_EQ(req.body, "");
  4614. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4615. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4616. res.set_content("empty", "text/plain");
  4617. })
  4618. .Post("/empty-no-content-type",
  4619. [&](const Request &req, Response &res) {
  4620. EXPECT_EQ(req.body, "");
  4621. EXPECT_FALSE(req.has_header("Content-Type"));
  4622. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4623. res.set_content("empty-no-content-type", "text/plain");
  4624. })
  4625. .Post("/path-only",
  4626. [&](const Request &req, Response &res) {
  4627. EXPECT_EQ(req.body, "");
  4628. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4629. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4630. res.set_content("path-only", "text/plain");
  4631. })
  4632. .Post("/path-headers-only",
  4633. [&](const Request &req, Response &res) {
  4634. EXPECT_EQ(req.body, "");
  4635. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4636. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4637. EXPECT_EQ("world", req.get_header_value("hello"));
  4638. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4639. res.set_content("path-headers-only", "text/plain");
  4640. })
  4641. .Post("/post-large",
  4642. [&](const Request &req, Response &res) {
  4643. EXPECT_EQ(req.body, LARGE_DATA);
  4644. res.set_content(req.body, "text/plain");
  4645. })
  4646. .Post("/post-loopback",
  4647. [&](const Request &, Response &res,
  4648. ContentReader const &content_reader) {
  4649. std::string body;
  4650. content_reader([&](const char *data, size_t data_length) {
  4651. body.append(data, data_length);
  4652. return true;
  4653. });
  4654. res.set_content(body, "text/plain");
  4655. })
  4656. .Put("/put-loopback",
  4657. [&](const Request &, Response &res,
  4658. ContentReader const &content_reader) {
  4659. std::string body;
  4660. content_reader([&](const char *data, size_t data_length) {
  4661. body.append(data, data_length);
  4662. return true;
  4663. });
  4664. res.set_content(body, "text/plain");
  4665. })
  4666. .Patch("/patch-loopback",
  4667. [&](const Request &, Response &res,
  4668. ContentReader const &content_reader) {
  4669. std::string body;
  4670. content_reader([&](const char *data, size_t data_length) {
  4671. body.append(data, data_length);
  4672. return true;
  4673. });
  4674. res.set_content(body, "text/plain");
  4675. })
  4676. .Put("/empty-no-content-type",
  4677. [&](const Request &req, Response &res) {
  4678. EXPECT_EQ(req.body, "");
  4679. EXPECT_FALSE(req.has_header("Content-Type"));
  4680. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4681. res.set_content("empty-no-content-type", "text/plain");
  4682. })
  4683. .Put("/put",
  4684. [&](const Request &req, Response &res) {
  4685. EXPECT_EQ(req.body, "PUT");
  4686. res.set_content(req.body, "text/plain");
  4687. })
  4688. .Put("/put-large",
  4689. [&](const Request &req, Response &res) {
  4690. EXPECT_EQ(req.body, LARGE_DATA);
  4691. res.set_content(req.body, "text/plain");
  4692. })
  4693. .Patch("/patch",
  4694. [&](const Request &req, Response &res) {
  4695. EXPECT_EQ(req.body, "PATCH");
  4696. res.set_content(req.body, "text/plain");
  4697. })
  4698. .Delete("/delete",
  4699. [&](const Request & /*req*/, Response &res) {
  4700. res.set_content("DELETE", "text/plain");
  4701. })
  4702. .Delete("/delete-body",
  4703. [&](const Request &req, Response &res) {
  4704. EXPECT_EQ(req.body, "content");
  4705. res.set_content(req.body, "text/plain");
  4706. })
  4707. .Options(R"(\*)",
  4708. [&](const Request & /*req*/, Response &res) {
  4709. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4710. })
  4711. .CustomRoute("PROPFIND", "/dav/:id",
  4712. [&](const Request &req, Response &res) {
  4713. res.set_header("x-body-size",
  4714. std::to_string(req.body.size()));
  4715. res.set_header("x-matched-route", req.matched_route);
  4716. res.set_header("x-dav-id", req.path_params.at("id"));
  4717. res.status = StatusCode::MultiStatus_207;
  4718. res.set_content(req.body, "application/xml");
  4719. })
  4720. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4721. [&](const Request &req, Response &res) {
  4722. res.set_header("x-dav-match", req.matches[1]);
  4723. res.status = StatusCode::MultiStatus_207;
  4724. })
  4725. .CustomRoute("MKCOL", "/dav-mkcol",
  4726. [&](const Request &req, Response &res) {
  4727. EXPECT_TRUE(req.body.empty());
  4728. res.status = StatusCode::Created_201;
  4729. })
  4730. .CustomRoute(
  4731. "REPORT", "/dav-report",
  4732. [&](const Request & /*req*/, Response &res,
  4733. const ContentReader &content_reader) {
  4734. std::string body;
  4735. content_reader([&](const char *data, size_t data_length) {
  4736. body.append(data, data_length);
  4737. return true;
  4738. });
  4739. res.set_header("x-body-size", std::to_string(body.size()));
  4740. res.status = StatusCode::MultiStatus_207;
  4741. res.set_content(body, "application/xml");
  4742. })
  4743. .Get("/request-target",
  4744. [&](const Request &req, Response & /*res*/) {
  4745. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4746. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4747. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4748. })
  4749. .Get("/long-query-value",
  4750. [&](const Request &req, Response & /*res*/) {
  4751. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4752. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4753. })
  4754. .Get("/too-long-query-value",
  4755. [&](const Request &req, Response & /*res*/) {
  4756. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4757. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4758. })
  4759. .Get("/array-param",
  4760. [&](const Request &req, Response & /*res*/) {
  4761. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4762. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4763. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4764. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4765. })
  4766. .Get("/array-param-values",
  4767. [&](const Request &req, Response & /*res*/) {
  4768. auto values = req.get_param_values("array");
  4769. EXPECT_EQ(3u, values.size());
  4770. EXPECT_EQ("value1", values[0]);
  4771. EXPECT_EQ("value2", values[1]);
  4772. EXPECT_EQ("value3", values[2]);
  4773. auto empty = req.get_param_values("nonexistent");
  4774. EXPECT_TRUE(empty.empty());
  4775. })
  4776. .Post("/validate-no-multiple-headers",
  4777. [&](const Request &req, Response & /*res*/) {
  4778. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4779. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4780. })
  4781. .Post("/content_receiver",
  4782. [&](const Request &req, Response &res,
  4783. const ContentReader &content_reader) {
  4784. if (req.is_multipart_form_data()) {
  4785. std::vector<FormData> items;
  4786. content_reader(
  4787. [&](const FormData &file) {
  4788. items.push_back(file);
  4789. return true;
  4790. },
  4791. [&](const char *data, size_t data_length) {
  4792. items.back().content.append(data, data_length);
  4793. return true;
  4794. });
  4795. EXPECT_EQ(5u, items.size());
  4796. {
  4797. const auto &file = get_file_value(items, "text1");
  4798. EXPECT_TRUE(file.filename.empty());
  4799. EXPECT_EQ("text default", file.content);
  4800. }
  4801. {
  4802. const auto &file = get_file_value(items, "text2");
  4803. EXPECT_TRUE(file.filename.empty());
  4804. EXPECT_EQ("aωb", file.content);
  4805. }
  4806. {
  4807. const auto &file = get_file_value(items, "file1");
  4808. EXPECT_EQ("hello.txt", file.filename);
  4809. EXPECT_EQ("text/plain", file.content_type);
  4810. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4811. }
  4812. {
  4813. const auto &file = get_file_value(items, "file2");
  4814. EXPECT_EQ("world.json", file.filename);
  4815. EXPECT_EQ("application/json", file.content_type);
  4816. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4817. }
  4818. {
  4819. const auto &file = get_file_value(items, "file3");
  4820. EXPECT_TRUE(file.filename.empty());
  4821. EXPECT_EQ("application/octet-stream", file.content_type);
  4822. EXPECT_EQ(0u, file.content.size());
  4823. }
  4824. } else {
  4825. std::string body;
  4826. content_reader([&](const char *data, size_t data_length) {
  4827. EXPECT_EQ(7U, data_length);
  4828. body.append(data, data_length);
  4829. return true;
  4830. });
  4831. EXPECT_EQ(body, "content");
  4832. res.set_content(body, "text/plain");
  4833. }
  4834. })
  4835. .Put("/content_receiver",
  4836. [&](const Request & /*req*/, Response &res,
  4837. const ContentReader &content_reader) {
  4838. std::string body;
  4839. content_reader([&](const char *data, size_t data_length) {
  4840. body.append(data, data_length);
  4841. return true;
  4842. });
  4843. EXPECT_EQ(body, "content");
  4844. res.set_content(body, "text/plain");
  4845. })
  4846. .Patch("/content_receiver",
  4847. [&](const Request & /*req*/, Response &res,
  4848. const ContentReader &content_reader) {
  4849. std::string body;
  4850. content_reader([&](const char *data, size_t data_length) {
  4851. body.append(data, data_length);
  4852. return true;
  4853. });
  4854. EXPECT_EQ(body, "content");
  4855. res.set_content(body, "text/plain");
  4856. })
  4857. .Post("/query-string-and-body",
  4858. [&](const Request &req, Response & /*res*/) {
  4859. ASSERT_TRUE(req.has_param("key"));
  4860. EXPECT_EQ(req.get_param_value("key"), "value");
  4861. EXPECT_EQ(req.body, "content");
  4862. })
  4863. .Get("/last-request",
  4864. [&](const Request &req, Response & /*res*/) {
  4865. EXPECT_EQ("close", req.get_header_value("Connection"));
  4866. })
  4867. .Get(R"(/redirect/(\d+))",
  4868. [&](const Request &req, Response &res) {
  4869. auto num = std::stoi(req.matches[1]) + 1;
  4870. std::string url = "/redirect/" + std::to_string(num);
  4871. res.set_redirect(url);
  4872. })
  4873. .Post("/binary",
  4874. [&](const Request &req, Response &res) {
  4875. EXPECT_EQ(4U, req.body.size());
  4876. EXPECT_EQ("application/octet-stream",
  4877. req.get_header_value("Content-Type"));
  4878. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4879. res.set_content(req.body, "application/octet-stream");
  4880. })
  4881. .Put("/binary",
  4882. [&](const Request &req, Response &res) {
  4883. EXPECT_EQ(4U, req.body.size());
  4884. EXPECT_EQ("application/octet-stream",
  4885. req.get_header_value("Content-Type"));
  4886. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4887. res.set_content(req.body, "application/octet-stream");
  4888. })
  4889. .Patch("/binary",
  4890. [&](const Request &req, Response &res) {
  4891. EXPECT_EQ(4U, req.body.size());
  4892. EXPECT_EQ("application/octet-stream",
  4893. req.get_header_value("Content-Type"));
  4894. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4895. res.set_content(req.body, "application/octet-stream");
  4896. })
  4897. .Delete("/binary",
  4898. [&](const Request &req, Response &res) {
  4899. EXPECT_EQ(4U, req.body.size());
  4900. EXPECT_EQ("application/octet-stream",
  4901. req.get_header_value("Content-Type"));
  4902. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4903. res.set_content(req.body, "application/octet-stream");
  4904. })
  4905. .Get("/issue1772",
  4906. [&](const Request & /*req*/, Response &res) {
  4907. res.status = 401;
  4908. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4909. })
  4910. .Delete("/issue609",
  4911. [](const httplib::Request &, httplib::Response &res,
  4912. const httplib::ContentReader &) {
  4913. res.set_content("ok", "text/plain");
  4914. })
  4915. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4916. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4917. .Get("/compress",
  4918. [&](const Request & /*req*/, Response &res) {
  4919. res.set_content(
  4920. "12345678901234567890123456789012345678901234567890123456789"
  4921. "01234567890123456789012345678901234567890",
  4922. "text/plain");
  4923. })
  4924. .Get("/compress-with-charset",
  4925. [&](const Request & /*req*/, Response &res) {
  4926. res.set_content(
  4927. "12345678901234567890123456789012345678901234567890123456789"
  4928. "01234567890123456789012345678901234567890",
  4929. "application/json; charset=utf-8");
  4930. })
  4931. .Get("/nocompress",
  4932. [&](const Request & /*req*/, Response &res) {
  4933. res.set_content(
  4934. "12345678901234567890123456789012345678901234567890123456789"
  4935. "01234567890123456789012345678901234567890",
  4936. "application/octet-stream");
  4937. })
  4938. .Post("/compress-multipart",
  4939. [&](const Request &req, Response & /*res*/) {
  4940. EXPECT_EQ(2u, req.form.fields.size());
  4941. ASSERT_TRUE(!req.form.has_field("???"));
  4942. {
  4943. const auto &text = req.form.get_field("key1");
  4944. EXPECT_EQ("test", text);
  4945. }
  4946. {
  4947. const auto &text = req.form.get_field("key2");
  4948. EXPECT_EQ("--abcdefg123", text);
  4949. }
  4950. })
  4951. #endif
  4952. ;
  4953. persons_["john"] = "programmer";
  4954. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4955. svr_.wait_until_ready();
  4956. }
  4957. virtual void TearDown() {
  4958. svr_.stop();
  4959. if (!request_threads_.empty()) {
  4960. std::this_thread::sleep_for(std::chrono::seconds(1));
  4961. for (auto &t : request_threads_) {
  4962. t.join();
  4963. }
  4964. }
  4965. t_.join();
  4966. }
  4967. map<string, string> persons_;
  4968. #ifdef CPPHTTPLIB_SSL_ENABLED
  4969. SSLClient cli_;
  4970. SSLServer svr_;
  4971. #else
  4972. Client cli_;
  4973. Server svr_;
  4974. #endif
  4975. thread t_;
  4976. std::vector<thread> request_threads_;
  4977. };
  4978. TEST_F(ServerTest, GetMethod200) {
  4979. auto res = cli_.Get("/hi");
  4980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4981. EXPECT_EQ("HTTP/1.1", res->version);
  4982. EXPECT_EQ(StatusCode::OK_200, res->status);
  4983. EXPECT_EQ("OK", res->reason);
  4984. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4985. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4986. EXPECT_EQ("Hello World!", res->body);
  4987. }
  4988. TEST_F(ServerTest, GetEmptyFile) {
  4989. auto res = cli_.Get("/empty_file");
  4990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4991. EXPECT_EQ(StatusCode::OK_200, res->status);
  4992. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4993. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4994. EXPECT_EQ("", res->body);
  4995. }
  4996. TEST_F(ServerTest, GetFileContent) {
  4997. auto res = cli_.Get("/file_content");
  4998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4999. EXPECT_EQ(StatusCode::OK_200, res->status);
  5000. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5001. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5002. EXPECT_EQ("test.html", res->body);
  5003. }
  5004. TEST_F(ServerTest, GetFileContentWithRange) {
  5005. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5007. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5008. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5009. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5010. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5011. EXPECT_EQ("est", res->body);
  5012. }
  5013. TEST_F(ServerTest, GetFileContentWithContentType) {
  5014. auto res = cli_.Get("/file_content_with_content_type");
  5015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5016. EXPECT_EQ(StatusCode::OK_200, res->status);
  5017. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5018. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5019. EXPECT_EQ("file\n", res->body);
  5020. }
  5021. TEST_F(ServerTest, GetInvalidFileContent) {
  5022. auto res = cli_.Get("/invalid_file_content");
  5023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5024. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5025. }
  5026. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5027. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5029. EXPECT_EQ("HTTP/1.1", res->version);
  5030. EXPECT_EQ(StatusCode::OK_200, res->status);
  5031. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5032. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5033. EXPECT_EQ("Hello World!", res->body);
  5034. }
  5035. TEST_F(ServerTest, GetMethod302) {
  5036. auto res = cli_.Get("/");
  5037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5038. EXPECT_EQ(StatusCode::Found_302, res->status);
  5039. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5040. }
  5041. TEST_F(ServerTest, GetMethod302Redirect) {
  5042. cli_.set_follow_location(true);
  5043. auto res = cli_.Get("/");
  5044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5045. EXPECT_EQ(StatusCode::OK_200, res->status);
  5046. EXPECT_EQ("Hello World!", res->body);
  5047. EXPECT_EQ("/hi", res->location);
  5048. }
  5049. TEST_F(ServerTest, GetMethod404) {
  5050. auto res = cli_.Get("/invalid");
  5051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5052. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5053. }
  5054. TEST_F(ServerTest, HeadMethod200) {
  5055. auto res = cli_.Head("/hi");
  5056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5057. EXPECT_EQ(StatusCode::OK_200, res->status);
  5058. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5059. EXPECT_TRUE(res->body.empty());
  5060. }
  5061. TEST_F(ServerTest, HeadMethod200Static) {
  5062. auto res = cli_.Head("/mount/dir/index.html");
  5063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5064. EXPECT_EQ(StatusCode::OK_200, res->status);
  5065. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5066. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5067. EXPECT_TRUE(res->body.empty());
  5068. }
  5069. TEST_F(ServerTest, HeadMethod404) {
  5070. auto res = cli_.Head("/invalid");
  5071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5072. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5073. EXPECT_TRUE(res->body.empty());
  5074. }
  5075. TEST_F(ServerTest, GetMethodPersonJohn) {
  5076. auto res = cli_.Get("/person/john");
  5077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5078. EXPECT_EQ(StatusCode::OK_200, res->status);
  5079. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5080. EXPECT_EQ("programmer", res->body);
  5081. }
  5082. TEST_F(ServerTest, PostMethod1) {
  5083. auto res = cli_.Get("/person/john1");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5086. res = cli_.Post("/person", "name=john1&note=coder",
  5087. "application/x-www-form-urlencoded");
  5088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5089. ASSERT_EQ(StatusCode::OK_200, res->status);
  5090. res = cli_.Get("/person/john1");
  5091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5092. ASSERT_EQ(StatusCode::OK_200, res->status);
  5093. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5094. ASSERT_EQ("coder", res->body);
  5095. }
  5096. TEST_F(ServerTest, PostMethod2) {
  5097. auto res = cli_.Get("/person/john2");
  5098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5099. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5100. Params params;
  5101. params.emplace("name", "john2");
  5102. params.emplace("note", "coder");
  5103. res = cli_.Post("/person", params);
  5104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5105. ASSERT_EQ(StatusCode::OK_200, res->status);
  5106. res = cli_.Get("/person/john2");
  5107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5108. ASSERT_EQ(StatusCode::OK_200, res->status);
  5109. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5110. ASSERT_EQ("coder", res->body);
  5111. }
  5112. TEST_F(ServerTest, PutMethod3) {
  5113. auto res = cli_.Get("/person/john3");
  5114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5115. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5116. Params params;
  5117. params.emplace("name", "john3");
  5118. params.emplace("note", "coder");
  5119. res = cli_.Put("/person", params);
  5120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5121. ASSERT_EQ(StatusCode::OK_200, res->status);
  5122. res = cli_.Get("/person/john3");
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. ASSERT_EQ(StatusCode::OK_200, res->status);
  5125. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5126. ASSERT_EQ("coder", res->body);
  5127. }
  5128. TEST_F(ServerTest, DeleteMethod1) {
  5129. auto res = cli_.Get("/person/john4");
  5130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5131. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5132. Params params;
  5133. params.emplace("name", "john4");
  5134. params.emplace("note", "coder");
  5135. res = cli_.Post("/person", params);
  5136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5137. ASSERT_EQ(StatusCode::OK_200, res->status);
  5138. res = cli_.Get("/person/john4");
  5139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5140. ASSERT_EQ(StatusCode::OK_200, res->status);
  5141. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5142. ASSERT_EQ("coder", res->body);
  5143. Params delete_params;
  5144. delete_params.emplace("name", "john4");
  5145. res = cli_.Delete("/person", delete_params);
  5146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5147. ASSERT_EQ(StatusCode::OK_200, res->status);
  5148. ASSERT_EQ("DELETED", res->body);
  5149. res = cli_.Get("/person/john4");
  5150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5151. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5152. }
  5153. TEST_F(ServerTest, DeleteMethod2) {
  5154. auto res = cli_.Get("/person/john5");
  5155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5156. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5157. Params params;
  5158. params.emplace("name", "john5");
  5159. params.emplace("note", "developer");
  5160. res = cli_.Post("/person", params);
  5161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5162. ASSERT_EQ(StatusCode::OK_200, res->status);
  5163. res = cli_.Get("/person/john5");
  5164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5165. ASSERT_EQ(StatusCode::OK_200, res->status);
  5166. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5167. ASSERT_EQ("developer", res->body);
  5168. Params delete_params;
  5169. delete_params.emplace("name", "john5");
  5170. Headers headers;
  5171. headers.emplace("Custom-Header", "test-value");
  5172. res = cli_.Delete("/person", headers, delete_params);
  5173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5174. ASSERT_EQ(StatusCode::OK_200, res->status);
  5175. ASSERT_EQ("DELETED", res->body);
  5176. res = cli_.Get("/person/john5");
  5177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5178. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5179. }
  5180. TEST_F(ServerTest, DeleteMethod3) {
  5181. auto res = cli_.Get("/person/john6");
  5182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5183. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5184. Params params;
  5185. params.emplace("name", "john6");
  5186. params.emplace("note", "tester");
  5187. res = cli_.Post("/person", params);
  5188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5189. ASSERT_EQ(StatusCode::OK_200, res->status);
  5190. res = cli_.Get("/person/john6");
  5191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5192. ASSERT_EQ(StatusCode::OK_200, res->status);
  5193. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5194. ASSERT_EQ("tester", res->body);
  5195. Params delete_params;
  5196. delete_params.emplace("name", "john6");
  5197. Headers headers;
  5198. headers.emplace("Custom-Header", "test-value");
  5199. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5201. ASSERT_EQ(StatusCode::OK_200, res->status);
  5202. ASSERT_EQ("DELETED", res->body);
  5203. res = cli_.Get("/person/john6");
  5204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5205. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5206. }
  5207. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5208. Params params;
  5209. params.emplace("json", JSON_DATA);
  5210. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. ASSERT_EQ(StatusCode::OK_200, res->status);
  5213. ASSERT_EQ(JSON_DATA, res->body);
  5214. }
  5215. TEST_F(ServerTest, PostEmptyContent) {
  5216. auto res = cli_.Post("/empty", "", "text/plain");
  5217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5218. ASSERT_EQ(StatusCode::OK_200, res->status);
  5219. ASSERT_EQ("empty", res->body);
  5220. }
  5221. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5222. auto res = cli_.Post("/empty-no-content-type");
  5223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5224. ASSERT_EQ(StatusCode::OK_200, res->status);
  5225. ASSERT_EQ("empty-no-content-type", res->body);
  5226. }
  5227. TEST_F(ServerTest, PostPathOnly) {
  5228. auto res = cli_.Post("/path-only");
  5229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5230. ASSERT_EQ(StatusCode::OK_200, res->status);
  5231. ASSERT_EQ("path-only", res->body);
  5232. }
  5233. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5234. auto res = cli_.Post("/path-headers-only",
  5235. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5237. ASSERT_EQ(StatusCode::OK_200, res->status);
  5238. ASSERT_EQ("path-headers-only", res->body);
  5239. }
  5240. TEST_F(ServerTest, PostLarge) {
  5241. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5243. ASSERT_EQ(StatusCode::OK_200, res->status);
  5244. EXPECT_EQ(LARGE_DATA, res->body);
  5245. }
  5246. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5247. auto res = cli_.Put("/empty-no-content-type");
  5248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5249. ASSERT_EQ(StatusCode::OK_200, res->status);
  5250. ASSERT_EQ("empty-no-content-type", res->body);
  5251. }
  5252. TEST_F(ServerTest, GetMethodDir) {
  5253. auto res = cli_.Get("/dir/");
  5254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5255. EXPECT_EQ(StatusCode::OK_200, res->status);
  5256. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5257. auto body = R"(<html>
  5258. <head>
  5259. </head>
  5260. <body>
  5261. <a href="/dir/test.html">Test</a>
  5262. <a href="/hi">hi</a>
  5263. </body>
  5264. </html>
  5265. )";
  5266. EXPECT_EQ(body, res->body);
  5267. }
  5268. TEST_F(ServerTest, GetMethodDirTest) {
  5269. auto res = cli_.Get("/dir/test.html");
  5270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5273. EXPECT_EQ("test.html", res->body);
  5274. }
  5275. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5276. auto res = cli_.Get("/dir/../dir/test.html");
  5277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5278. EXPECT_EQ(StatusCode::OK_200, res->status);
  5279. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5280. EXPECT_EQ("test.html", res->body);
  5281. }
  5282. TEST_F(ServerTest, GetMethodInvalidPath) {
  5283. auto res = cli_.Get("/dir/../test.html");
  5284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5285. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5286. }
  5287. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5288. auto res = cli_.Get("/../www/dir/test.html");
  5289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5291. }
  5292. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5293. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5295. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5296. }
  5297. TEST_F(ServerTest, GetMethodDirMountTest) {
  5298. auto res = cli_.Get("/mount/dir/test.html");
  5299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5300. EXPECT_EQ(StatusCode::OK_200, res->status);
  5301. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5302. EXPECT_EQ("test.html", res->body);
  5303. }
  5304. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5305. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5307. EXPECT_EQ(StatusCode::OK_200, res->status);
  5308. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5309. EXPECT_EQ("test.html", res->body);
  5310. }
  5311. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5312. auto res = cli_.Get("/mount/dir/../test.html");
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5315. }
  5316. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5317. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5319. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5320. }
  5321. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5322. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5324. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5325. }
  5326. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5327. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5329. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5330. }
  5331. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5332. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5334. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5335. }
  5336. TEST_F(ServerTest, PostMethod303) {
  5337. auto res = cli_.Post("/1", "body", "text/plain");
  5338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5339. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5340. EXPECT_EQ("/2", res->get_header_value("Location"));
  5341. }
  5342. TEST_F(ServerTest, PostMethod303Redirect) {
  5343. cli_.set_follow_location(true);
  5344. auto res = cli_.Post("/1", "body", "text/plain");
  5345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5346. EXPECT_EQ(StatusCode::OK_200, res->status);
  5347. EXPECT_EQ("redirected.", res->body);
  5348. EXPECT_EQ("/2", res->location);
  5349. }
  5350. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5351. auto res = cli_.Get("/dir/test.abcde");
  5352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5353. EXPECT_EQ(StatusCode::OK_200, res->status);
  5354. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5355. EXPECT_EQ("abcde", res->body);
  5356. }
  5357. TEST_F(ServerTest, StaticFileRange) {
  5358. auto res =
  5359. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5361. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5362. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5363. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5364. EXPECT_EQ(true, res->has_header("Content-Range"));
  5365. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5366. EXPECT_EQ(std::string("cd"), res->body);
  5367. }
  5368. TEST_F(ServerTest, StaticFileRanges) {
  5369. auto res = cli_.Get("/dir/test.abcde",
  5370. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5372. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5373. EXPECT_TRUE(
  5374. res->get_header_value("Content-Type")
  5375. .find(
  5376. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5377. 0);
  5378. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5379. }
  5380. TEST_F(ServerTest, StaticFileRangeHead) {
  5381. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5383. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5384. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5385. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5386. EXPECT_EQ(true, res->has_header("Content-Range"));
  5387. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5388. }
  5389. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5390. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5392. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5393. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5394. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5395. EXPECT_EQ(true, res->has_header("Content-Range"));
  5396. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5397. res->get_header_value("Content-Range"));
  5398. EXPECT_EQ("LAST\n", res->body);
  5399. }
  5400. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5401. auto res =
  5402. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5405. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5406. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5407. EXPECT_EQ(true, res->has_header("Content-Range"));
  5408. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5409. }
  5410. TEST_F(ServerTest, StaticFileBigFile) {
  5411. auto res = cli_.Get("/dir/1MB.txt");
  5412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5413. EXPECT_EQ(StatusCode::OK_200, res->status);
  5414. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5415. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5416. }
  5417. TEST_F(ServerTest, InvalidBaseDirMount) {
  5418. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5419. }
  5420. TEST_F(ServerTest, Binary) {
  5421. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5422. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5423. "application/octet-stream");
  5424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5425. ASSERT_EQ(StatusCode::OK_200, res->status);
  5426. ASSERT_EQ(4U, res->body.size());
  5427. res = cli_.Put("/binary", binary.data(), binary.size(),
  5428. "application/octet-stream");
  5429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5430. ASSERT_EQ(StatusCode::OK_200, res->status);
  5431. ASSERT_EQ(4U, res->body.size());
  5432. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5433. "application/octet-stream");
  5434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5435. ASSERT_EQ(StatusCode::OK_200, res->status);
  5436. ASSERT_EQ(4U, res->body.size());
  5437. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5438. "application/octet-stream");
  5439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5440. ASSERT_EQ(StatusCode::OK_200, res->status);
  5441. ASSERT_EQ(4U, res->body.size());
  5442. }
  5443. TEST_F(ServerTest, BinaryString) {
  5444. auto binary = std::string("\x00\x01\x02\x03", 4);
  5445. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5447. ASSERT_EQ(StatusCode::OK_200, res->status);
  5448. ASSERT_EQ(4U, res->body.size());
  5449. res = cli_.Put("/binary", binary, "application/octet-stream");
  5450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5451. ASSERT_EQ(StatusCode::OK_200, res->status);
  5452. ASSERT_EQ(4U, res->body.size());
  5453. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5455. ASSERT_EQ(StatusCode::OK_200, res->status);
  5456. ASSERT_EQ(4U, res->body.size());
  5457. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. ASSERT_EQ(StatusCode::OK_200, res->status);
  5460. ASSERT_EQ(4U, res->body.size());
  5461. }
  5462. TEST_F(ServerTest, EmptyRequest) {
  5463. auto res = cli_.Get("");
  5464. ASSERT_TRUE(!res);
  5465. EXPECT_EQ(Error::Connection, res.error());
  5466. }
  5467. TEST_F(ServerTest, LongRequest) {
  5468. std::string request;
  5469. for (size_t i = 0; i < 545; i++) {
  5470. request += "/TooLongRequest";
  5471. }
  5472. request += "OK";
  5473. auto res = cli_.Get(request.c_str());
  5474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5475. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5476. }
  5477. TEST_F(ServerTest, TooLongRequest) {
  5478. std::string request;
  5479. for (size_t i = 0; i < 546; i++) {
  5480. request += "/TooLongRequest";
  5481. }
  5482. request += "_NG";
  5483. auto start = std::chrono::high_resolution_clock::now();
  5484. cli_.set_keep_alive(true);
  5485. auto res = cli_.Get(request.c_str());
  5486. auto end = std::chrono::high_resolution_clock::now();
  5487. auto elapsed =
  5488. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5489. .count();
  5490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5491. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5492. EXPECT_LE(elapsed, 1000);
  5493. EXPECT_EQ("close", res->get_header_value("Connection"));
  5494. EXPECT_FALSE(cli_.is_socket_open());
  5495. }
  5496. TEST_F(ServerTest, AlmostTooLongRequest) {
  5497. // test for #2046 - URI length check shouldn't include other content on req
  5498. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5499. // leading /, space, HTTP/1.1)
  5500. std::string request =
  5501. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5502. auto res = cli_.Get(request.c_str());
  5503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5504. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5505. }
  5506. TEST_F(ServerTest, LongHeader) {
  5507. Request req;
  5508. req.method = "GET";
  5509. req.path = "/hi";
  5510. std::string host_and_port;
  5511. host_and_port += HOST;
  5512. host_and_port += ":";
  5513. host_and_port += std::to_string(PORT);
  5514. req.headers.emplace("Host", host_and_port.c_str());
  5515. req.headers.emplace("Accept", "*/*");
  5516. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5517. req.headers.emplace(
  5518. "Header-Name",
  5519. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5520. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5521. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5522. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5523. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5524. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5525. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5526. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5527. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5528. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5529. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5530. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5531. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5532. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5533. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5534. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5535. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5536. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5537. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5538. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5539. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5540. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5541. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5542. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5543. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5544. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5545. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5546. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5547. "@@@@@@@@@@@@@@@@");
  5548. auto res = std::make_shared<Response>();
  5549. auto error = Error::Success;
  5550. auto ret = cli_.send(req, *res, error);
  5551. ASSERT_TRUE(ret);
  5552. EXPECT_EQ(StatusCode::OK_200, res->status);
  5553. }
  5554. TEST_F(ServerTest, LongQueryValue) {
  5555. auto start = std::chrono::high_resolution_clock::now();
  5556. cli_.set_keep_alive(true);
  5557. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5558. auto end = std::chrono::high_resolution_clock::now();
  5559. auto elapsed =
  5560. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5561. .count();
  5562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5563. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5564. EXPECT_LE(elapsed, 1000);
  5565. EXPECT_EQ("close", res->get_header_value("Connection"));
  5566. EXPECT_FALSE(cli_.is_socket_open());
  5567. }
  5568. TEST_F(ServerTest, TooLongQueryValue) {
  5569. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5570. ASSERT_FALSE(res);
  5571. EXPECT_EQ(Error::Read, res.error());
  5572. }
  5573. TEST_F(ServerTest, TooLongHeader) {
  5574. Request req;
  5575. req.method = "GET";
  5576. req.path = "/hi";
  5577. std::string host_and_port;
  5578. host_and_port += HOST;
  5579. host_and_port += ":";
  5580. host_and_port += std::to_string(PORT);
  5581. req.headers.emplace("Host", host_and_port.c_str());
  5582. req.headers.emplace("Accept", "*/*");
  5583. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5584. req.headers.emplace(
  5585. "Header-Name",
  5586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5594. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5595. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5596. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5597. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5598. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5599. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5600. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5601. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5602. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5603. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5614. "@@@@@@@@@@@@@@@@@");
  5615. auto res = std::make_shared<Response>();
  5616. auto error = Error::Success;
  5617. auto ret = cli_.send(req, *res, error);
  5618. ASSERT_TRUE(ret);
  5619. EXPECT_EQ(StatusCode::OK_200, res->status);
  5620. }
  5621. TEST_F(ServerTest, HeaderCountAtLimit) {
  5622. // Test with headers just under the 100 limit
  5623. httplib::Headers headers;
  5624. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5625. // This should keep us just under the 100 header limit
  5626. for (int i = 0; i < 95; i++) {
  5627. std::string name = "X-Test-Header-" + std::to_string(i);
  5628. std::string value = "value" + std::to_string(i);
  5629. headers.emplace(name, value);
  5630. }
  5631. // This should work fine as we're under the limit
  5632. auto res = cli_.Get("/hi", headers);
  5633. EXPECT_TRUE(res);
  5634. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5635. }
  5636. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5637. // Test with many headers to exceed the 100 limit
  5638. httplib::Headers headers;
  5639. // Add 150 headers to definitely exceed the 100 limit
  5640. for (int i = 0; i < 150; i++) {
  5641. std::string name = "X-Test-Header-" + std::to_string(i);
  5642. std::string value = "value" + std::to_string(i);
  5643. headers.emplace(name, value);
  5644. }
  5645. // This should fail due to exceeding header count limit
  5646. cli_.set_keep_alive(true);
  5647. auto res = cli_.Get("/hi", headers);
  5648. // The server should respond with 400 Bad Request
  5649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5650. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5651. EXPECT_EQ("close", res->get_header_value("Connection"));
  5652. EXPECT_FALSE(cli_.is_socket_open());
  5653. }
  5654. TEST_F(ServerTest, PercentEncoding) {
  5655. auto res = cli_.Get("/e%6edwith%");
  5656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5657. EXPECT_EQ(StatusCode::OK_200, res->status);
  5658. }
  5659. TEST_F(ServerTest, PercentEncodingUnicode) {
  5660. auto res = cli_.Get("/e%u006edwith%");
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. EXPECT_EQ(StatusCode::OK_200, res->status);
  5663. }
  5664. TEST_F(ServerTest, InvalidPercentEncoding) {
  5665. auto res = cli_.Get("/%endwith%");
  5666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5668. }
  5669. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5670. auto res = cli_.Get("/%uendwith%");
  5671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5672. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5673. }
  5674. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5675. auto res = cli_.Get("/hello?aaa=bbb%");
  5676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5677. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5678. }
  5679. TEST_F(ServerTest, PlusSignEncoding) {
  5680. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5682. EXPECT_EQ(StatusCode::OK_200, res->status);
  5683. EXPECT_EQ("a +b", res->body);
  5684. }
  5685. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5686. // This test simulates a potential DoS attack using many headers
  5687. // to verify our security fix prevents memory exhaustion
  5688. httplib::Headers attack_headers;
  5689. // Attempt to add many headers like an attacker would (200 headers to far
  5690. // exceed limit)
  5691. for (int i = 0; i < 200; i++) {
  5692. std::string name = "X-Attack-Header-" + std::to_string(i);
  5693. std::string value = "attack_payload_" + std::to_string(i);
  5694. attack_headers.emplace(name, value);
  5695. }
  5696. // Try to POST with excessive headers
  5697. cli_.set_keep_alive(true);
  5698. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5699. // Should either fail or return 400 Bad Request due to security limit
  5700. if (res) {
  5701. // If we get a response, it should be 400 Bad Request
  5702. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5703. EXPECT_EQ("close", res->get_header_value("Connection"));
  5704. }
  5705. EXPECT_FALSE(cli_.is_socket_open());
  5706. }
  5707. TEST_F(ServerTest, MultipartFormData) {
  5708. UploadFormDataItems items = {
  5709. {"text1", "text default", "", ""},
  5710. {"text2", "aωb", "", ""},
  5711. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5712. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5713. {"file3", "", "", "application/octet-stream"},
  5714. {"file4", "", "", " application/json tmp-string "}};
  5715. auto res = cli_.Post("/multipart", items);
  5716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5717. EXPECT_EQ(StatusCode::OK_200, res->status);
  5718. }
  5719. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5720. UploadFormDataItems items = {
  5721. {"text", "default text", "", ""},
  5722. {"multi_text1", "aaaaa", "", ""},
  5723. {"multi_text1", "bbbbb", "", ""},
  5724. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5725. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5726. "application/json"},
  5727. };
  5728. auto res = cli_.Post("/multipart/multi_file_values", items);
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. EXPECT_EQ(StatusCode::OK_200, res->status);
  5731. }
  5732. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5733. auto res = cli_.Get("/hi");
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. EXPECT_EQ(StatusCode::OK_200, res->status);
  5736. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5737. EXPECT_EQ("Hello World!", res->body);
  5738. }
  5739. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5740. Request req;
  5741. req.method = "POST";
  5742. req.path = "/chunked";
  5743. std::string host_and_port;
  5744. host_and_port += HOST;
  5745. host_and_port += ":";
  5746. host_and_port += std::to_string(PORT);
  5747. req.headers.emplace("Host", host_and_port.c_str());
  5748. req.headers.emplace("Accept", "*/*");
  5749. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5750. req.headers.emplace("Content-Type", "text/plain");
  5751. req.headers.emplace("Content-Length", "0");
  5752. req.headers.emplace(
  5753. "Transfer-Encoding",
  5754. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5755. // Client does not chunk, so make a chunked body manually.
  5756. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5757. auto res = std::make_shared<Response>();
  5758. auto error = Error::Success;
  5759. auto ret = cli_.send(req, *res, error);
  5760. ASSERT_TRUE(ret);
  5761. EXPECT_EQ(StatusCode::OK_200, res->status);
  5762. }
  5763. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5764. // rather than treat them as valid lengths.
  5765. template <typename ClientT>
  5766. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5767. Request req;
  5768. req.method = "POST";
  5769. req.path = "/chunked";
  5770. std::string host_and_port;
  5771. host_and_port += HOST;
  5772. host_and_port += ":";
  5773. host_and_port += std::to_string(PORT);
  5774. req.headers.emplace("Host", host_and_port.c_str());
  5775. req.headers.emplace("Content-Length", "0");
  5776. req.headers.emplace("Transfer-Encoding", "chunked");
  5777. req.body = body;
  5778. auto res = std::make_shared<Response>();
  5779. auto error = Error::Success;
  5780. ASSERT_TRUE(cli.send(req, *res, error));
  5781. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5782. }
  5783. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5784. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5785. }
  5786. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5787. expect_chunked_body_rejected(
  5788. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5789. }
  5790. TEST_F(ServerTest, GetStreamed2) {
  5791. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5793. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5794. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5795. EXPECT_EQ(true, res->has_header("Content-Range"));
  5796. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5797. EXPECT_EQ(std::string("ab"), res->body);
  5798. }
  5799. TEST_F(ServerTest, GetStreamed) {
  5800. auto res = cli_.Get("/streamed");
  5801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5802. EXPECT_EQ(StatusCode::OK_200, res->status);
  5803. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5804. EXPECT_EQ(std::string("aaabbb"), res->body);
  5805. }
  5806. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5807. auto res = cli_.Get("/streamed-without-length",
  5808. Headers{make_range_header({{0, -1}})});
  5809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5810. EXPECT_EQ(StatusCode::OK_200, res->status);
  5811. EXPECT_EQ(false, res->has_header("Content-Length"));
  5812. EXPECT_EQ(false, res->has_header("Content-Range"));
  5813. EXPECT_EQ(std::string("abcdefg"), res->body);
  5814. }
  5815. TEST_F(ServerTest, GetStreamedWithRange1) {
  5816. auto res =
  5817. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5819. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5820. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5821. EXPECT_EQ(true, res->has_header("Content-Range"));
  5822. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5823. EXPECT_EQ(std::string("def"), res->body);
  5824. }
  5825. TEST_F(ServerTest, GetStreamedWithRange2) {
  5826. auto res =
  5827. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5829. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5830. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5831. EXPECT_EQ(true, res->has_header("Content-Range"));
  5832. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5833. EXPECT_EQ(std::string("bcdefg"), res->body);
  5834. }
  5835. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5836. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5838. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5839. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5840. EXPECT_EQ(true, res->has_header("Content-Range"));
  5841. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5842. EXPECT_EQ(std::string("efg"), res->body);
  5843. }
  5844. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5845. auto res =
  5846. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5848. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5849. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5850. EXPECT_EQ(false, res->has_header("Content-Range"));
  5851. EXPECT_EQ(0U, res->body.size());
  5852. }
  5853. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5854. // Only a 206 is served as a partial representation. Under any other status
  5855. // `apply_ranges()` reported the full content length, so the body must match
  5856. // that header, and the content provider must never be asked for an offset
  5857. // outside the representation.
  5858. auto check = [&](int status, const char *range) {
  5859. auto path =
  5860. std::string("/streamed-with-range?status=") + std::to_string(status);
  5861. auto ctx = path + " Range: " + range;
  5862. auto res = cli_.Get(path, Headers{{"Range", range}});
  5863. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5864. EXPECT_EQ(status, res->status) << ctx;
  5865. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5866. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5867. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5868. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5869. };
  5870. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5871. check(403, "bytes=3-5");
  5872. // The offset is far past the representation.
  5873. check(403, "bytes=100000-100200");
  5874. // `first_pos` is still -1 here, and the bounds asserts in
  5875. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5876. check(403, "bytes=-3");
  5877. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5878. // multipart branch would have written one that is empty.
  5879. check(403, "bytes=1-2, 4-5");
  5880. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5881. // covers the whole representation.
  5882. check(200, "bytes=3-5");
  5883. check(200, "bytes=1-2, 4-5");
  5884. }
  5885. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5886. auto res =
  5887. cli_.Get("/streamed-with-range",
  5888. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5889. "92233720368547758079223372036854775807"}});
  5890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5891. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5892. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5893. EXPECT_EQ(false, res->has_header("Content-Range"));
  5894. EXPECT_EQ(0U, res->body.size());
  5895. }
  5896. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5897. auto res = cli_.Get(
  5898. "/with-range",
  5899. Headers{{"Range",
  5900. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5901. {"Accept-Encoding", ""}});
  5902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5904. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5905. EXPECT_EQ(true, res->has_header("Content-Range"));
  5906. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5907. EXPECT_EQ(std::string("abcdefg"), res->body);
  5908. }
  5909. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5910. auto res = cli_.Get("/with-range", Headers{
  5911. {"Range", "bytes=0-"},
  5912. {"Accept-Encoding", ""},
  5913. });
  5914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5915. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5916. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5917. EXPECT_EQ(true, res->has_header("Content-Range"));
  5918. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5919. EXPECT_EQ(std::string("abcdefg"), res->body);
  5920. }
  5921. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5922. auto res = cli_.Get("/streamed-with-range",
  5923. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5925. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5926. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5927. EXPECT_EQ(false, res->has_header("Content-Range"));
  5928. EXPECT_EQ(267U, res->body.size());
  5929. // Check that both range contents are present
  5930. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5931. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5932. // Check that Content-Range headers are present for both ranges
  5933. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5934. std::string::npos);
  5935. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5936. std::string::npos);
  5937. }
  5938. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5939. Ranges ranges;
  5940. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5941. ranges.emplace_back(0, -1);
  5942. }
  5943. auto res = cli_.Get("/streamed-with-range?error",
  5944. Headers{{make_range_header(ranges)}});
  5945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5946. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5947. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5948. EXPECT_EQ(false, res->has_header("Content-Range"));
  5949. EXPECT_EQ(0U, res->body.size());
  5950. }
  5951. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5952. auto res = cli_.Get("/streamed-with-range",
  5953. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5955. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5956. EXPECT_EQ(5U, res->body.size());
  5957. // Check that overlapping ranges are coalesced into a single range
  5958. EXPECT_EQ("bcdef", res->body);
  5959. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5960. // Should be single range, not multipart
  5961. EXPECT_TRUE(res->has_header("Content-Range"));
  5962. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5963. }
  5964. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5965. auto res = cli_.Get("/streamed-with-range",
  5966. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5969. EXPECT_EQ(268U, res->body.size());
  5970. // Check that both range contents are present
  5971. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5972. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5973. // Check that Content-Range headers are present for both ranges
  5974. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5975. std::string::npos);
  5976. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5977. std::string::npos);
  5978. }
  5979. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5980. auto res = cli_.Get("/streamed-with-range",
  5981. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5983. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5984. EXPECT_EQ(269U, res->body.size());
  5985. // Check that both duplicate range contents are present
  5986. size_t first_abc = res->body.find("abc\r\n");
  5987. EXPECT_TRUE(first_abc != std::string::npos);
  5988. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5989. EXPECT_TRUE(second_abc != std::string::npos);
  5990. // Check that Content-Range headers are present for both ranges
  5991. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5992. EXPECT_TRUE(first_range != std::string::npos);
  5993. size_t second_range =
  5994. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5995. EXPECT_TRUE(second_range != std::string::npos);
  5996. }
  5997. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5998. auto res =
  5999. cli_.Get("/streamed-with-range?error",
  6000. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6003. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6004. EXPECT_EQ(false, res->has_header("Content-Range"));
  6005. EXPECT_EQ(0U, res->body.size());
  6006. }
  6007. TEST_F(ServerTest, GetStreamedEndless) {
  6008. uint64_t offset = 0;
  6009. auto res = cli_.Get("/streamed-cancel",
  6010. [&](const char * /*data*/, uint64_t data_length) {
  6011. if (offset < 100) {
  6012. offset += data_length;
  6013. return true;
  6014. }
  6015. return false;
  6016. });
  6017. ASSERT_TRUE(!res);
  6018. EXPECT_EQ(Error::Canceled, res.error());
  6019. }
  6020. TEST_F(ServerTest, ClientStop) {
  6021. std::atomic_size_t count{4};
  6022. std::vector<std::thread> threads;
  6023. for (auto i = count.load(); i != 0; --i) {
  6024. threads.emplace_back([&]() {
  6025. auto res = cli_.Get("/streamed-cancel",
  6026. [&](const char *, uint64_t) { return true; });
  6027. --count;
  6028. ASSERT_TRUE(!res);
  6029. EXPECT_TRUE(res.error() == Error::Canceled ||
  6030. res.error() == Error::Read || res.error() == Error::Write);
  6031. });
  6032. }
  6033. std::this_thread::sleep_for(std::chrono::seconds(2));
  6034. while (count != 0) {
  6035. cli_.stop();
  6036. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6037. }
  6038. for (auto &t : threads) {
  6039. t.join();
  6040. }
  6041. }
  6042. TEST_F(ServerTest, GetWithRange1) {
  6043. auto res = cli_.Get("/with-range", Headers{
  6044. make_range_header({{3, 5}}),
  6045. {"Accept-Encoding", ""},
  6046. });
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6049. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6050. EXPECT_EQ(true, res->has_header("Content-Range"));
  6051. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6052. EXPECT_EQ(std::string("def"), res->body);
  6053. }
  6054. TEST_F(ServerTest, GetWithRange2) {
  6055. auto res = cli_.Get("/with-range", Headers{
  6056. make_range_header({{1, -1}}),
  6057. {"Accept-Encoding", ""},
  6058. });
  6059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6061. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6062. EXPECT_EQ(true, res->has_header("Content-Range"));
  6063. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6064. EXPECT_EQ(std::string("bcdefg"), res->body);
  6065. }
  6066. TEST_F(ServerTest, GetWithRange3) {
  6067. auto res = cli_.Get("/with-range", Headers{
  6068. make_range_header({{0, 0}}),
  6069. {"Accept-Encoding", ""},
  6070. });
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6073. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6074. EXPECT_EQ(true, res->has_header("Content-Range"));
  6075. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6076. EXPECT_EQ(std::string("a"), res->body);
  6077. }
  6078. TEST_F(ServerTest, GetWithRange4) {
  6079. auto res = cli_.Get("/with-range", Headers{
  6080. make_range_header({{-1, 2}}),
  6081. {"Accept-Encoding", ""},
  6082. });
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6085. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6086. EXPECT_EQ(true, res->has_header("Content-Range"));
  6087. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6088. EXPECT_EQ(std::string("fg"), res->body);
  6089. }
  6090. TEST_F(ServerTest, GetWithRange5) {
  6091. auto res = cli_.Get("/with-range", Headers{
  6092. make_range_header({{0, 5}}),
  6093. {"Accept-Encoding", ""},
  6094. });
  6095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6096. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6097. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6098. EXPECT_EQ(true, res->has_header("Content-Range"));
  6099. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6100. EXPECT_EQ(std::string("abcdef"), res->body);
  6101. }
  6102. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6103. auto res =
  6104. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6106. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6107. }
  6108. TEST_F(ServerTest, GetWithRangeMultipart) {
  6109. auto res =
  6110. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6112. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6113. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6114. EXPECT_EQ(false, res->has_header("Content-Range"));
  6115. EXPECT_EQ(267U, res->body.size());
  6116. }
  6117. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6118. auto res = cli_.Get("/with-range",
  6119. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6121. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6122. }
  6123. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6124. auto res = cli_.Get("/with-range-customized-response",
  6125. Headers{{make_range_header({{1, 2}})}});
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6128. EXPECT_EQ(true, res->has_header("Content-Length"));
  6129. EXPECT_EQ(false, res->has_header("Content-Range"));
  6130. EXPECT_EQ(JSON_DATA, res->body);
  6131. }
  6132. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6133. auto res = cli_.Get("/with-range-customized-response",
  6134. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6136. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6137. EXPECT_EQ(true, res->has_header("Content-Length"));
  6138. EXPECT_EQ(false, res->has_header("Content-Range"));
  6139. EXPECT_EQ(JSON_DATA, res->body);
  6140. }
  6141. TEST_F(ServerTest, Issue1772) {
  6142. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6144. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6145. }
  6146. TEST_F(ServerTest, Issue609) {
  6147. auto res = cli_.Delete("/issue609");
  6148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6149. EXPECT_EQ(StatusCode::OK_200, res->status);
  6150. EXPECT_EQ(std::string("ok"), res->body);
  6151. }
  6152. TEST_F(ServerTest, GetStreamedChunked) {
  6153. auto res = cli_.Get("/streamed-chunked");
  6154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6155. EXPECT_EQ(StatusCode::OK_200, res->status);
  6156. EXPECT_EQ(std::string("123456789"), res->body);
  6157. }
  6158. TEST_F(ServerTest, GetStreamedChunked2) {
  6159. auto res = cli_.Get("/streamed-chunked2");
  6160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6161. EXPECT_EQ(StatusCode::OK_200, res->status);
  6162. EXPECT_EQ(std::string("123456789"), res->body);
  6163. }
  6164. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6165. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6167. EXPECT_EQ(StatusCode::OK_200, res->status);
  6168. EXPECT_EQ(std::string("123456789"), res->body);
  6169. EXPECT_TRUE(res->has_header("Trailer"));
  6170. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6171. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6172. // Trailers are now stored separately from headers (security fix)
  6173. EXPECT_EQ(2U, res->trailers.size());
  6174. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6175. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6176. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6177. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6178. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6179. // Verify trailers are NOT in headers (security verification)
  6180. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6181. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6182. }
  6183. TEST_F(ServerTest, LargeChunkedPost) {
  6184. Request req;
  6185. req.method = "POST";
  6186. req.path = "/large-chunked";
  6187. std::string host_and_port;
  6188. host_and_port += HOST;
  6189. host_and_port += ":";
  6190. host_and_port += std::to_string(PORT);
  6191. req.headers.emplace("Host", host_and_port.c_str());
  6192. req.headers.emplace("Accept", "*/*");
  6193. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6194. req.headers.emplace("Content-Type", "text/plain");
  6195. req.headers.emplace("Content-Length", "0");
  6196. req.headers.emplace("Transfer-Encoding", "chunked");
  6197. std::string long_string(30 * 1024u, 'a');
  6198. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6199. // Attempt to make a large enough post to exceed OS buffers, to test that
  6200. // the server handles short reads if the full chunk data isn't available.
  6201. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6202. auto res = std::make_shared<Response>();
  6203. auto error = Error::Success;
  6204. auto ret = cli_.send(req, *res, error);
  6205. ASSERT_TRUE(ret);
  6206. EXPECT_EQ(StatusCode::OK_200, res->status);
  6207. }
  6208. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6209. auto res = cli_.Get("/remote_addr");
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. EXPECT_EQ(StatusCode::OK_200, res->status);
  6212. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6213. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6214. }
  6215. TEST_F(ServerTest, GetMethodLocalAddr) {
  6216. auto res = cli_.Get("/local_addr");
  6217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6218. EXPECT_EQ(StatusCode::OK_200, res->status);
  6219. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6220. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6221. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6222. }
  6223. TEST_F(ServerTest, HTTPResponseSplitting) {
  6224. auto res = cli_.Get("/http_response_splitting");
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. EXPECT_EQ(StatusCode::OK_200, res->status);
  6227. }
  6228. TEST_F(ServerTest, SlowRequest) {
  6229. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6230. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6231. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6232. }
  6233. #if 0
  6234. TEST_F(ServerTest, SlowPost) {
  6235. char buffer[64 * 1024];
  6236. memset(buffer, 0x42, sizeof(buffer));
  6237. auto res = cli_.Post(
  6238. "/slowpost", 64 * 1024 * 1024,
  6239. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6240. auto ret = sink.write(buffer, sizeof(buffer));
  6241. EXPECT_TRUE(ret);
  6242. return true;
  6243. },
  6244. "text/plain");
  6245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6246. EXPECT_EQ(StatusCode::OK_200, res->status);
  6247. }
  6248. TEST_F(ServerTest, SlowPostFail) {
  6249. char buffer[64 * 1024];
  6250. memset(buffer, 0x42, sizeof(buffer));
  6251. cli_.set_write_timeout(std::chrono::seconds(0));
  6252. auto res = cli_.Post(
  6253. "/slowpost", 64 * 1024 * 1024,
  6254. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6255. sink.write(buffer, sizeof(buffer));
  6256. return true;
  6257. },
  6258. "text/plain");
  6259. ASSERT_TRUE(!res);
  6260. EXPECT_EQ(Error::Write, res.error());
  6261. }
  6262. #endif
  6263. TEST_F(ServerTest, Put) {
  6264. auto res = cli_.Put("/put", "PUT", "text/plain");
  6265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6266. EXPECT_EQ(StatusCode::OK_200, res->status);
  6267. EXPECT_EQ("PUT", res->body);
  6268. }
  6269. TEST_F(ServerTest, PutWithContentProvider) {
  6270. auto res = cli_.Put(
  6271. "/put", 3,
  6272. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6273. sink.os << "PUT";
  6274. return true;
  6275. },
  6276. "text/plain");
  6277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6278. EXPECT_EQ(StatusCode::OK_200, res->status);
  6279. EXPECT_EQ("PUT", res->body);
  6280. }
  6281. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6282. auto res = cli_.Post(
  6283. "/post", 42,
  6284. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6285. return false;
  6286. },
  6287. "text/plain");
  6288. ASSERT_TRUE(!res);
  6289. EXPECT_EQ(Error::Canceled, res.error());
  6290. }
  6291. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6292. auto res = cli_.Put(
  6293. "/put",
  6294. [](size_t /*offset*/, DataSink &sink) {
  6295. sink.os << "PUT";
  6296. sink.done();
  6297. return true;
  6298. },
  6299. "text/plain");
  6300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6301. EXPECT_EQ(StatusCode::OK_200, res->status);
  6302. EXPECT_EQ("PUT", res->body);
  6303. }
  6304. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6305. auto res = cli_.Post(
  6306. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6307. "text/plain");
  6308. ASSERT_TRUE(!res);
  6309. EXPECT_EQ(Error::Canceled, res.error());
  6310. }
  6311. TEST_F(ServerTest, PostLoopBack) {
  6312. std::string body;
  6313. auto res = cli_.Post(
  6314. "/post-loopback", 9,
  6315. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6316. EXPECT_EQ(9u, length);
  6317. sink.write("123", 3);
  6318. sink.write("456", 3);
  6319. sink.write("789", 3);
  6320. return true;
  6321. },
  6322. "text/plain",
  6323. [&body](const char *data, size_t data_length) {
  6324. body.append(data, data_length);
  6325. return true;
  6326. });
  6327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6328. EXPECT_EQ(StatusCode::OK_200, res->status);
  6329. EXPECT_EQ("123456789", body);
  6330. }
  6331. TEST_F(ServerTest, PutLoopBack) {
  6332. std::string body;
  6333. auto res = cli_.Put(
  6334. "/put-loopback", 9,
  6335. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6336. EXPECT_EQ(9u, length);
  6337. sink.write("123", 3);
  6338. sink.write("456", 3);
  6339. sink.write("789", 3);
  6340. return true;
  6341. },
  6342. "text/plain",
  6343. [&body](const char *data, size_t data_length) {
  6344. body.append(data, data_length);
  6345. return true;
  6346. });
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. EXPECT_EQ(StatusCode::OK_200, res->status);
  6349. EXPECT_EQ("123456789", body);
  6350. }
  6351. TEST_F(ServerTest, PatchLoopBack) {
  6352. std::string body;
  6353. auto res = cli_.Patch(
  6354. "/patch-loopback", 9,
  6355. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6356. EXPECT_EQ(9u, length);
  6357. sink.write("123", 3);
  6358. sink.write("456", 3);
  6359. sink.write("789", 3);
  6360. return true;
  6361. },
  6362. "text/plain",
  6363. [&body](const char *data, size_t data_length) {
  6364. body.append(data, data_length);
  6365. return true;
  6366. });
  6367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6368. EXPECT_EQ(StatusCode::OK_200, res->status);
  6369. EXPECT_EQ("123456789", body);
  6370. }
  6371. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6372. std::string body;
  6373. auto res = cli_.Post(
  6374. "/post-loopback",
  6375. [](size_t /*offset*/, DataSink &sink) {
  6376. sink.write("123", 3);
  6377. sink.write("456", 3);
  6378. sink.write("789", 3);
  6379. sink.done();
  6380. return true;
  6381. },
  6382. "text/plain",
  6383. [&body](const char *data, size_t data_length) {
  6384. body.append(data, data_length);
  6385. return true;
  6386. });
  6387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6388. EXPECT_EQ(StatusCode::OK_200, res->status);
  6389. EXPECT_EQ("123456789", body);
  6390. }
  6391. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6392. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6393. cli_.set_compress(true);
  6394. auto res = cli_.Put(
  6395. "/put", 3,
  6396. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6397. sink.os << "PUT";
  6398. return true;
  6399. },
  6400. "text/plain");
  6401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6402. EXPECT_EQ(StatusCode::OK_200, res->status);
  6403. EXPECT_EQ("PUT", res->body);
  6404. }
  6405. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6406. cli_.set_compress(true);
  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, PutWithContentProviderWithoutLengthWithGzip) {
  6417. cli_.set_compress(true);
  6418. auto res = cli_.Put(
  6419. "/put",
  6420. [](size_t /*offset*/, DataSink &sink) {
  6421. sink.os << "PUT";
  6422. sink.done();
  6423. return true;
  6424. },
  6425. "text/plain");
  6426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6427. EXPECT_EQ(StatusCode::OK_200, res->status);
  6428. EXPECT_EQ("PUT", res->body);
  6429. }
  6430. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6431. cli_.set_compress(true);
  6432. auto res = cli_.Post(
  6433. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6434. "text/plain");
  6435. ASSERT_TRUE(!res);
  6436. EXPECT_EQ(Error::Canceled, res.error());
  6437. }
  6438. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6439. cli_.set_compress(true);
  6440. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. EXPECT_EQ(LARGE_DATA, res->body);
  6444. }
  6445. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6446. #ifdef CPPHTTPLIB_SSL_ENABLED
  6447. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6448. Client cli(s.c_str());
  6449. cli.enable_server_certificate_verification(false);
  6450. #else
  6451. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6452. Client cli(s.c_str());
  6453. #endif
  6454. cli.set_compress(true);
  6455. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6457. EXPECT_EQ(StatusCode::OK_200, res->status);
  6458. EXPECT_EQ(LARGE_DATA, res->body);
  6459. // The compressed size should be less than a 10th of the original. May vary
  6460. // depending on the zlib library.
  6461. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6462. static_cast<uint64_t>(10 * 1024 * 1024));
  6463. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6464. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6465. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6466. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6467. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6468. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6469. #endif
  6470. }
  6471. TEST_F(ServerTest, PutContentWithDeflate) {
  6472. cli_.set_compress(false);
  6473. Headers headers;
  6474. headers.emplace("Content-Encoding", "deflate");
  6475. // PUT in deflate format:
  6476. auto res = cli_.Put("/put", headers,
  6477. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. EXPECT_EQ(StatusCode::OK_200, res->status);
  6480. EXPECT_EQ("PUT", res->body);
  6481. }
  6482. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6483. Headers headers;
  6484. headers.emplace("Accept-Encoding", "gzip, deflate");
  6485. auto res = cli_.Get("/streamed-chunked", headers);
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. EXPECT_EQ(StatusCode::OK_200, res->status);
  6488. EXPECT_EQ(std::string("123456789"), res->body);
  6489. }
  6490. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6491. Headers headers;
  6492. headers.emplace("Accept-Encoding", "gzip, deflate");
  6493. auto res = cli_.Get("/streamed-chunked2", headers);
  6494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6495. EXPECT_EQ(StatusCode::OK_200, res->status);
  6496. EXPECT_EQ(std::string("123456789"), res->body);
  6497. }
  6498. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6499. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. EXPECT_EQ(StatusCode::OK_200, res->status);
  6502. }
  6503. TEST(GzipDecompressor, ChunkedDecompression) {
  6504. std::string data;
  6505. for (size_t i = 0; i < 32 * 1024; ++i) {
  6506. data.push_back(static_cast<char>('a' + i % 26));
  6507. }
  6508. std::string compressed_data;
  6509. {
  6510. httplib::detail::gzip_compressor compressor;
  6511. bool result = compressor.compress(
  6512. data.data(), data.size(),
  6513. /*last=*/true,
  6514. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6515. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6516. compressed_data_size);
  6517. return true;
  6518. });
  6519. ASSERT_TRUE(result);
  6520. }
  6521. std::string decompressed_data;
  6522. {
  6523. httplib::detail::gzip_decompressor decompressor;
  6524. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6525. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6526. size_t chunk_size = 130;
  6527. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6528. chunk_begin += chunk_size) {
  6529. size_t current_chunk_size =
  6530. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6531. bool result = decompressor.decompress(
  6532. compressed_data.data() + chunk_begin, current_chunk_size,
  6533. [&](const char *decompressed_data_chunk,
  6534. size_t decompressed_data_chunk_size) {
  6535. decompressed_data.insert(decompressed_data.size(),
  6536. decompressed_data_chunk,
  6537. decompressed_data_chunk_size);
  6538. return true;
  6539. });
  6540. ASSERT_TRUE(result);
  6541. }
  6542. }
  6543. ASSERT_EQ(data, decompressed_data);
  6544. }
  6545. TEST(GzipDecompressor, DeflateDecompression) {
  6546. std::string original_text = "Raw deflate without gzip";
  6547. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6548. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6549. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6550. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6551. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6552. std::string decompressed_data;
  6553. {
  6554. httplib::detail::gzip_decompressor decompressor;
  6555. bool result = decompressor.decompress(
  6556. compressed_data.data(), compressed_data.size(),
  6557. [&](const char *decompressed_data_chunk,
  6558. size_t decompressed_data_chunk_size) {
  6559. decompressed_data.insert(decompressed_data.size(),
  6560. decompressed_data_chunk,
  6561. decompressed_data_chunk_size);
  6562. return true;
  6563. });
  6564. ASSERT_TRUE(result);
  6565. }
  6566. ASSERT_EQ(original_text, decompressed_data);
  6567. }
  6568. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6569. std::string original_text = "Raw deflate without gzip";
  6570. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6571. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6572. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6573. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6574. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6575. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6576. std::string decompressed_data;
  6577. {
  6578. httplib::detail::gzip_decompressor decompressor;
  6579. bool result = decompressor.decompress(
  6580. compressed_data.data(), compressed_data.size(),
  6581. [&](const char *decompressed_data_chunk,
  6582. size_t decompressed_data_chunk_size) {
  6583. decompressed_data.insert(decompressed_data.size(),
  6584. decompressed_data_chunk,
  6585. decompressed_data_chunk_size);
  6586. return true;
  6587. });
  6588. ASSERT_TRUE(result);
  6589. }
  6590. ASSERT_EQ(original_text, decompressed_data);
  6591. }
  6592. #endif
  6593. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6594. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6595. Headers headers;
  6596. headers.emplace("Accept-Encoding", "br");
  6597. auto res = cli_.Get("/streamed-chunked", headers);
  6598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6599. EXPECT_EQ(StatusCode::OK_200, res->status);
  6600. EXPECT_EQ(std::string("123456789"), res->body);
  6601. }
  6602. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6603. Headers headers;
  6604. headers.emplace("Accept-Encoding", "br");
  6605. auto res = cli_.Get("/streamed-chunked2", headers);
  6606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6607. EXPECT_EQ(StatusCode::OK_200, res->status);
  6608. EXPECT_EQ(std::string("123456789"), res->body);
  6609. }
  6610. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6611. cli_.set_compress(true);
  6612. auto res = cli_.Put(
  6613. "/put", 3,
  6614. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6615. sink.os << "PUT";
  6616. return true;
  6617. },
  6618. "text/plain");
  6619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6620. EXPECT_EQ(StatusCode::OK_200, res->status);
  6621. EXPECT_EQ("PUT", res->body);
  6622. }
  6623. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6624. cli_.set_compress(true);
  6625. auto res = cli_.Put(
  6626. "/put",
  6627. [](size_t /*offset*/, DataSink &sink) {
  6628. sink.os << "PUT";
  6629. sink.done();
  6630. return true;
  6631. },
  6632. "text/plain");
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. EXPECT_EQ(StatusCode::OK_200, res->status);
  6635. EXPECT_EQ("PUT", res->body);
  6636. }
  6637. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6638. cli_.set_compress(true);
  6639. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6641. EXPECT_EQ(StatusCode::OK_200, res->status);
  6642. EXPECT_EQ(LARGE_DATA, res->body);
  6643. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6644. }
  6645. #endif
  6646. TEST_F(ServerTest, Patch) {
  6647. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6649. EXPECT_EQ(StatusCode::OK_200, res->status);
  6650. EXPECT_EQ("PATCH", res->body);
  6651. }
  6652. TEST_F(ServerTest, Delete) {
  6653. auto res = cli_.Delete("/delete");
  6654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6655. EXPECT_EQ(StatusCode::OK_200, res->status);
  6656. EXPECT_EQ("DELETE", res->body);
  6657. }
  6658. TEST_F(ServerTest, DeleteContentReceiver) {
  6659. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::OK_200, res->status);
  6662. EXPECT_EQ("content", res->body);
  6663. }
  6664. TEST_F(ServerTest, Options) {
  6665. auto res = cli_.Options("*");
  6666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6667. EXPECT_EQ(StatusCode::OK_200, res->status);
  6668. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6669. EXPECT_TRUE(res->body.empty());
  6670. }
  6671. TEST_F(ServerTest, URL) {
  6672. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6674. EXPECT_EQ(StatusCode::OK_200, res->status);
  6675. }
  6676. TEST_F(ServerTest, ArrayParam) {
  6677. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6679. EXPECT_EQ(StatusCode::OK_200, res->status);
  6680. }
  6681. TEST_F(ServerTest, ArrayParamValues) {
  6682. auto res =
  6683. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. }
  6687. TEST_F(ServerTest, NoMultipleHeaders) {
  6688. Headers headers = {{"Content-Length", "5"}};
  6689. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6690. "text/plain");
  6691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6692. EXPECT_EQ(StatusCode::OK_200, res->status);
  6693. }
  6694. TEST_F(ServerTest, PostContentReceiver) {
  6695. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. ASSERT_EQ(StatusCode::OK_200, res->status);
  6698. ASSERT_EQ("content", res->body);
  6699. }
  6700. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6701. UploadFormDataItems items = {
  6702. {"text1", "text default", "", ""},
  6703. {"text2", "aωb", "", ""},
  6704. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6705. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6706. {"file3", "", "", "application/octet-stream"},
  6707. };
  6708. auto res = cli_.Post("/content_receiver", items);
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. }
  6712. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6713. UploadFormDataItems items = {
  6714. {"text1", "text default", "", ""},
  6715. {"text2", "aωb", "", ""},
  6716. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6717. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6718. {"file3", "", "", "application/octet-stream"},
  6719. };
  6720. auto boundary = std::string("+++++");
  6721. std::string body;
  6722. for (const auto &item : items) {
  6723. body += "--" + boundary + "\r\n";
  6724. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6725. if (!item.filename.empty()) {
  6726. body += "; filename=\"" + item.filename + "\"";
  6727. }
  6728. body += "\r\n";
  6729. if (!item.content_type.empty()) {
  6730. body += "Content-Type: " + item.content_type + "\r\n";
  6731. }
  6732. body += "\r\n";
  6733. body += item.content + "\r\n";
  6734. }
  6735. body += "--" + boundary + "--\r\n";
  6736. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6737. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6739. EXPECT_EQ(StatusCode::OK_200, res->status);
  6740. }
  6741. TEST(MultipartFormDataTest, FieldEscaping) {
  6742. Server svr;
  6743. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6744. const ContentReader &content_reader) {
  6745. ASSERT_TRUE(req.is_multipart_form_data());
  6746. std::vector<FormData> received;
  6747. content_reader(
  6748. [&](const FormData &file) {
  6749. received.push_back(file);
  6750. return true;
  6751. },
  6752. [&](const char *data, size_t data_length) {
  6753. received.back().content.append(data, data_length);
  6754. return true;
  6755. });
  6756. // '"', CR and LF in names and filenames are escaped following the
  6757. // WHATWG HTML standard, so each part still parses as a single part
  6758. // with no injected headers. Content types get CR/LF escaped too,
  6759. // while '"' (legal there, e.g. quoted charset) is preserved.
  6760. ASSERT_EQ(4U, received.size());
  6761. EXPECT_EQ("na%22me", received[0].name);
  6762. EXPECT_EQ("quoted name", received[0].content);
  6763. EXPECT_EQ("file", received[1].name);
  6764. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6765. received[1].filename);
  6766. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6767. EXPECT_EQ("injected", received[1].content);
  6768. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6769. EXPECT_EQ("my%22file.txt", received[2].filename);
  6770. EXPECT_EQ("cr lf name", received[2].content);
  6771. EXPECT_EQ("typed", received[3].name);
  6772. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6773. received[3].content_type);
  6774. EXPECT_EQ("typed content", received[3].content);
  6775. });
  6776. auto port = svr.bind_to_any_port("localhost");
  6777. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6778. auto se = detail::scope_exit([&] {
  6779. svr.stop();
  6780. t.join();
  6781. ASSERT_FALSE(svr.is_running());
  6782. });
  6783. svr.wait_until_ready();
  6784. Client cli("localhost", port);
  6785. UploadFormDataItems items = {
  6786. {"na\"me", "quoted name", "", ""},
  6787. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6788. "application/octet-stream"},
  6789. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6790. {"typed", "typed content", "",
  6791. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6792. };
  6793. auto res = cli.Post("/post", items);
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ(StatusCode::OK_200, res->status);
  6796. }
  6797. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6798. const UploadFormDataItems items = {
  6799. {"name1", "Content 1", "", ""},
  6800. {"name2", "Content 2", "file2.txt", "text/plain"},
  6801. };
  6802. Server svr;
  6803. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6804. const ContentReader &content_reader) {
  6805. ASSERT_TRUE(req.is_multipart_form_data());
  6806. std::vector<FormData> received;
  6807. content_reader(
  6808. [&](const FormData &file) {
  6809. received.push_back(file);
  6810. return true;
  6811. },
  6812. [&](const char *data, size_t data_length) {
  6813. received.back().content.append(data, data_length);
  6814. return true;
  6815. });
  6816. ASSERT_EQ(2U, received.size());
  6817. EXPECT_EQ("name1", received[0].name);
  6818. EXPECT_EQ("Content 1", received[0].content);
  6819. EXPECT_EQ("name2", received[1].name);
  6820. EXPECT_EQ("Content 2", received[1].content);
  6821. EXPECT_EQ("file2.txt", received[1].filename);
  6822. EXPECT_EQ("text/plain", received[1].content_type);
  6823. });
  6824. auto port = svr.bind_to_any_port("localhost");
  6825. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6826. auto se = detail::scope_exit([&] {
  6827. svr.stop();
  6828. t.join();
  6829. ASSERT_FALSE(svr.is_running());
  6830. });
  6831. svr.wait_until_ready();
  6832. Client cli("localhost", port);
  6833. // Whole-body serialization with a generated boundary
  6834. {
  6835. MultipartFormDataWriter writer;
  6836. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6837. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6838. writer.content_type());
  6839. auto body = writer.serialize(items);
  6840. EXPECT_EQ(body.size(), writer.content_length(items));
  6841. auto res = cli.Post("/post", body, writer.content_type());
  6842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6843. EXPECT_EQ(StatusCode::OK_200, res->status);
  6844. }
  6845. // Per-part framing with a custom boundary via a content provider
  6846. {
  6847. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6848. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6849. MultipartFormDataWriter writer("custom-boundary_123");
  6850. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6851. std::string body;
  6852. for (const auto &item : items) {
  6853. body += writer.item_begin(item);
  6854. body += item.content;
  6855. body += MultipartFormDataWriter::item_end();
  6856. }
  6857. body += writer.finish();
  6858. EXPECT_EQ(body.size(), writer.content_length(items));
  6859. auto res = cli.Post(
  6860. "/post", body.size(),
  6861. [&](size_t offset, size_t length, DataSink &sink) {
  6862. sink.write(body.data() + offset, length);
  6863. return true;
  6864. },
  6865. writer.content_type());
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. }
  6869. }
  6870. TEST_F(ServerTest, PostContentReceiverGzip) {
  6871. cli_.set_compress(true);
  6872. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6874. ASSERT_EQ(StatusCode::OK_200, res->status);
  6875. ASSERT_EQ("content", res->body);
  6876. }
  6877. TEST_F(ServerTest, PutContentReceiver) {
  6878. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. ASSERT_EQ(StatusCode::OK_200, res->status);
  6881. ASSERT_EQ("content", res->body);
  6882. }
  6883. TEST_F(ServerTest, PatchContentReceiver) {
  6884. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6886. ASSERT_EQ(StatusCode::OK_200, res->status);
  6887. ASSERT_EQ("content", res->body);
  6888. }
  6889. template <typename ClientType>
  6890. void TestWithHeadersAndContentReceiver(
  6891. ClientType &cli,
  6892. std::function<Result(ClientType &, const std::string &, const Headers &,
  6893. const std::string &, const std::string &,
  6894. ContentReceiver, DownloadProgress)>
  6895. request_func) {
  6896. Headers headers;
  6897. headers.emplace("X-Custom-Header", "test-value");
  6898. std::string received_body;
  6899. auto res = request_func(
  6900. cli, "/content_receiver", headers, "content", "application/json",
  6901. [&](const char *data, size_t data_length) {
  6902. received_body.append(data, data_length);
  6903. return true;
  6904. },
  6905. nullptr);
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(StatusCode::OK_200, res->status);
  6908. EXPECT_EQ("content", received_body);
  6909. }
  6910. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6911. #ifdef CPPHTTPLIB_SSL_ENABLED
  6912. using ClientT = SSLClient;
  6913. #else
  6914. using ClientT = Client;
  6915. #endif
  6916. TestWithHeadersAndContentReceiver<ClientT>(
  6917. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6918. const std::string &body, const std::string &content_type,
  6919. ContentReceiver receiver, DownloadProgress progress) {
  6920. return cli.Post(path, headers, body, content_type, receiver, progress);
  6921. });
  6922. }
  6923. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6924. #ifdef CPPHTTPLIB_SSL_ENABLED
  6925. using ClientT = SSLClient;
  6926. #else
  6927. using ClientT = Client;
  6928. #endif
  6929. TestWithHeadersAndContentReceiver<ClientT>(
  6930. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6931. const std::string &body, const std::string &content_type,
  6932. ContentReceiver receiver, DownloadProgress progress) {
  6933. return cli.Put(path, headers, body, content_type, receiver, progress);
  6934. });
  6935. }
  6936. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6937. #ifdef CPPHTTPLIB_SSL_ENABLED
  6938. using ClientT = SSLClient;
  6939. #else
  6940. using ClientT = Client;
  6941. #endif
  6942. TestWithHeadersAndContentReceiver<ClientT>(
  6943. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6944. const std::string &body, const std::string &content_type,
  6945. ContentReceiver receiver, DownloadProgress progress) {
  6946. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6947. });
  6948. }
  6949. template <typename ClientType>
  6950. void TestWithHeadersAndContentReceiverWithProgress(
  6951. ClientType &cli,
  6952. std::function<Result(ClientType &, const std::string &, const Headers &,
  6953. const std::string &, const std::string &,
  6954. ContentReceiver, DownloadProgress)>
  6955. request_func) {
  6956. Headers headers;
  6957. headers.emplace("X-Test-Header", "progress-test");
  6958. std::string received_body;
  6959. auto progress_called = false;
  6960. auto res = request_func(
  6961. cli, "/content_receiver", headers, "content", "text/plain",
  6962. [&](const char *data, size_t data_length) {
  6963. received_body.append(data, data_length);
  6964. return true;
  6965. },
  6966. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6967. progress_called = true;
  6968. return true;
  6969. });
  6970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6971. EXPECT_EQ(StatusCode::OK_200, res->status);
  6972. EXPECT_EQ("content", received_body);
  6973. EXPECT_TRUE(progress_called);
  6974. }
  6975. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6976. #ifdef CPPHTTPLIB_SSL_ENABLED
  6977. using ClientT = SSLClient;
  6978. #else
  6979. using ClientT = Client;
  6980. #endif
  6981. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6982. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6983. const std::string &body, const std::string &content_type,
  6984. ContentReceiver receiver, DownloadProgress progress) {
  6985. return cli.Post(path, headers, body, content_type, receiver, progress);
  6986. });
  6987. }
  6988. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6989. #ifdef CPPHTTPLIB_SSL_ENABLED
  6990. using ClientT = SSLClient;
  6991. #else
  6992. using ClientT = Client;
  6993. #endif
  6994. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6995. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6996. const std::string &body, const std::string &content_type,
  6997. ContentReceiver receiver, DownloadProgress progress) {
  6998. return cli.Put(path, headers, body, content_type, receiver, progress);
  6999. });
  7000. }
  7001. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7002. #ifdef CPPHTTPLIB_SSL_ENABLED
  7003. using ClientT = SSLClient;
  7004. #else
  7005. using ClientT = Client;
  7006. #endif
  7007. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7008. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7009. const std::string &body, const std::string &content_type,
  7010. ContentReceiver receiver, DownloadProgress progress) {
  7011. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7012. });
  7013. }
  7014. template <typename ClientType>
  7015. void TestWithHeadersAndContentReceiverError(
  7016. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7017. const Headers &, const std::string &,
  7018. const std::string &, ContentReceiver)>
  7019. request_func) {
  7020. Headers headers;
  7021. headers.emplace("X-Error-Test", "true");
  7022. std::string received_body;
  7023. auto receiver_failed = false;
  7024. auto res =
  7025. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7026. [&](const char *data, size_t data_length) {
  7027. received_body.append(data, data_length);
  7028. receiver_failed = true;
  7029. return false;
  7030. });
  7031. ASSERT_FALSE(res);
  7032. EXPECT_TRUE(receiver_failed);
  7033. }
  7034. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7035. #ifdef CPPHTTPLIB_SSL_ENABLED
  7036. using ClientT = SSLClient;
  7037. #else
  7038. using ClientT = Client;
  7039. #endif
  7040. TestWithHeadersAndContentReceiverError<ClientT>(
  7041. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7042. const std::string &body, const std::string &content_type,
  7043. ContentReceiver receiver) {
  7044. return cli.Post(path, headers, body, content_type, receiver);
  7045. });
  7046. }
  7047. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7048. #ifdef CPPHTTPLIB_SSL_ENABLED
  7049. using ClientT = SSLClient;
  7050. #else
  7051. using ClientT = Client;
  7052. #endif
  7053. TestWithHeadersAndContentReceiverError<ClientT>(
  7054. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7055. const std::string &body, const std::string &content_type,
  7056. ContentReceiver receiver) {
  7057. return cli.Put(path, headers, body, content_type, receiver);
  7058. });
  7059. }
  7060. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7061. #ifdef CPPHTTPLIB_SSL_ENABLED
  7062. using ClientT = SSLClient;
  7063. #else
  7064. using ClientT = Client;
  7065. #endif
  7066. TestWithHeadersAndContentReceiverError<ClientT>(
  7067. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7068. const std::string &body, const std::string &content_type,
  7069. ContentReceiver receiver) {
  7070. return cli.Patch(path, headers, body, content_type, receiver);
  7071. });
  7072. }
  7073. TEST_F(ServerTest, PostQueryStringAndBody) {
  7074. auto res =
  7075. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7077. ASSERT_EQ(StatusCode::OK_200, res->status);
  7078. }
  7079. TEST_F(ServerTest, HTTP2Magic) {
  7080. Request req;
  7081. req.method = "PRI";
  7082. req.path = "*";
  7083. req.body = "SM";
  7084. auto res = std::make_shared<Response>();
  7085. auto error = Error::Success;
  7086. auto ret = cli_.send(req, *res, error);
  7087. ASSERT_TRUE(ret);
  7088. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7089. }
  7090. TEST_F(ServerTest, KeepAlive) {
  7091. auto res = cli_.Get("/hi");
  7092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7093. EXPECT_EQ(StatusCode::OK_200, res->status);
  7094. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7095. EXPECT_EQ("Hello World!", res->body);
  7096. res = cli_.Get("/hi");
  7097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7098. EXPECT_EQ(StatusCode::OK_200, res->status);
  7099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7100. EXPECT_EQ("Hello World!", res->body);
  7101. res = cli_.Get("/hi");
  7102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7103. EXPECT_EQ(StatusCode::OK_200, res->status);
  7104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7105. EXPECT_EQ("Hello World!", res->body);
  7106. res = cli_.Get("/not-exist");
  7107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7108. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7109. res = cli_.Post("/empty", "", "text/plain");
  7110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7111. EXPECT_EQ(StatusCode::OK_200, res->status);
  7112. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7113. EXPECT_EQ("empty", res->body);
  7114. EXPECT_EQ("close", res->get_header_value("Connection"));
  7115. res = cli_.Post(
  7116. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7117. "text/plain");
  7118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7119. EXPECT_EQ(StatusCode::OK_200, res->status);
  7120. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7121. EXPECT_EQ("empty", res->body);
  7122. cli_.set_keep_alive(false);
  7123. res = cli_.Get("/last-request");
  7124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7125. EXPECT_EQ(StatusCode::OK_200, res->status);
  7126. EXPECT_EQ("close", res->get_header_value("Connection"));
  7127. }
  7128. TEST_F(ServerTest, TooManyRedirect) {
  7129. cli_.set_follow_location(true);
  7130. auto res = cli_.Get("/redirect/0");
  7131. ASSERT_TRUE(!res);
  7132. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7133. }
  7134. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7135. Request req;
  7136. req.method = "FOOBAR";
  7137. req.path = "/hi";
  7138. cli_.set_keep_alive(true);
  7139. auto res = cli_.send(req);
  7140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7141. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7142. EXPECT_EQ("close", res->get_header_value("Connection"));
  7143. EXPECT_FALSE(cli_.is_socket_open());
  7144. }
  7145. TEST_F(ServerTest, CustomRouteReadsBody) {
  7146. const std::string xml =
  7147. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7148. Request req;
  7149. req.method = "PROPFIND";
  7150. req.path = "/dav/dir";
  7151. req.set_header("Depth", "1");
  7152. req.body = xml;
  7153. auto res = cli_.send(req);
  7154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7155. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7156. EXPECT_EQ(xml, res->body);
  7157. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7158. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7159. }
  7160. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7161. Request req;
  7162. req.method = "PROPFIND";
  7163. req.path = "/dav/42";
  7164. auto res = cli_.send(req);
  7165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7166. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7167. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7168. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7169. }
  7170. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7171. Request req;
  7172. req.method = "PROPFIND";
  7173. req.path = "/dav-re/123";
  7174. auto res = cli_.send(req);
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7177. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7178. }
  7179. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7180. Request req;
  7181. req.method = "MKCOL";
  7182. req.path = "/dav-mkcol";
  7183. auto res = cli_.send(req);
  7184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7185. EXPECT_EQ(StatusCode::Created_201, res->status);
  7186. }
  7187. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7188. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7189. Request req;
  7190. req.method = "REPORT";
  7191. req.path = "/dav-report";
  7192. req.body = xml;
  7193. auto res = cli_.send(req);
  7194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7195. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7196. EXPECT_EQ(xml, res->body);
  7197. }
  7198. // A content reader route must fire even when the request carries no body,
  7199. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7200. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7201. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7202. Request req;
  7203. req.method = "REPORT";
  7204. req.path = "/dav-report";
  7205. auto res = cli_.send(req);
  7206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7207. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7208. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7209. }
  7210. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7211. Request req;
  7212. req.method = "PROPFIND";
  7213. req.path = "/not-dav";
  7214. auto res = cli_.send(req);
  7215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7216. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7217. }
  7218. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7219. Request req;
  7220. req.method = "UNLOCK";
  7221. req.path = "/dav/dir";
  7222. cli_.set_keep_alive(true);
  7223. auto res = cli_.send(req);
  7224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7225. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7226. EXPECT_EQ("close", res->get_header_value("Connection"));
  7227. EXPECT_FALSE(cli_.is_socket_open());
  7228. }
  7229. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7230. // The mount point serves this path, but only for GET and HEAD.
  7231. auto get_res = cli_.Get("/dir/index.html");
  7232. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7233. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7234. Request req;
  7235. req.method = "PROPFIND";
  7236. req.path = "/dir/index.html";
  7237. auto res = cli_.send(req);
  7238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7240. }
  7241. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7242. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7243. cli_.set_keep_alive(true);
  7244. for (auto i = 0; i < 2; i++) {
  7245. Request req;
  7246. req.method = "PROPFIND";
  7247. req.path = "/dav/dir";
  7248. req.body = xml;
  7249. auto res = cli_.send(req);
  7250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7251. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7252. EXPECT_EQ(xml, res->body);
  7253. EXPECT_TRUE(cli_.is_socket_open());
  7254. }
  7255. // A built-in method must still be served on the same connection.
  7256. cli_.set_keep_alive(false);
  7257. auto res = cli_.Get("/hi");
  7258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7259. EXPECT_EQ(StatusCode::OK_200, res->status);
  7260. EXPECT_EQ("close", res->get_header_value("Connection"));
  7261. }
  7262. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7263. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7264. Request req;
  7265. req.method = "PROPFIND";
  7266. req.path = "/dav/dir";
  7267. req.set_header("Expect", "100-continue");
  7268. req.body = xml;
  7269. auto res = cli_.send(req);
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7272. EXPECT_EQ(xml, res->body);
  7273. }
  7274. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7275. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7276. TEST_F(ServerTest, Gzip) {
  7277. Headers headers;
  7278. headers.emplace("Accept-Encoding", "gzip, deflate");
  7279. auto res = cli_.Get("/compress", headers);
  7280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7281. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7282. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7283. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7284. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7285. "7890123456789012345678901234567890",
  7286. res->body);
  7287. EXPECT_EQ(StatusCode::OK_200, res->status);
  7288. }
  7289. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7290. Headers headers;
  7291. headers.emplace("Accept-Encoding", "gzip, deflate");
  7292. auto res = cli_.Get("/compress-with-charset", headers);
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7295. EXPECT_EQ("application/json; charset=utf-8",
  7296. res->get_header_value("Content-Type"));
  7297. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7298. "7890123456789012345678901234567890",
  7299. res->body);
  7300. EXPECT_EQ(StatusCode::OK_200, res->status);
  7301. }
  7302. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7303. Headers headers;
  7304. headers.emplace("Accept-Encoding", "");
  7305. auto res = cli_.Get("/compress", headers);
  7306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7307. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7308. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7309. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7310. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7311. "7890123456789012345678901234567890",
  7312. res->body);
  7313. EXPECT_EQ(StatusCode::OK_200, res->status);
  7314. }
  7315. TEST_F(ServerTest, GzipWithContentReceiver) {
  7316. Headers headers;
  7317. headers.emplace("Accept-Encoding", "gzip, deflate");
  7318. std::string body;
  7319. auto res = cli_.Get("/compress", headers,
  7320. [&](const char *data, uint64_t data_length) {
  7321. EXPECT_EQ(100U, data_length);
  7322. body.append(data, data_length);
  7323. return true;
  7324. });
  7325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7326. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7327. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7328. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7329. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7330. "7890123456789012345678901234567890",
  7331. body);
  7332. EXPECT_EQ(StatusCode::OK_200, res->status);
  7333. }
  7334. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7335. Headers headers;
  7336. headers.emplace("Accept-Encoding", "gzip, deflate");
  7337. cli_.set_decompress(false);
  7338. auto res = cli_.Get("/compress", headers);
  7339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7340. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7341. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7342. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7343. EXPECT_EQ(33U, res->body.size());
  7344. EXPECT_EQ(StatusCode::OK_200, res->status);
  7345. }
  7346. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7347. Headers headers;
  7348. headers.emplace("Accept-Encoding", "");
  7349. std::string body;
  7350. auto res = cli_.Get("/compress", headers,
  7351. [&](const char *data, uint64_t data_length) {
  7352. EXPECT_EQ(100U, data_length);
  7353. body.append(data, data_length);
  7354. return true;
  7355. });
  7356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7357. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7358. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7359. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7360. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7361. "7890123456789012345678901234567890",
  7362. body);
  7363. EXPECT_EQ(StatusCode::OK_200, res->status);
  7364. }
  7365. TEST_F(ServerTest, NoGzip) {
  7366. Headers headers;
  7367. headers.emplace("Accept-Encoding", "gzip, deflate");
  7368. auto res = cli_.Get("/nocompress", headers);
  7369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7370. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7371. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7372. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7373. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7374. "7890123456789012345678901234567890",
  7375. res->body);
  7376. EXPECT_EQ(StatusCode::OK_200, res->status);
  7377. }
  7378. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7379. Headers headers;
  7380. headers.emplace("Accept-Encoding", "gzip, deflate");
  7381. std::string body;
  7382. auto res = cli_.Get("/nocompress", headers,
  7383. [&](const char *data, uint64_t data_length) {
  7384. EXPECT_EQ(100U, data_length);
  7385. body.append(data, data_length);
  7386. return true;
  7387. });
  7388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7389. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7390. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7391. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7392. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7393. "7890123456789012345678901234567890",
  7394. body);
  7395. EXPECT_EQ(StatusCode::OK_200, res->status);
  7396. }
  7397. TEST_F(ServerTest, MultipartFormDataGzip) {
  7398. UploadFormDataItems items = {
  7399. {"key1", "test", "", ""},
  7400. {"key2", "--abcdefg123", "", ""},
  7401. };
  7402. cli_.set_compress(true);
  7403. auto res = cli_.Post("/compress-multipart", items);
  7404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7405. EXPECT_EQ(StatusCode::OK_200, res->status);
  7406. }
  7407. #endif
  7408. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7409. TEST_F(ServerTest, Brotli) {
  7410. Headers headers;
  7411. headers.emplace("Accept-Encoding", "br");
  7412. auto res = cli_.Get("/compress", headers);
  7413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7414. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7415. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7416. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7417. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7418. "7890123456789012345678901234567890",
  7419. res->body);
  7420. EXPECT_EQ(StatusCode::OK_200, res->status);
  7421. }
  7422. #endif
  7423. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7424. TEST_F(ServerTest, Zstd) {
  7425. Headers headers;
  7426. headers.emplace("Accept-Encoding", "zstd");
  7427. auto res = cli_.Get("/compress", headers);
  7428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7429. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7430. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7431. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7432. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7433. "7890123456789012345678901234567890",
  7434. res->body);
  7435. EXPECT_EQ(StatusCode::OK_200, res->status);
  7436. }
  7437. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7438. Headers headers;
  7439. headers.emplace("Accept-Encoding", "");
  7440. auto res = cli_.Get("/compress", headers);
  7441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7442. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7443. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7444. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7445. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7446. "7890123456789012345678901234567890",
  7447. res->body);
  7448. EXPECT_EQ(StatusCode::OK_200, res->status);
  7449. }
  7450. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7451. Headers headers;
  7452. headers.emplace("Accept-Encoding", "zstd");
  7453. std::string body;
  7454. auto res = cli_.Get("/compress", headers,
  7455. [&](const char *data, uint64_t data_length) {
  7456. EXPECT_EQ(100U, data_length);
  7457. body.append(data, data_length);
  7458. return true;
  7459. });
  7460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7461. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7462. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7463. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7464. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7465. "7890123456789012345678901234567890",
  7466. body);
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. }
  7469. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7470. Headers headers;
  7471. headers.emplace("Accept-Encoding", "zstd");
  7472. cli_.set_decompress(false);
  7473. auto res = cli_.Get("/compress", headers);
  7474. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7475. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7476. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7477. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7479. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7480. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7481. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7482. EXPECT_EQ(StatusCode::OK_200, res->status);
  7483. ASSERT_EQ(26U, res->body.size());
  7484. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7485. 0);
  7486. }
  7487. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7488. Headers headers;
  7489. headers.emplace("Accept-Encoding", "");
  7490. std::string body;
  7491. auto res = cli_.Get("/compress", headers,
  7492. [&](const char *data, uint64_t data_length) {
  7493. EXPECT_EQ(100U, data_length);
  7494. body.append(data, data_length);
  7495. return true;
  7496. });
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7499. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7500. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7501. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7502. "7890123456789012345678901234567890",
  7503. body);
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. }
  7506. TEST_F(ServerTest, NoZstd) {
  7507. Headers headers;
  7508. headers.emplace("Accept-Encoding", "zstd");
  7509. auto res = cli_.Get("/nocompress", headers);
  7510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7511. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7512. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7513. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7514. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7515. "7890123456789012345678901234567890",
  7516. res->body);
  7517. EXPECT_EQ(StatusCode::OK_200, res->status);
  7518. }
  7519. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7520. Headers headers;
  7521. headers.emplace("Accept-Encoding", "zstd");
  7522. std::string body;
  7523. auto res = cli_.Get("/nocompress", headers,
  7524. [&](const char *data, uint64_t data_length) {
  7525. EXPECT_EQ(100U, data_length);
  7526. body.append(data, data_length);
  7527. return true;
  7528. });
  7529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7530. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7531. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7532. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7533. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7534. "7890123456789012345678901234567890",
  7535. body);
  7536. EXPECT_EQ(StatusCode::OK_200, res->status);
  7537. }
  7538. // TODO: How to enable zstd ??
  7539. TEST_F(ServerTest, MultipartFormDataZstd) {
  7540. UploadFormDataItems items = {
  7541. {"key1", "test", "", ""},
  7542. {"key2", "--abcdefg123", "", ""},
  7543. };
  7544. Headers headers;
  7545. headers.emplace("Accept-Encoding", "zstd");
  7546. cli_.set_compress(true);
  7547. auto res = cli_.Post("/compress-multipart", headers, items);
  7548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7549. EXPECT_EQ(StatusCode::OK_200, res->status);
  7550. }
  7551. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7552. Headers headers;
  7553. headers.emplace("Accept-Encoding", "zstd");
  7554. cli_.set_compress(true);
  7555. auto res = cli_.Put(
  7556. "/put", headers, 3,
  7557. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7558. sink.os << "PUT";
  7559. return true;
  7560. },
  7561. "text/plain");
  7562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7563. EXPECT_EQ(StatusCode::OK_200, res->status);
  7564. EXPECT_EQ("PUT", res->body);
  7565. }
  7566. // Pre-compression logging tests
  7567. TEST_F(ServerTest, PreCompressionLogging) {
  7568. // Test data for compression (matches the actual /compress endpoint content)
  7569. const std::string test_content =
  7570. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7571. "3456789012345678901234567890";
  7572. // Variables to capture logging data
  7573. std::string pre_compression_body;
  7574. std::string pre_compression_content_type;
  7575. std::string pre_compression_content_encoding;
  7576. std::string post_compression_body;
  7577. std::string post_compression_content_type;
  7578. std::string post_compression_content_encoding;
  7579. // Set up pre-compression logger
  7580. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7581. const Response &res) {
  7582. pre_compression_body = res.body;
  7583. pre_compression_content_type = res.get_header_value("Content-Type");
  7584. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7585. });
  7586. // Set up post-compression logger
  7587. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7588. post_compression_body = res.body;
  7589. post_compression_content_type = res.get_header_value("Content-Type");
  7590. post_compression_content_encoding =
  7591. res.get_header_value("Content-Encoding");
  7592. });
  7593. // Test with gzip compression
  7594. Headers headers;
  7595. headers.emplace("Accept-Encoding", "gzip");
  7596. auto res = cli_.Get("/compress", headers);
  7597. // Verify response was compressed
  7598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7599. EXPECT_EQ(StatusCode::OK_200, res->status);
  7600. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7601. // Verify pre-compression logger captured uncompressed content
  7602. EXPECT_EQ(test_content, pre_compression_body);
  7603. EXPECT_EQ("text/plain", pre_compression_content_type);
  7604. EXPECT_TRUE(pre_compression_content_encoding
  7605. .empty()); // No encoding header before compression
  7606. // Verify post-compression logger captured compressed content
  7607. EXPECT_NE(test_content,
  7608. post_compression_body); // Should be different after compression
  7609. EXPECT_EQ("text/plain", post_compression_content_type);
  7610. EXPECT_EQ("gzip", post_compression_content_encoding);
  7611. // Verify compressed content is smaller
  7612. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7613. }
  7614. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7615. const std::string test_content =
  7616. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7617. "3456789012345678901234567890";
  7618. std::string pre_compression_body;
  7619. std::string post_compression_body;
  7620. svr_.set_pre_compression_logger(
  7621. [&](const Request & /*req*/, const Response &res) {
  7622. pre_compression_body = res.body;
  7623. });
  7624. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7625. post_compression_body = res.body;
  7626. });
  7627. Headers headers;
  7628. headers.emplace("Accept-Encoding", "br");
  7629. auto res = cli_.Get("/compress", headers);
  7630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7631. EXPECT_EQ(StatusCode::OK_200, res->status);
  7632. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7633. // Verify pre-compression content is uncompressed
  7634. EXPECT_EQ(test_content, pre_compression_body);
  7635. // Verify post-compression content is compressed
  7636. EXPECT_NE(test_content, post_compression_body);
  7637. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7638. }
  7639. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7640. const std::string test_content =
  7641. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7642. "3456789012345678901234567890";
  7643. std::string pre_compression_body;
  7644. std::string post_compression_body;
  7645. svr_.set_pre_compression_logger(
  7646. [&](const Request & /*req*/, const Response &res) {
  7647. pre_compression_body = res.body;
  7648. });
  7649. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7650. post_compression_body = res.body;
  7651. });
  7652. // Request without compression (use /nocompress endpoint)
  7653. Headers headers;
  7654. auto res = cli_.Get("/nocompress", headers);
  7655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7656. EXPECT_EQ(StatusCode::OK_200, res->status);
  7657. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7658. // Pre-compression logger should not be called when no compression is applied
  7659. EXPECT_TRUE(
  7660. pre_compression_body.empty()); // Pre-compression logger not called
  7661. EXPECT_EQ(
  7662. test_content,
  7663. post_compression_body); // Post-compression logger captures final content
  7664. }
  7665. TEST_F(ServerTest, LoggerSeesContentLength) {
  7666. size_t logged_content_length = 0;
  7667. std::string logged_content_length_header;
  7668. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7669. logged_content_length = res.content_length_;
  7670. logged_content_length_header = res.get_header_value("Content-Length");
  7671. });
  7672. auto res = cli_.Get("/nocompress");
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ(res->body.size(), logged_content_length);
  7676. EXPECT_EQ(std::to_string(logged_content_length),
  7677. logged_content_length_header);
  7678. }
  7679. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7680. const std::string test_content =
  7681. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7682. "3456789012345678901234567890";
  7683. std::string pre_compression_body;
  7684. bool pre_logger_called = false;
  7685. // Set only pre-compression logger
  7686. svr_.set_pre_compression_logger(
  7687. [&](const Request & /*req*/, const Response &res) {
  7688. pre_compression_body = res.body;
  7689. pre_logger_called = true;
  7690. });
  7691. Headers headers;
  7692. headers.emplace("Accept-Encoding", "gzip");
  7693. auto res = cli_.Get("/compress", headers);
  7694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7695. EXPECT_EQ(StatusCode::OK_200, res->status);
  7696. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7697. // Verify pre-compression logger was called
  7698. EXPECT_TRUE(pre_logger_called);
  7699. EXPECT_EQ(test_content, pre_compression_body);
  7700. }
  7701. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7702. {
  7703. // Test with Expect: 100-continue header - success case
  7704. // Server returns 100 Continue, client sends body, server returns 200 OK
  7705. Request req;
  7706. req.method = "POST";
  7707. req.path = "/post-large";
  7708. req.set_header("Expect", "100-continue");
  7709. req.body = LARGE_DATA;
  7710. Response res;
  7711. auto error = Error::Success;
  7712. cli_.set_keep_alive(true);
  7713. auto ret = cli_.send(req, res, error);
  7714. EXPECT_TRUE(ret);
  7715. EXPECT_EQ(StatusCode::OK_200, res.status);
  7716. EXPECT_EQ(LARGE_DATA, res.body);
  7717. }
  7718. {
  7719. // Test with Expect: 100-continue header - error case
  7720. // Client should not send the body when server returns an error
  7721. Request req;
  7722. req.method = "POST";
  7723. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7724. req.set_header("Expect", "100-continue");
  7725. req.body = LARGE_DATA;
  7726. Response res;
  7727. auto error = Error::Success;
  7728. auto start = std::chrono::high_resolution_clock::now();
  7729. cli_.set_keep_alive(true);
  7730. auto ret = cli_.send(req, res, error);
  7731. auto end = std::chrono::high_resolution_clock::now();
  7732. auto elapsed =
  7733. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7734. .count();
  7735. // With Expect: 100-continue, request completes successfully but with error
  7736. EXPECT_TRUE(ret);
  7737. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7738. EXPECT_EQ("close", res.get_header_value("Connection"));
  7739. EXPECT_FALSE(cli_.is_socket_open());
  7740. EXPECT_LE(elapsed, 2000);
  7741. }
  7742. {
  7743. // Send an extra GET request to ensure error recovery without hanging
  7744. Request req;
  7745. req.method = "GET";
  7746. req.path = "/hi";
  7747. auto start = std::chrono::high_resolution_clock::now();
  7748. auto res = cli_.send(req);
  7749. auto end = std::chrono::high_resolution_clock::now();
  7750. auto elapsed =
  7751. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7752. .count();
  7753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7754. EXPECT_EQ(StatusCode::OK_200, res->status);
  7755. EXPECT_EQ("Hello World!", res->body);
  7756. EXPECT_LE(elapsed, 500);
  7757. }
  7758. }
  7759. TEST(ZstdDecompressor, ChunkedDecompression) {
  7760. std::string data;
  7761. for (size_t i = 0; i < 32 * 1024; ++i) {
  7762. data.push_back(static_cast<char>('a' + i % 26));
  7763. }
  7764. std::string compressed_data;
  7765. {
  7766. httplib::detail::zstd_compressor compressor;
  7767. bool result = compressor.compress(
  7768. data.data(), data.size(),
  7769. /*last=*/true,
  7770. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7771. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7772. compressed_data_size);
  7773. return true;
  7774. });
  7775. ASSERT_TRUE(result);
  7776. }
  7777. std::string decompressed_data;
  7778. {
  7779. httplib::detail::zstd_decompressor decompressor;
  7780. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7781. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7782. size_t chunk_size = 130;
  7783. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7784. chunk_begin += chunk_size) {
  7785. size_t current_chunk_size =
  7786. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7787. bool result = decompressor.decompress(
  7788. compressed_data.data() + chunk_begin, current_chunk_size,
  7789. [&](const char *decompressed_data_chunk,
  7790. size_t decompressed_data_chunk_size) {
  7791. decompressed_data.insert(decompressed_data.size(),
  7792. decompressed_data_chunk,
  7793. decompressed_data_chunk_size);
  7794. return true;
  7795. });
  7796. ASSERT_TRUE(result);
  7797. }
  7798. }
  7799. ASSERT_EQ(data, decompressed_data);
  7800. }
  7801. TEST(ZstdDecompressor, Decompress) {
  7802. std::string original_text = "Compressed with ZSTD";
  7803. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7804. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7805. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7806. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7807. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7808. std::string decompressed_data;
  7809. {
  7810. httplib::detail::zstd_decompressor decompressor;
  7811. bool result = decompressor.decompress(
  7812. compressed_data.data(), compressed_data.size(),
  7813. [&](const char *decompressed_data_chunk,
  7814. size_t decompressed_data_chunk_size) {
  7815. decompressed_data.insert(decompressed_data.size(),
  7816. decompressed_data_chunk,
  7817. decompressed_data_chunk_size);
  7818. return true;
  7819. });
  7820. ASSERT_TRUE(result);
  7821. }
  7822. ASSERT_EQ(original_text, decompressed_data);
  7823. }
  7824. #endif
  7825. // Sends a raw request to a server listening at HOST:PORT, writing it in
  7826. // separate chunks so that the server sees each part in its own read(). Used to
  7827. // place a read boundary at a specific offset of a request body.
  7828. static bool send_request_in_parts(time_t read_timeout_sec,
  7829. const std::vector<std::string> &parts,
  7830. std::string *resp = nullptr,
  7831. int port = PORT) {
  7832. auto error = Error::Success;
  7833. auto client_sock = detail::create_client_socket(
  7834. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7835. /*connection_timeout_sec=*/5, 0,
  7836. /*read_timeout_sec=*/5, 0,
  7837. /*write_timeout_sec=*/5, 0, std::string(), error);
  7838. if (client_sock == INVALID_SOCKET) { return false; }
  7839. auto ret = detail::process_client_socket(
  7840. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7841. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7842. for (size_t i = 0; i < parts.size(); i++) {
  7843. const auto &part = parts[i];
  7844. if (part.size() !=
  7845. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  7846. return false;
  7847. }
  7848. if (i + 1 < parts.size()) {
  7849. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7850. }
  7851. }
  7852. char buf[512];
  7853. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7854. while (line_reader.getline()) {
  7855. if (resp) { *resp += line_reader.ptr(); }
  7856. }
  7857. return true;
  7858. });
  7859. detail::close_socket(client_sock);
  7860. return ret;
  7861. }
  7862. // Sends a raw request to a server listening at HOST:PORT.
  7863. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7864. std::string *resp = nullptr, int port = PORT) {
  7865. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  7866. }
  7867. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7868. Server svr;
  7869. std::string header_value;
  7870. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7871. header_value = req.get_header_value("foo");
  7872. res.set_content("ok", "text/plain");
  7873. });
  7874. thread t = thread([&] { svr.listen(HOST, PORT); });
  7875. auto se = detail::scope_exit([&] {
  7876. svr.stop();
  7877. t.join();
  7878. ASSERT_FALSE(svr.is_running());
  7879. });
  7880. svr.wait_until_ready();
  7881. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7882. // like characters are not treated the same - use vertical tab and escape.
  7883. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7884. "foo: \t \v bar \x1B\t \r\n"
  7885. "Connection: close\r\n"
  7886. "\r\n";
  7887. std::string res;
  7888. ASSERT_TRUE(send_request(5, req, &res));
  7889. EXPECT_EQ(header_value, "");
  7890. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7891. }
  7892. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7893. Server svr;
  7894. std::string received;
  7895. svr.Get("/order", [&](const Request &req, Response &res) {
  7896. received = entries_to_string(req.headers);
  7897. res.set_content("ok", "text/plain");
  7898. });
  7899. auto port = svr.bind_to_any_port(HOST);
  7900. thread t = thread([&] { svr.listen_after_bind(); });
  7901. auto se = detail::scope_exit([&] {
  7902. svr.stop();
  7903. t.join();
  7904. ASSERT_FALSE(svr.is_running());
  7905. });
  7906. svr.wait_until_ready();
  7907. const std::string req = "GET /order HTTP/1.1\r\n"
  7908. "X-First: 1\r\n"
  7909. "X-Dup: a\r\n"
  7910. "X-Second: 2\r\n"
  7911. "X-Dup: b\r\n"
  7912. "Connection: close\r\n"
  7913. "\r\n";
  7914. std::string res;
  7915. ASSERT_TRUE(send_request(5, req, &res, port));
  7916. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7917. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7918. }
  7919. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7920. Server svr;
  7921. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7922. res.set_header("Set-Cookie", "first=1");
  7923. res.set_header("X-Between", "y");
  7924. res.set_header("Set-Cookie", "second=2");
  7925. res.set_content("ok", "text/plain");
  7926. });
  7927. auto port = svr.bind_to_any_port(HOST);
  7928. thread t = thread([&] { svr.listen_after_bind(); });
  7929. auto se = detail::scope_exit([&] {
  7930. svr.stop();
  7931. t.join();
  7932. ASSERT_FALSE(svr.is_running());
  7933. });
  7934. svr.wait_until_ready();
  7935. Client cli(HOST, port);
  7936. auto res = cli.Get("/cookies");
  7937. ASSERT_TRUE(res);
  7938. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7939. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7940. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7941. }
  7942. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7943. Server svr;
  7944. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7945. auto i = new int(0);
  7946. res.set_header("Trailer", "X-Safe, X-Reflected");
  7947. res.set_chunked_content_provider(
  7948. "text/plain",
  7949. [i](size_t /*offset*/, DataSink &sink) {
  7950. if (*i == 0) {
  7951. sink.os << "body";
  7952. } else {
  7953. Headers trailer;
  7954. // A valid trailer that must survive.
  7955. trailer.emplace("X-Safe", "safe");
  7956. // Attacker-controlled value carrying CR/LF (response splitting).
  7957. trailer.emplace("X-Reflected",
  7958. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7959. // Attacker-controlled name carrying CR/LF.
  7960. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7961. sink.done_with_trailer(trailer);
  7962. }
  7963. (*i)++;
  7964. return true;
  7965. },
  7966. [i](bool /*success*/) { delete i; });
  7967. });
  7968. thread t = thread([&] { svr.listen(HOST, PORT); });
  7969. auto se = detail::scope_exit([&] {
  7970. svr.stop();
  7971. t.join();
  7972. ASSERT_FALSE(svr.is_running());
  7973. });
  7974. svr.wait_until_ready();
  7975. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7976. "Host: " + HOST +
  7977. "\r\n"
  7978. "Connection: close\r\n"
  7979. "\r\n";
  7980. std::string res;
  7981. ASSERT_TRUE(send_request(5, req, &res));
  7982. // The injected fields must not appear anywhere in the raw response.
  7983. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7984. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7985. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7986. // Invalid trailers are dropped entirely, matching set_header().
  7987. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7988. // The valid trailer still passes through.
  7989. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7990. }
  7991. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7992. Server svr;
  7993. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7994. // res.headers is a public field an application can populate directly,
  7995. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7996. // A valid header that must survive.
  7997. res.headers.emplace("X-Safe", "safe");
  7998. // Attacker-controlled value carrying CR/LF (response splitting).
  7999. res.headers.emplace("X-Reflected",
  8000. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8001. // Attacker-controlled name carrying CR/LF.
  8002. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8003. res.set_content("body", "text/plain");
  8004. });
  8005. thread t = thread([&] { svr.listen(HOST, PORT); });
  8006. auto se = detail::scope_exit([&] {
  8007. svr.stop();
  8008. t.join();
  8009. ASSERT_FALSE(svr.is_running());
  8010. });
  8011. svr.wait_until_ready();
  8012. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8013. "Host: " + HOST +
  8014. "\r\n"
  8015. "Connection: close\r\n"
  8016. "\r\n";
  8017. std::string res;
  8018. ASSERT_TRUE(send_request(5, req, &res));
  8019. // The injected fields must not appear anywhere in the raw response.
  8020. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8021. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8022. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8023. // Invalid headers are dropped entirely, matching set_header().
  8024. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8025. // The valid header still passes through.
  8026. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8027. }
  8028. // Forward declaration: in split builds split.py strips `inline` and moves the
  8029. // definition into httplib.cc, so detail::write_request_line is not visible from
  8030. // the public httplib.h. Re-declaring it here lets the tests link against the
  8031. // symbol in both header-only and split builds.
  8032. namespace httplib {
  8033. namespace detail {
  8034. ssize_t write_request_line(Stream &strm, const std::string &method,
  8035. const std::string &path);
  8036. } // namespace detail
  8037. } // namespace httplib
  8038. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  8039. // A well-formed target is written verbatim.
  8040. {
  8041. detail::BufferStream strm;
  8042. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8043. EXPECT_GT(n, 0);
  8044. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8045. }
  8046. // A target carrying CR/LF must be rejected before anything reaches the wire,
  8047. // otherwise it splits the request line and injects a header or a whole
  8048. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  8049. // when path encoding is disabled.
  8050. const std::string evil_targets[] = {
  8051. "/a\r\nInjected: pwned",
  8052. "/a\rInjected",
  8053. "/a\nInjected",
  8054. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8055. };
  8056. for (const auto &evil : evil_targets) {
  8057. detail::BufferStream strm;
  8058. auto n = detail::write_request_line(strm, "GET", evil);
  8059. EXPECT_LT(n, 0);
  8060. EXPECT_TRUE(strm.get_buffer().empty());
  8061. }
  8062. }
  8063. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8064. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  8065. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  8066. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  8067. // client must fail cleanly with Error::Write instead of putting a
  8068. // request-line-less, header-injecting request on the wire.
  8069. Server svr;
  8070. svr.Get("/a", [](const Request &, Response &res) {
  8071. res.set_content("ok", "text/plain");
  8072. });
  8073. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8074. auto se = detail::scope_exit([&] {
  8075. svr.stop();
  8076. thread.join();
  8077. ASSERT_FALSE(svr.is_running());
  8078. });
  8079. svr.wait_until_ready();
  8080. {
  8081. Client cli(HOST, PORT);
  8082. cli.set_path_encode(false);
  8083. // The request is rejected before anything is written, so the connection
  8084. // stays silent and the subsequent response read would otherwise block for
  8085. // the full default read timeout. Shorten it -- the assertion is on the
  8086. // error, not the timeout.
  8087. cli.set_read_timeout(1, 0);
  8088. auto res = cli.Get("/a\r\nInjected: pwned");
  8089. EXPECT_FALSE(res);
  8090. EXPECT_EQ(Error::Write, res.error());
  8091. }
  8092. }
  8093. // Sends a raw request and verifies that there isn't a crash or exception.
  8094. static void test_raw_request(const std::string &req,
  8095. std::string *out = nullptr) {
  8096. Server svr;
  8097. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8098. res.set_content("ok", "text/plain");
  8099. });
  8100. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8101. res.set_content("ok", "text/plain");
  8102. });
  8103. svr.Get("/header_field_value_check",
  8104. [&](const Request & /*req*/, Response &res) {
  8105. res.set_content("ok", "text/plain");
  8106. });
  8107. svr.CustomRoute("PROPFIND", "/dav",
  8108. [&](const Request & /*req*/, Response &res) {
  8109. res.status = StatusCode::MultiStatus_207;
  8110. });
  8111. // Server read timeout must be longer than the client read timeout for the
  8112. // bug to reproduce, probably to force the server to process a request
  8113. // without a trailing blank line.
  8114. const time_t client_read_timeout_sec = 1;
  8115. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8116. bool listen_thread_ok = false;
  8117. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8118. auto se = detail::scope_exit([&] {
  8119. svr.stop();
  8120. t.join();
  8121. ASSERT_FALSE(svr.is_running());
  8122. EXPECT_TRUE(listen_thread_ok);
  8123. });
  8124. svr.wait_until_ready();
  8125. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8126. }
  8127. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8128. // A certain header line causes an exception if the header property is parsed
  8129. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8130. test_raw_request(
  8131. "GET /hi HTTP/1.1\r\n"
  8132. " : "
  8133. " "
  8134. " ");
  8135. }
  8136. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8137. // A certain header line causes an exception if the header property *name* is
  8138. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8139. // greedy matcher and requires backtracking when there are a lot of ":"
  8140. // characters.
  8141. // This occurs with libc++ but not libstdc++.
  8142. test_raw_request(
  8143. "GET /hi HTTP/1.1\r\n"
  8144. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8145. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8146. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8147. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8148. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8149. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8150. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8151. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8152. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8153. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8154. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8155. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8156. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8157. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8158. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8159. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8160. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8161. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8162. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8163. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8164. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8165. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8166. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8167. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8168. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8169. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8170. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8171. "&&&%%%");
  8172. }
  8173. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8174. // Make sure this doesn't crash the server.
  8175. // In a previous version of the header line regex, the "\r" rendered the line
  8176. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8177. // a new position where the leading white space ended and the field value
  8178. // began.
  8179. // The crash occurs with libc++ but not libstdc++.
  8180. test_raw_request("GET /hi HTTP/1.1\r\n"
  8181. "a:" +
  8182. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8183. "\r\n"
  8184. "\r\n");
  8185. }
  8186. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8187. std::string out;
  8188. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8189. "Content-Type: text/plain\r\n"
  8190. "Transfer-Encoding: chunked\r\n"
  8191. "\r\n"
  8192. "nothex\r\n",
  8193. &out);
  8194. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8195. }
  8196. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8197. std::string out;
  8198. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8199. "Content-Type: text/plain\r\n"
  8200. "Transfer-Encoding: chunked\r\n"
  8201. "\r\n"
  8202. "3\r\n"
  8203. "xyz\r\n"
  8204. "NaN\r\n",
  8205. &out);
  8206. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8207. }
  8208. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8209. std::string out;
  8210. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8211. "Content-Type: text/plain\r\n"
  8212. "Transfer-Encoding: chunked\r\n"
  8213. "\r\n"
  8214. // Length is too large for 64 bits.
  8215. "1ffffffffffffffff\r\n"
  8216. "xyz\r\n",
  8217. &out);
  8218. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8219. }
  8220. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8221. test_raw_request("GET /hi HTTP/1.1\r\n"
  8222. "Content-Type: text/plain\r\n\r");
  8223. }
  8224. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8225. std::string out;
  8226. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8227. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8228. }
  8229. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8230. Server svr;
  8231. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8232. EXPECT_TRUE(!req.remote_addr.empty());
  8233. });
  8234. thread t = thread([&] { svr.listen(HOST, PORT); });
  8235. auto se = detail::scope_exit([&] {
  8236. svr.stop();
  8237. t.join();
  8238. ASSERT_FALSE(svr.is_running());
  8239. });
  8240. svr.wait_until_ready();
  8241. // Send an invalid request line to trigger Bad Request
  8242. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8243. std::string out;
  8244. ASSERT_TRUE(send_request(5, bad_req, &out));
  8245. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8246. }
  8247. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8248. // answered right away rather than blocking on a read that waits for EOF.
  8249. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8250. std::string out;
  8251. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8252. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8253. }
  8254. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8255. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8256. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8257. for (const auto *method : methods) {
  8258. Server svr;
  8259. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8260. EXPECT_FALSE(svr.is_valid()) << method;
  8261. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8262. }
  8263. }
  8264. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8265. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8266. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8267. for (const auto *method : methods) {
  8268. Server svr;
  8269. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8270. EXPECT_FALSE(svr.is_valid()) << method;
  8271. }
  8272. }
  8273. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8274. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8275. "COPY", "MOVE", "LOCK",
  8276. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8277. Server svr;
  8278. for (const auto *method : methods) {
  8279. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8280. }
  8281. EXPECT_TRUE(svr.is_valid());
  8282. }
  8283. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8284. Server svr;
  8285. svr.CustomRoute("POST", "/x",
  8286. [](const Request &, Response &, const ContentReader &) {});
  8287. EXPECT_FALSE(svr.is_valid());
  8288. }
  8289. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8290. Server svr;
  8291. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8292. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8293. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8294. EXPECT_FALSE(svr.is_valid());
  8295. }
  8296. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8297. Server svr;
  8298. auto captured = Error::Success;
  8299. svr.set_error_logger(
  8300. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8301. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8302. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8303. }
  8304. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8305. std::string out;
  8306. std::string request(
  8307. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8308. test_raw_request(request, &out);
  8309. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8310. }
  8311. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8312. std::string out;
  8313. std::string request(
  8314. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8315. test_raw_request(request, &out);
  8316. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8317. }
  8318. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8319. std::string out;
  8320. std::string request(
  8321. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8322. test_raw_request(request, &out);
  8323. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8324. }
  8325. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8326. std::string out;
  8327. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8328. "Test: \r\n\r\n",
  8329. &out);
  8330. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8331. }
  8332. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8333. Server svr;
  8334. std::string x_custom;
  8335. std::string cookie;
  8336. std::string xff;
  8337. std::string x_unicode;
  8338. std::string x_iis;
  8339. svr.Get("/check", [&](const Request &req, Response &res) {
  8340. x_custom = req.get_header_value("X-Custom");
  8341. cookie = req.get_header_value("Cookie");
  8342. xff = req.get_header_value("X-Forwarded-For");
  8343. x_unicode = req.get_header_value("X-Unicode");
  8344. x_iis = req.get_header_value("X-IIS");
  8345. res.set_content("ok", "text/plain");
  8346. });
  8347. thread t = thread([&] { svr.listen(HOST, PORT); });
  8348. auto se = detail::scope_exit([&] {
  8349. svr.stop();
  8350. t.join();
  8351. ASSERT_FALSE(svr.is_running());
  8352. });
  8353. svr.wait_until_ready();
  8354. const std::string req = "GET /check HTTP/1.1\r\n"
  8355. "Host: localhost\r\n"
  8356. "X-Custom: a%0D%0AInjected: b\r\n"
  8357. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8358. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8359. "X-Unicode: %E3%81%82\r\n"
  8360. "X-IIS: %u00E9\r\n"
  8361. "Connection: close\r\n"
  8362. "\r\n";
  8363. std::string res;
  8364. ASSERT_TRUE(send_request(5, req, &res));
  8365. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8366. // Every value must be returned verbatim (wire form), with no decoding.
  8367. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8368. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8369. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8370. EXPECT_EQ("%E3%81%82", x_unicode);
  8371. EXPECT_EQ("%u00E9", x_iis);
  8372. }
  8373. // Applications that previously relied on automatic percent-decoding can
  8374. // reproduce the old behavior by explicitly calling decode_path_component()
  8375. // or, for RFC 3986 conformance, decode_uri_component().
  8376. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8377. Server svr;
  8378. std::string decoded;
  8379. svr.Get("/check", [&](const Request &req, Response &res) {
  8380. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8381. res.set_content("ok", "text/plain");
  8382. });
  8383. thread t = thread([&] { svr.listen(HOST, PORT); });
  8384. auto se = detail::scope_exit([&] {
  8385. svr.stop();
  8386. t.join();
  8387. ASSERT_FALSE(svr.is_running());
  8388. });
  8389. svr.wait_until_ready();
  8390. const std::string req = "GET /check HTTP/1.1\r\n"
  8391. "Host: localhost\r\n"
  8392. "X-Custom: hello%20world\r\n"
  8393. "Connection: close\r\n"
  8394. "\r\n";
  8395. std::string res;
  8396. ASSERT_TRUE(send_request(5, req, &res));
  8397. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8398. EXPECT_EQ("hello world", decoded);
  8399. }
  8400. // Regression test for #2033. Browsers send Referer values that include
  8401. // percent-encoded characters such as %0A inside the URL. Decoding the
  8402. // header value would either trip the post-decode CR/LF/NUL guard (the
  8403. // original bug, returning 400) or, after that guard was relaxed, silently
  8404. // store a literal LF — both unacceptable. The wire form must round-trip.
  8405. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8406. Server svr;
  8407. std::string referer;
  8408. svr.Get("/check", [&](const Request &req, Response &res) {
  8409. referer = req.get_header_value("Referer");
  8410. res.set_content("ok", "text/plain");
  8411. });
  8412. thread t = thread([&] { svr.listen(HOST, PORT); });
  8413. auto se = detail::scope_exit([&] {
  8414. svr.stop();
  8415. t.join();
  8416. ASSERT_FALSE(svr.is_running());
  8417. });
  8418. svr.wait_until_ready();
  8419. const std::string req = "GET /check HTTP/1.1\r\n"
  8420. "Host: localhost\r\n"
  8421. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8422. "Connection: close\r\n"
  8423. "\r\n";
  8424. std::string res;
  8425. ASSERT_TRUE(send_request(5, req, &res));
  8426. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8427. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8428. }
  8429. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8430. Server svr;
  8431. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8432. res.set_header("Cache-Control", "no-cache");
  8433. res.set_chunked_content_provider(
  8434. "text/event-stream", [](size_t offset, DataSink &sink) {
  8435. std::string s = "data:";
  8436. s += std::to_string(offset);
  8437. s += "\n\n";
  8438. auto ret = sink.write(s.data(), s.size());
  8439. EXPECT_TRUE(ret);
  8440. std::this_thread::sleep_for(std::chrono::seconds(1));
  8441. return true;
  8442. });
  8443. });
  8444. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8445. svr.wait_until_ready();
  8446. Client client(HOST, PORT);
  8447. const Headers headers = {{"Accept", "text/event-stream"}};
  8448. auto get_thread = std::thread([&client, &headers]() {
  8449. auto res = client.Get(
  8450. "/events", headers,
  8451. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8452. });
  8453. auto se = detail::scope_exit([&] {
  8454. svr.stop();
  8455. get_thread.join();
  8456. listen_thread.join();
  8457. ASSERT_FALSE(svr.is_running());
  8458. });
  8459. // Give GET time to get a few messages.
  8460. std::this_thread::sleep_for(std::chrono::seconds(2));
  8461. }
  8462. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8463. httplib::Server svr;
  8464. svr.Post("/hi",
  8465. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8466. res.status = StatusCode::OK_200;
  8467. });
  8468. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8469. svr.wait_until_ready();
  8470. Client cli(HOST, PORT);
  8471. auto res = cli.Post("/hi", "data", "text/plain");
  8472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8473. EXPECT_EQ(StatusCode::OK_200, res->status);
  8474. svr.stop();
  8475. thread.join();
  8476. ASSERT_FALSE(svr.is_running());
  8477. res = cli.Post("/hi", "data", "text/plain");
  8478. ASSERT_FALSE(res);
  8479. }
  8480. TEST(ServerStopTest, ListenFailure) {
  8481. Server svr;
  8482. auto t = thread([&]() {
  8483. auto ret = svr.listen("????", PORT);
  8484. EXPECT_FALSE(ret);
  8485. });
  8486. svr.wait_until_ready();
  8487. svr.stop();
  8488. t.join();
  8489. }
  8490. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8491. TEST(ServerStopTest, Decommision) {
  8492. Server svr;
  8493. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8494. for (int i = 0; i < 4; i++) {
  8495. auto is_even = !(i % 2);
  8496. std::thread t{[&] {
  8497. try {
  8498. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8499. if (is_even) {
  8500. throw std::runtime_error("Some thing that happens to go wrong.");
  8501. }
  8502. svr.listen(HOST, PORT);
  8503. } catch (...) { svr.decommission(); }
  8504. }};
  8505. svr.wait_until_ready();
  8506. // Server is up
  8507. {
  8508. Client cli(HOST, PORT);
  8509. auto res = cli.Get("/hi");
  8510. if (is_even) {
  8511. EXPECT_FALSE(res);
  8512. } else {
  8513. EXPECT_TRUE(res);
  8514. EXPECT_EQ("hi...", res->body);
  8515. }
  8516. }
  8517. svr.stop();
  8518. t.join();
  8519. // Server is down...
  8520. {
  8521. Client cli(HOST, PORT);
  8522. auto res = cli.Get("/hi");
  8523. EXPECT_FALSE(res);
  8524. }
  8525. }
  8526. }
  8527. #endif
  8528. // Helper function for string body upload progress tests
  8529. template <typename SetupHandler, typename ClientCall>
  8530. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  8531. ClientCall &&client_call,
  8532. const string &body) {
  8533. Server svr;
  8534. setup_handler(svr);
  8535. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8536. auto se = detail::scope_exit([&] {
  8537. svr.stop();
  8538. t.join();
  8539. });
  8540. svr.wait_until_ready();
  8541. Client cli(HOST, PORT);
  8542. vector<uint64_t> progress_values;
  8543. bool progress_called = false;
  8544. auto res =
  8545. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8546. progress_values.push_back(current);
  8547. progress_called = true;
  8548. return true;
  8549. });
  8550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8551. EXPECT_EQ(200, res->status);
  8552. EXPECT_TRUE(progress_called);
  8553. }
  8554. TEST(UploadProgressTest, PostStringBodyBasic) {
  8555. TestStringBodyUploadProgress(
  8556. [](Server &svr) {
  8557. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8558. res.set_content("received", "text/plain");
  8559. });
  8560. },
  8561. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8562. return cli.Post("/test", body, "text/plain", progress_callback);
  8563. },
  8564. "test data for upload progress");
  8565. }
  8566. TEST(UploadProgressTest, PutStringBodyBasic) {
  8567. TestStringBodyUploadProgress(
  8568. [](Server &svr) {
  8569. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  8570. res.set_content("put received", "text/plain");
  8571. });
  8572. },
  8573. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8574. return cli.Put("/test", body, "text/plain", progress_callback);
  8575. },
  8576. "put test data for upload progress");
  8577. }
  8578. TEST(UploadProgressTest, PatchStringBodyBasic) {
  8579. TestStringBodyUploadProgress(
  8580. [](Server &svr) {
  8581. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  8582. res.set_content("patch received", "text/plain");
  8583. });
  8584. },
  8585. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8586. return cli.Patch("/test", body, "text/plain", progress_callback);
  8587. },
  8588. "patch test data for upload progress");
  8589. }
  8590. // Helper function for content provider upload progress tests
  8591. template <typename SetupHandler, typename ClientCall>
  8592. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  8593. ClientCall &&client_call) {
  8594. Server svr;
  8595. setup_handler(svr);
  8596. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8597. auto se = detail::scope_exit([&] {
  8598. svr.stop();
  8599. t.join();
  8600. });
  8601. svr.wait_until_ready();
  8602. Client cli(HOST, PORT);
  8603. vector<uint64_t> progress_values;
  8604. auto res =
  8605. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8606. progress_values.push_back(current);
  8607. return true;
  8608. });
  8609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8610. EXPECT_EQ(200, res->status);
  8611. EXPECT_FALSE(progress_values.empty());
  8612. }
  8613. TEST(UploadProgressTest, PostContentProviderProgress) {
  8614. TestContentProviderUploadProgress(
  8615. [](Server &svr) {
  8616. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8617. res.set_content("provider received", "text/plain");
  8618. });
  8619. },
  8620. [](Client &cli, UploadProgress progress_callback) {
  8621. return cli.Post(
  8622. "/test", 10,
  8623. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  8624. sink.os << "test data";
  8625. return true;
  8626. },
  8627. "text/plain", progress_callback);
  8628. });
  8629. }
  8630. // Helper function for multipart upload progress tests
  8631. template <typename SetupHandler, typename ClientCall>
  8632. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  8633. ClientCall &&client_call,
  8634. const string &endpoint) {
  8635. Server svr;
  8636. setup_handler(svr);
  8637. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8638. auto se = detail::scope_exit([&] {
  8639. svr.stop();
  8640. t.join();
  8641. });
  8642. svr.wait_until_ready();
  8643. Client cli(HOST, PORT);
  8644. vector<uint64_t> progress_values;
  8645. UploadFormDataItems items = {
  8646. {"field1", "value1", "", ""},
  8647. {"field2", "longer value for progress tracking test", "", ""},
  8648. {"file1", "file content data for upload progress", "test.txt",
  8649. "text/plain"}};
  8650. auto res = client_call(cli, endpoint, items,
  8651. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8652. progress_values.push_back(current);
  8653. return true;
  8654. });
  8655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8656. EXPECT_EQ(200, res->status);
  8657. EXPECT_FALSE(progress_values.empty());
  8658. }
  8659. TEST(UploadProgressTest, PostMultipartProgress) {
  8660. TestMultipartUploadProgress(
  8661. [](Server &svr) {
  8662. svr.Post("/multipart", [](const Request &req, Response &res) {
  8663. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8664. res.set_content("multipart received", "text/plain");
  8665. });
  8666. },
  8667. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8668. UploadProgress progress_callback) {
  8669. return cli.Post(endpoint, items, progress_callback);
  8670. },
  8671. "/multipart");
  8672. }
  8673. // Helper function for basic download progress tests
  8674. template <typename SetupHandler, typename ClientCall>
  8675. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8676. ClientCall &&client_call, const string &endpoint,
  8677. size_t expected_content_size) {
  8678. Server svr;
  8679. setup_handler(svr);
  8680. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8681. auto se = detail::scope_exit([&] {
  8682. svr.stop();
  8683. t.join();
  8684. });
  8685. svr.wait_until_ready();
  8686. Client cli(HOST, PORT);
  8687. vector<uint64_t> progress_values;
  8688. auto res = client_call(cli, endpoint,
  8689. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8690. progress_values.push_back(current);
  8691. return true;
  8692. });
  8693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8694. EXPECT_EQ(200, res->status);
  8695. EXPECT_FALSE(progress_values.empty());
  8696. EXPECT_EQ(expected_content_size, res->body.size());
  8697. }
  8698. TEST(DownloadProgressTest, GetBasic) {
  8699. TestBasicDownloadProgress(
  8700. [](Server &svr) {
  8701. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8702. string content(1000, 'D');
  8703. res.set_content(content, "text/plain");
  8704. });
  8705. },
  8706. [](Client &cli, const string &endpoint,
  8707. DownloadProgress progress_callback) {
  8708. return cli.Get(endpoint, progress_callback);
  8709. },
  8710. "/download", 1000u);
  8711. }
  8712. // Helper function for content receiver download progress tests
  8713. template <typename SetupHandler, typename ClientCall>
  8714. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8715. ClientCall &&client_call,
  8716. const string &endpoint,
  8717. size_t expected_content_size) {
  8718. Server svr;
  8719. setup_handler(svr);
  8720. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8721. auto se = detail::scope_exit([&] {
  8722. svr.stop();
  8723. t.join();
  8724. });
  8725. svr.wait_until_ready();
  8726. Client cli(HOST, PORT);
  8727. vector<uint64_t> progress_values;
  8728. string received_body;
  8729. auto res = client_call(
  8730. cli, endpoint,
  8731. [&](const char *data, size_t data_length) -> bool {
  8732. received_body.append(data, data_length);
  8733. return true;
  8734. },
  8735. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8736. progress_values.push_back(current);
  8737. return true;
  8738. });
  8739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8740. EXPECT_EQ(200, res->status);
  8741. EXPECT_FALSE(progress_values.empty());
  8742. EXPECT_EQ(expected_content_size, received_body.size());
  8743. EXPECT_TRUE(res->body.empty());
  8744. }
  8745. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8746. TestContentReceiverDownloadProgress(
  8747. [](Server &svr) {
  8748. svr.Get("/download-receiver",
  8749. [](const Request & /*req*/, Response &res) {
  8750. string content(2000, 'R');
  8751. res.set_content(content, "text/plain");
  8752. });
  8753. },
  8754. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8755. DownloadProgress progress_callback) {
  8756. return cli.Get(endpoint, content_receiver, progress_callback);
  8757. },
  8758. "/download-receiver", 2000u);
  8759. }
  8760. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  8761. // A provider reaching a pass with nothing to hand over - an empty buffer
  8762. // popped off a queue, say - must not be taken to mean the body is finished.
  8763. // It used to end the loop with the terminating chunk unwritten while the
  8764. // server still considered the response complete, so the peer waited for an
  8765. // end that never arrived.
  8766. Server svr;
  8767. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8768. auto step = std::make_shared<int>(0);
  8769. res.set_chunked_content_provider("text/plain",
  8770. [step](size_t /*offset*/, DataSink &sink) {
  8771. switch ((*step)++) {
  8772. case 0: sink.write("", 0); break;
  8773. case 1: sink.write("hello", 5); break;
  8774. default: sink.done(); break;
  8775. }
  8776. return true;
  8777. });
  8778. });
  8779. auto port = svr.bind_to_any_port(HOST);
  8780. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8781. auto listen_se = detail::scope_exit([&] {
  8782. svr.stop();
  8783. listen_thread.join();
  8784. ASSERT_FALSE(svr.is_running());
  8785. });
  8786. svr.wait_until_ready();
  8787. Client cli(HOST, port);
  8788. // Without the fix the body is never terminated, so bound the wait rather
  8789. // than letting the test hang on the default read timeout.
  8790. cli.set_read_timeout(5, 0);
  8791. auto res = cli.Get("/stream");
  8792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8793. EXPECT_EQ(StatusCode::OK_200, res->status);
  8794. EXPECT_EQ("hello", res->body);
  8795. }
  8796. TEST(StreamingTest, NoContentLengthStreaming) {
  8797. Server svr;
  8798. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8799. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8800. if (offset < 6) {
  8801. sink.os << (offset < 3 ? "a" : "b");
  8802. } else {
  8803. sink.done();
  8804. }
  8805. return true;
  8806. });
  8807. });
  8808. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8809. auto listen_se = detail::scope_exit([&] {
  8810. svr.stop();
  8811. listen_thread.join();
  8812. ASSERT_FALSE(svr.is_running());
  8813. });
  8814. svr.wait_until_ready();
  8815. Client client(HOST, PORT);
  8816. auto get_thread = std::thread([&client]() {
  8817. std::string s;
  8818. auto res =
  8819. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8820. s += std::string(data, len);
  8821. return true;
  8822. });
  8823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8824. EXPECT_EQ(StatusCode::OK_200, res->status);
  8825. EXPECT_EQ("aaabbb", s);
  8826. });
  8827. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8828. // Give GET time to get a few messages.
  8829. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8830. }
  8831. TEST(MountTest, Unmount) {
  8832. Server svr;
  8833. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8834. auto se = detail::scope_exit([&] {
  8835. svr.stop();
  8836. listen_thread.join();
  8837. ASSERT_FALSE(svr.is_running());
  8838. });
  8839. svr.wait_until_ready();
  8840. Client cli("localhost", PORT);
  8841. svr.set_mount_point("/mount2", "./www2");
  8842. auto res = cli.Get("/");
  8843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8844. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8845. res = cli.Get("/mount2/dir/test.html");
  8846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8847. EXPECT_EQ(StatusCode::OK_200, res->status);
  8848. svr.set_mount_point("/", "./www");
  8849. res = cli.Get("/dir/");
  8850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8851. EXPECT_EQ(StatusCode::OK_200, res->status);
  8852. svr.remove_mount_point("/");
  8853. res = cli.Get("/dir/");
  8854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8855. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8856. svr.remove_mount_point("/mount2");
  8857. res = cli.Get("/mount2/dir/test.html");
  8858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8860. }
  8861. TEST(MountTest, PathSegmentBoundary) {
  8862. Server svr;
  8863. svr.set_mount_point("/mount2", "./www2");
  8864. svr.set_mount_point("/", "./www");
  8865. auto port = svr.bind_to_any_port(HOST);
  8866. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8867. auto se = detail::scope_exit([&] {
  8868. svr.stop();
  8869. listen_thread.join();
  8870. ASSERT_FALSE(svr.is_running());
  8871. });
  8872. svr.wait_until_ready();
  8873. Client cli(HOST, port);
  8874. auto res = cli.Get("/mount2/dir/test.html");
  8875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8876. EXPECT_EQ(StatusCode::OK_200, res->status);
  8877. // "/mount2" must not match part-way through a path segment.
  8878. res = cli.Get("/mount2dir/test.html");
  8879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8880. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8881. // A mount point ending in '/' keeps matching every path below it.
  8882. res = cli.Get("/dir/test.html");
  8883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8884. EXPECT_EQ(StatusCode::OK_200, res->status);
  8885. }
  8886. TEST(MountTest, Redicect) {
  8887. Server svr;
  8888. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8889. auto se = detail::scope_exit([&] {
  8890. svr.stop();
  8891. listen_thread.join();
  8892. ASSERT_FALSE(svr.is_running());
  8893. });
  8894. svr.set_mount_point("/", "./www");
  8895. svr.wait_until_ready();
  8896. Client cli("localhost", PORT);
  8897. auto res = cli.Get("/dir/");
  8898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. res = cli.Get("/dir");
  8901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8902. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8903. res = cli.Get("/file");
  8904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8905. EXPECT_EQ(StatusCode::OK_200, res->status);
  8906. res = cli.Get("/file/");
  8907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8908. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8909. cli.set_follow_location(true);
  8910. res = cli.Get("/dir");
  8911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8912. EXPECT_EQ(StatusCode::OK_200, res->status);
  8913. }
  8914. TEST(MountTest, MultibytesPathName) {
  8915. Server svr;
  8916. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8917. auto se = detail::scope_exit([&] {
  8918. svr.stop();
  8919. listen_thread.join();
  8920. ASSERT_FALSE(svr.is_running());
  8921. });
  8922. svr.set_mount_point("/", "./www");
  8923. svr.wait_until_ready();
  8924. Client cli("localhost", PORT);
  8925. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8927. EXPECT_EQ(StatusCode::OK_200, res->status);
  8928. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8929. }
  8930. #ifdef _WIN32
  8931. // Issue #2435: mmap::open() must succeed even when another handle holds
  8932. // the file open for writing (e.g. an active log file).
  8933. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8934. const char *path = "mmap_concurrent_writer_test.txt";
  8935. const char *content = "hello";
  8936. {
  8937. std::ofstream f(path, std::ios::binary);
  8938. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8939. }
  8940. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8941. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8942. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8943. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8944. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8945. detail::mmap m(path);
  8946. ASSERT_TRUE(m.is_open());
  8947. EXPECT_EQ(strlen(content), m.size());
  8948. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8949. }
  8950. #endif
  8951. #ifndef _WIN32
  8952. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8953. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8954. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8955. TEST(MmapTest, FailedMappingIsNotOpen) {
  8956. const char *path = "./mmap_failed_mapping_test_dir";
  8957. ASSERT_EQ(0, ::mkdir(path, 0755));
  8958. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8959. detail::mmap m(path);
  8960. EXPECT_FALSE(m.is_open());
  8961. EXPECT_EQ(0U, m.size());
  8962. EXPECT_NE(static_cast<const void *>(m.data()),
  8963. static_cast<const void *>(MAP_FAILED));
  8964. }
  8965. #endif
  8966. TEST(KeepAliveTest, ReadTimeout) {
  8967. Server svr;
  8968. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8969. std::this_thread::sleep_for(std::chrono::seconds(2));
  8970. res.set_content("a", "text/plain");
  8971. });
  8972. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8973. res.set_content("b", "text/plain");
  8974. });
  8975. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8976. auto se = detail::scope_exit([&] {
  8977. svr.stop();
  8978. listen_thread.join();
  8979. ASSERT_FALSE(svr.is_running());
  8980. });
  8981. svr.wait_until_ready();
  8982. Client cli("localhost", PORT);
  8983. cli.set_keep_alive(true);
  8984. cli.set_read_timeout(std::chrono::seconds(1));
  8985. auto resa = cli.Get("/a");
  8986. ASSERT_FALSE(resa);
  8987. EXPECT_EQ(Error::Read, resa.error());
  8988. auto resb = cli.Get("/b");
  8989. ASSERT_TRUE(resb);
  8990. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8991. EXPECT_EQ("b", resb->body);
  8992. }
  8993. TEST(KeepAliveTest, MaxCount) {
  8994. size_t keep_alive_max_count = 3;
  8995. Server svr;
  8996. svr.set_keep_alive_max_count(keep_alive_max_count);
  8997. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8998. res.set_content("Hello World!", "text/plain");
  8999. });
  9000. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9001. auto se = detail::scope_exit([&] {
  9002. svr.stop();
  9003. listen_thread.join();
  9004. ASSERT_FALSE(svr.is_running());
  9005. });
  9006. svr.wait_until_ready();
  9007. Client cli(HOST, PORT);
  9008. cli.set_keep_alive(true);
  9009. for (size_t i = 0; i < 5; i++) {
  9010. auto result = cli.Get("/hi");
  9011. ASSERT_TRUE(result);
  9012. EXPECT_EQ(StatusCode::OK_200, result->status);
  9013. if (i == keep_alive_max_count - 1) {
  9014. EXPECT_EQ("close", result->get_header_value("Connection"));
  9015. } else {
  9016. EXPECT_FALSE(result->has_header("Connection"));
  9017. }
  9018. }
  9019. }
  9020. TEST(KeepAliveTest, Issue1041) {
  9021. Server svr;
  9022. svr.set_keep_alive_timeout(3);
  9023. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9024. res.set_content("Hello World!", "text/plain");
  9025. });
  9026. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9027. auto se = detail::scope_exit([&] {
  9028. svr.stop();
  9029. listen_thread.join();
  9030. ASSERT_FALSE(svr.is_running());
  9031. });
  9032. svr.wait_until_ready();
  9033. Client cli(HOST, PORT);
  9034. cli.set_keep_alive(true);
  9035. auto result = cli.Get("/hi");
  9036. ASSERT_TRUE(result);
  9037. EXPECT_EQ(StatusCode::OK_200, result->status);
  9038. std::this_thread::sleep_for(std::chrono::seconds(5));
  9039. result = cli.Get("/hi");
  9040. ASSERT_TRUE(result);
  9041. EXPECT_EQ(StatusCode::OK_200, result->status);
  9042. }
  9043. TEST(KeepAliveTest, Issue1959) {
  9044. Server svr;
  9045. svr.set_keep_alive_timeout(5);
  9046. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9047. res.set_content("a", "text/plain");
  9048. });
  9049. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9050. auto se = detail::scope_exit([&] {
  9051. if (!svr.is_running()) return;
  9052. svr.stop();
  9053. listen_thread.join();
  9054. ASSERT_FALSE(svr.is_running());
  9055. });
  9056. svr.wait_until_ready();
  9057. Client cli("localhost", PORT);
  9058. cli.set_keep_alive(true);
  9059. using namespace std::chrono;
  9060. auto start = steady_clock::now();
  9061. cli.Get("/a");
  9062. svr.stop();
  9063. listen_thread.join();
  9064. auto end = steady_clock::now();
  9065. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9066. EXPECT_LT(elapsed, 5000);
  9067. }
  9068. #ifdef CPPHTTPLIB_SSL_ENABLED
  9069. TEST(KeepAliveTest, SSLClientReconnection) {
  9070. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9071. ASSERT_TRUE(svr.is_valid());
  9072. svr.set_keep_alive_timeout(1);
  9073. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9074. res.set_content("Hello World!", "text/plain");
  9075. });
  9076. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9077. auto se = detail::scope_exit([&] {
  9078. svr.stop();
  9079. listen_thread.join();
  9080. ASSERT_FALSE(svr.is_running());
  9081. });
  9082. svr.wait_until_ready();
  9083. SSLClient cli(HOST, PORT);
  9084. cli.enable_server_certificate_verification(false);
  9085. cli.set_keep_alive(true);
  9086. auto result = cli.Get("/hi");
  9087. ASSERT_TRUE(result);
  9088. EXPECT_EQ(StatusCode::OK_200, result->status);
  9089. result = cli.Get("/hi");
  9090. ASSERT_TRUE(result);
  9091. EXPECT_EQ(StatusCode::OK_200, result->status);
  9092. std::this_thread::sleep_for(std::chrono::seconds(2));
  9093. // Recoonect
  9094. result = cli.Get("/hi");
  9095. ASSERT_TRUE(result);
  9096. EXPECT_EQ(StatusCode::OK_200, result->status);
  9097. result = cli.Get("/hi");
  9098. ASSERT_TRUE(result);
  9099. EXPECT_EQ(StatusCode::OK_200, result->status);
  9100. }
  9101. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9103. ASSERT_TRUE(svr.is_valid());
  9104. svr.set_keep_alive_timeout(1);
  9105. std::string content = "reconnect";
  9106. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9107. res.set_content("Hello World!", "text/plain");
  9108. });
  9109. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9110. auto se = detail::scope_exit([&] {
  9111. svr.stop();
  9112. listen_thread.join();
  9113. ASSERT_FALSE(svr.is_running());
  9114. });
  9115. svr.wait_until_ready();
  9116. SSLClient cli(HOST, PORT);
  9117. cli.enable_server_certificate_verification(false);
  9118. cli.set_keep_alive(true);
  9119. auto result = cli.Post(
  9120. "/hi", content.size(),
  9121. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9122. sink.write(content.c_str(), content.size());
  9123. return true;
  9124. },
  9125. "text/plain");
  9126. ASSERT_TRUE(result);
  9127. EXPECT_EQ(200, result->status);
  9128. std::this_thread::sleep_for(std::chrono::seconds(2));
  9129. // Recoonect
  9130. result = cli.Post(
  9131. "/hi", content.size(),
  9132. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9133. sink.write(content.c_str(), content.size());
  9134. return true;
  9135. },
  9136. "text/plain");
  9137. ASSERT_TRUE(result);
  9138. EXPECT_EQ(200, result->status);
  9139. result = cli.Post(
  9140. "/hi", content.size(),
  9141. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9142. sink.write(content.c_str(), content.size());
  9143. return true;
  9144. },
  9145. "text/plain");
  9146. ASSERT_TRUE(result);
  9147. EXPECT_EQ(200, result->status);
  9148. }
  9149. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9150. using namespace httplib::tls;
  9151. {
  9152. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9153. ASSERT_TRUE(svr.is_valid());
  9154. svr.Get("/sni", [&](const Request &req, Response &res) {
  9155. std::string expected = req.sni();
  9156. EXPECT_EQ(expected, req.get_param_value("expected"));
  9157. res.set_content("ok", "text/plain");
  9158. });
  9159. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9160. auto se = detail::scope_exit([&] {
  9161. svr.stop();
  9162. listen_thread.join();
  9163. ASSERT_FALSE(svr.is_running());
  9164. });
  9165. svr.wait_until_ready();
  9166. {
  9167. SSLClient cli("localhost", PORT);
  9168. cli.enable_server_certificate_verification(false);
  9169. auto res = cli.Get("/sni?expected=localhost");
  9170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9171. }
  9172. {
  9173. SSLClient cli("::1", PORT);
  9174. cli.enable_server_certificate_verification(false);
  9175. auto res = cli.Get("/sni?expected=");
  9176. // NOTE: This may fail if the server is listening on IPv4 only
  9177. // (e.g., when localhost resolves to 127.0.0.1 only)
  9178. if (res) {
  9179. EXPECT_EQ(StatusCode::OK_200, res->status);
  9180. } else {
  9181. EXPECT_EQ(Error::Connection, res.error());
  9182. }
  9183. }
  9184. }
  9185. }
  9186. #endif
  9187. TEST(ClientProblemDetectionTest, ContentProvider) {
  9188. Server svr;
  9189. size_t content_length = 1024 * 1024;
  9190. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9191. res.set_content_provider(
  9192. content_length, "text/plain",
  9193. [&](size_t offset, size_t length, DataSink &sink) {
  9194. auto out_len = std::min(length, static_cast<size_t>(1024));
  9195. std::string out(out_len, '@');
  9196. sink.write(out.data(), out_len);
  9197. return offset < 4096;
  9198. },
  9199. [](bool success) { ASSERT_FALSE(success); });
  9200. });
  9201. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9202. res.set_content_provider(
  9203. 0, "text/plain",
  9204. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9205. EXPECT_TRUE(false);
  9206. return true;
  9207. },
  9208. [](bool success) { ASSERT_FALSE(success); });
  9209. });
  9210. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9211. auto se = detail::scope_exit([&] {
  9212. svr.stop();
  9213. listen_thread.join();
  9214. ASSERT_FALSE(svr.is_running());
  9215. });
  9216. svr.wait_until_ready();
  9217. Client cli("localhost", PORT);
  9218. {
  9219. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9220. size_t /*data_length*/) { return false; });
  9221. ASSERT_FALSE(res);
  9222. }
  9223. {
  9224. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9225. size_t /*data_length*/) { return false; });
  9226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9227. }
  9228. }
  9229. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9230. // A writer only has to assign `write`. The other three used to be left as
  9231. // empty std::functions, so a provider calling one threw
  9232. // std::bad_function_call out of the thread running it and took the whole
  9233. // process down.
  9234. DataSink sink;
  9235. std::string written;
  9236. sink.write = [&](const char *data, size_t data_len) {
  9237. written.append(data, data_len);
  9238. return true;
  9239. };
  9240. EXPECT_TRUE(sink.is_writable());
  9241. sink.done();
  9242. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9243. EXPECT_TRUE(written.empty());
  9244. }
  9245. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9246. // A sink that cannot carry trailers still has to finish.
  9247. DataSink sink;
  9248. auto done_count = 0;
  9249. sink.done = [&]() { done_count++; };
  9250. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9251. EXPECT_EQ(1, done_count);
  9252. }
  9253. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9254. Server svr;
  9255. const std::string body(4096, 'x');
  9256. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9257. res.set_content_provider(body.size(), "text/plain",
  9258. [&](size_t offset, size_t length, DataSink &sink) {
  9259. sink.write(body.data() + offset, length);
  9260. sink.done();
  9261. return true;
  9262. });
  9263. });
  9264. auto port = svr.bind_to_any_port(HOST);
  9265. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9266. auto se = detail::scope_exit([&] {
  9267. svr.stop();
  9268. listen_thread.join();
  9269. ASSERT_FALSE(svr.is_running());
  9270. });
  9271. svr.wait_until_ready();
  9272. Client cli(HOST, port);
  9273. auto res = cli.Get("/");
  9274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9275. EXPECT_EQ(StatusCode::OK_200, res->status);
  9276. EXPECT_EQ(body, res->body);
  9277. }
  9278. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9279. Server svr;
  9280. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9281. res.set_content_provider(
  9282. 1024, "text/plain",
  9283. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9284. sink.write("hello", 5);
  9285. sink.done(); // short of the 1024 bytes the response promised
  9286. return true;
  9287. });
  9288. });
  9289. auto port = svr.bind_to_any_port(HOST);
  9290. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9291. auto se = detail::scope_exit([&] {
  9292. svr.stop();
  9293. listen_thread.join();
  9294. ASSERT_FALSE(svr.is_running());
  9295. });
  9296. svr.wait_until_ready();
  9297. Client cli(HOST, port);
  9298. cli.set_read_timeout(5, 0);
  9299. // The response is short of its Content-Length, so the client cannot read a
  9300. // complete body. What matters is that this returns at all: a no-op done()
  9301. // would leave the writer looping over a provider that never makes progress.
  9302. auto res = cli.Get("/");
  9303. EXPECT_FALSE(res);
  9304. }
  9305. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9306. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9307. // The compressed path builds the whole body before connecting, so this
  9308. // fails client-side and never reaches a server.
  9309. Client cli(HOST, PORT);
  9310. cli.set_compress(true);
  9311. auto res = cli.Post(
  9312. "/", 1024,
  9313. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9314. sink.write("hello", 5);
  9315. sink.done(); // short of the 1024 bytes the request announced
  9316. return true;
  9317. },
  9318. "text/plain");
  9319. ASSERT_FALSE(res);
  9320. EXPECT_EQ(Error::Write, res.error());
  9321. }
  9322. #endif
  9323. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9324. Server svr;
  9325. svr.set_error_handler([](Request const &, Response &res) -> void {
  9326. res.set_chunked_content_provider(
  9327. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9328. sink.os << "hello";
  9329. sink.os << "world";
  9330. sink.done();
  9331. return true;
  9332. });
  9333. });
  9334. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9335. auto se = detail::scope_exit([&] {
  9336. svr.stop();
  9337. listen_thread.join();
  9338. ASSERT_FALSE(svr.is_running());
  9339. });
  9340. svr.wait_until_ready();
  9341. Client cli("localhost", PORT);
  9342. auto res = cli.Get("/");
  9343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9344. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9345. EXPECT_EQ("helloworld", res->body);
  9346. }
  9347. TEST(LongPollingTest, ClientCloseDetection) {
  9348. Server svr;
  9349. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9350. res.set_chunked_content_provider(
  9351. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9352. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9353. sink.os << "hello";
  9354. auto count = 10;
  9355. while (count > 0 && sink.is_writable()) {
  9356. this_thread::sleep_for(chrono::milliseconds(10));
  9357. count--;
  9358. }
  9359. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9360. return true;
  9361. });
  9362. });
  9363. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9364. auto se = detail::scope_exit([&] {
  9365. svr.stop();
  9366. listen_thread.join();
  9367. ASSERT_FALSE(svr.is_running());
  9368. });
  9369. svr.wait_until_ready();
  9370. Client cli("localhost", PORT);
  9371. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9372. EXPECT_EQ("hello", string(data, data_length));
  9373. return false; // close the socket immediately.
  9374. });
  9375. ASSERT_FALSE(res);
  9376. }
  9377. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9378. Server svr;
  9379. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9380. res.set_chunked_content_provider(
  9381. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9382. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9383. sink.os << "hello";
  9384. EXPECT_TRUE(sink.os.good());
  9385. // Wait for the client to close the connection
  9386. auto count = 10;
  9387. while (count > 0 && sink.is_writable()) {
  9388. this_thread::sleep_for(chrono::milliseconds(10));
  9389. count--;
  9390. }
  9391. // After client disconnect, write repeatedly until the socket
  9392. // write actually fails (small writes may be absorbed by the
  9393. // kernel buffer)
  9394. std::string chunk(1024, 'x');
  9395. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9396. sink.os << chunk;
  9397. }
  9398. EXPECT_TRUE(sink.os.fail());
  9399. return true;
  9400. });
  9401. });
  9402. auto port = svr.bind_to_any_port("localhost");
  9403. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9404. auto se = detail::scope_exit([&] {
  9405. svr.stop();
  9406. listen_thread.join();
  9407. ASSERT_FALSE(svr.is_running());
  9408. });
  9409. svr.wait_until_ready();
  9410. Client cli("localhost", port);
  9411. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9412. EXPECT_EQ("hello", string(data, data_length));
  9413. return false; // close the socket immediately.
  9414. });
  9415. ASSERT_FALSE(res);
  9416. }
  9417. TEST(GetWithParametersTest, GetWithParameters) {
  9418. Server svr;
  9419. svr.Get("/", [&](const Request &req, Response &) {
  9420. EXPECT_EQ("world", req.get_param_value("hello"));
  9421. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9422. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9423. });
  9424. svr.Get("/params", [&](const Request &req, Response &) {
  9425. EXPECT_EQ("world", req.get_param_value("hello"));
  9426. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9427. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9428. });
  9429. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  9430. EXPECT_EQ("resource-id", req.matches[1]);
  9431. EXPECT_EQ("foo", req.get_param_value("param1"));
  9432. EXPECT_EQ("bar", req.get_param_value("param2"));
  9433. });
  9434. svr.Get("/users/:id", [&](const Request &req, Response &) {
  9435. EXPECT_EQ("user-id", req.path_params.at("id"));
  9436. EXPECT_EQ("foo", req.get_param_value("param1"));
  9437. EXPECT_EQ("bar", req.get_param_value("param2"));
  9438. });
  9439. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9440. auto se = detail::scope_exit([&] {
  9441. svr.stop();
  9442. listen_thread.join();
  9443. ASSERT_FALSE(svr.is_running());
  9444. });
  9445. svr.wait_until_ready();
  9446. {
  9447. Client cli(HOST, PORT);
  9448. Params params;
  9449. params.emplace("hello", "world");
  9450. params.emplace("hello2", "world2");
  9451. params.emplace("hello3", "world3");
  9452. auto res = cli.Get("/", params, Headers{});
  9453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9454. EXPECT_EQ(StatusCode::OK_200, res->status);
  9455. }
  9456. {
  9457. Client cli(HOST, PORT);
  9458. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9460. EXPECT_EQ(StatusCode::OK_200, res->status);
  9461. }
  9462. {
  9463. Client cli(HOST, PORT);
  9464. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9466. EXPECT_EQ(StatusCode::OK_200, res->status);
  9467. }
  9468. {
  9469. Client cli(HOST, PORT);
  9470. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9472. EXPECT_EQ(StatusCode::OK_200, res->status);
  9473. }
  9474. }
  9475. TEST(GetWithParametersTest, GetWithParameters2) {
  9476. Server svr;
  9477. svr.Get("/", [&](const Request &req, Response &res) {
  9478. auto text = req.get_param_value("hello");
  9479. res.set_content(text, "text/plain");
  9480. });
  9481. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9482. auto se = detail::scope_exit([&] {
  9483. svr.stop();
  9484. listen_thread.join();
  9485. ASSERT_FALSE(svr.is_running());
  9486. });
  9487. svr.wait_until_ready();
  9488. Client cli("localhost", PORT);
  9489. Params params;
  9490. params.emplace("hello", "world");
  9491. std::string body;
  9492. auto res = cli.Get("/", params, Headers{},
  9493. [&](const char *data, size_t data_length) {
  9494. body.append(data, data_length);
  9495. return true;
  9496. });
  9497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9498. EXPECT_EQ(StatusCode::OK_200, res->status);
  9499. EXPECT_EQ("world", body);
  9500. }
  9501. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9502. Server svr;
  9503. svr.Get("/search", [&](const Request &req, Response &res) {
  9504. auto q = req.get_param_value("q");
  9505. res.set_content(q, "text/plain");
  9506. });
  9507. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9508. auto se = detail::scope_exit([&] {
  9509. svr.stop();
  9510. listen_thread.join();
  9511. ASSERT_FALSE(svr.is_running());
  9512. });
  9513. svr.wait_until_ready();
  9514. Client cli("localhost", PORT);
  9515. // Verify that Get(path, params) works without requiring Headers argument
  9516. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9518. EXPECT_EQ(StatusCode::OK_200, res->status);
  9519. EXPECT_EQ("cpp-httplib", res->body);
  9520. }
  9521. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9522. auto host = "httpbingo.org";
  9523. auto path = std::string{"/range/32"};
  9524. #ifdef CPPHTTPLIB_SSL_ENABLED
  9525. SSLClient cli(host);
  9526. #else
  9527. Client cli(host);
  9528. #endif
  9529. cli.set_default_headers({make_range_header({{1, 10}})});
  9530. cli.set_connection_timeout(5);
  9531. {
  9532. auto res = cli.Get(path);
  9533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9534. EXPECT_EQ("bcdefghijk", res->body);
  9535. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9536. }
  9537. {
  9538. auto res = cli.Get(path);
  9539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9540. EXPECT_EQ("bcdefghijk", res->body);
  9541. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9542. }
  9543. }
  9544. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  9545. Server svr;
  9546. svr.set_default_headers({{"Hello", "World"}});
  9547. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9548. res.set_content("ok", "text/plain");
  9549. });
  9550. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9551. auto se = detail::scope_exit([&] {
  9552. svr.stop();
  9553. listen_thread.join();
  9554. ASSERT_FALSE(svr.is_running());
  9555. });
  9556. svr.wait_until_ready();
  9557. Client cli("localhost", PORT);
  9558. auto res = cli.Get("/");
  9559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9560. EXPECT_EQ(StatusCode::OK_200, res->status);
  9561. EXPECT_EQ("ok", res->body);
  9562. EXPECT_EQ("World", res->get_header_value("Hello"));
  9563. }
  9564. #ifdef CPPHTTPLIB_SSL_ENABLED
  9565. TEST(KeepAliveTest, ReadTimeoutSSL) {
  9566. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9567. ASSERT_TRUE(svr.is_valid());
  9568. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9569. std::this_thread::sleep_for(std::chrono::seconds(2));
  9570. res.set_content("a", "text/plain");
  9571. });
  9572. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9573. res.set_content("b", "text/plain");
  9574. });
  9575. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9576. auto se = detail::scope_exit([&] {
  9577. svr.stop();
  9578. listen_thread.join();
  9579. ASSERT_FALSE(svr.is_running());
  9580. });
  9581. svr.wait_until_ready();
  9582. SSLClient cli("localhost", PORT);
  9583. cli.enable_server_certificate_verification(false);
  9584. cli.set_keep_alive(true);
  9585. cli.set_read_timeout(std::chrono::seconds(1));
  9586. auto resa = cli.Get("/a");
  9587. ASSERT_TRUE(!resa);
  9588. EXPECT_EQ(Error::Read, resa.error());
  9589. auto resb = cli.Get("/b");
  9590. ASSERT_TRUE(resb);
  9591. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9592. EXPECT_EQ("b", resb->body);
  9593. }
  9594. #endif
  9595. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  9596. protected:
  9597. ServerTestWithAI_PASSIVE()
  9598. : cli_(HOST, PORT)
  9599. #ifdef CPPHTTPLIB_SSL_ENABLED
  9600. ,
  9601. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9602. #endif
  9603. {
  9604. #ifdef CPPHTTPLIB_SSL_ENABLED
  9605. cli_.enable_server_certificate_verification(false);
  9606. #endif
  9607. }
  9608. virtual void SetUp() {
  9609. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9610. res.set_content("Hello World!", "text/plain");
  9611. });
  9612. t_ = thread(
  9613. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  9614. svr_.wait_until_ready();
  9615. }
  9616. virtual void TearDown() {
  9617. svr_.stop();
  9618. t_.join();
  9619. }
  9620. #ifdef CPPHTTPLIB_SSL_ENABLED
  9621. SSLClient cli_;
  9622. SSLServer svr_;
  9623. #else
  9624. Client cli_;
  9625. Server svr_;
  9626. #endif
  9627. thread t_;
  9628. };
  9629. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  9630. auto res = cli_.Get("/hi");
  9631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9632. EXPECT_EQ(StatusCode::OK_200, res->status);
  9633. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9634. EXPECT_EQ("Hello World!", res->body);
  9635. }
  9636. class ServerUpDownTest : public ::testing::Test {
  9637. protected:
  9638. ServerUpDownTest() : cli_(HOST, PORT) {}
  9639. virtual void SetUp() {
  9640. t_ = thread([&]() {
  9641. svr_.bind_to_any_port(HOST);
  9642. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9643. ASSERT_TRUE(svr_.listen_after_bind());
  9644. });
  9645. svr_.wait_until_ready();
  9646. }
  9647. virtual void TearDown() {
  9648. svr_.stop();
  9649. t_.join();
  9650. }
  9651. Client cli_;
  9652. Server svr_;
  9653. thread t_;
  9654. };
  9655. TEST_F(ServerUpDownTest, QuickStartStop) {
  9656. // Should not crash, especially when run with
  9657. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  9658. }
  9659. class PayloadMaxLengthTest : public ::testing::Test {
  9660. protected:
  9661. PayloadMaxLengthTest()
  9662. : cli_(HOST, PORT)
  9663. #ifdef CPPHTTPLIB_SSL_ENABLED
  9664. ,
  9665. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9666. #endif
  9667. {
  9668. #ifdef CPPHTTPLIB_SSL_ENABLED
  9669. cli_.enable_server_certificate_verification(false);
  9670. #endif
  9671. }
  9672. virtual void SetUp() {
  9673. svr_.set_payload_max_length(8);
  9674. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9675. res.set_content("test", "text/plain");
  9676. });
  9677. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9678. svr_.wait_until_ready();
  9679. }
  9680. virtual void TearDown() {
  9681. svr_.stop();
  9682. t_.join();
  9683. }
  9684. #ifdef CPPHTTPLIB_SSL_ENABLED
  9685. SSLClient cli_;
  9686. SSLServer svr_;
  9687. #else
  9688. Client cli_;
  9689. Server svr_;
  9690. #endif
  9691. thread t_;
  9692. };
  9693. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  9694. auto res = cli_.Post("/test", "123456789", "text/plain");
  9695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9696. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9697. res = cli_.Post("/test", "12345678", "text/plain");
  9698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9699. EXPECT_EQ(StatusCode::OK_200, res->status);
  9700. }
  9701. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  9702. // Test chunked encoding with payload exceeding the 8-byte limit
  9703. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  9704. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  9705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9706. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9707. }
  9708. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  9709. // Test chunked encoding with payload within the 8-byte limit
  9710. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  9711. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  9712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9713. EXPECT_EQ(StatusCode::OK_200, res->status);
  9714. }
  9715. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  9716. // Test using send_request to send chunked data exceeding payload limit
  9717. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  9718. "Host: " +
  9719. std::string(HOST) + ":" + std::to_string(PORT) +
  9720. "\r\n"
  9721. "Transfer-Encoding: chunked\r\n"
  9722. "Connection: close\r\n"
  9723. "\r\n"
  9724. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  9725. "0123456789\r\n"
  9726. "0\r\n" // End chunk
  9727. "\r\n";
  9728. std::string response;
  9729. bool result = send_request(1, chunked_request, &response);
  9730. if (!result) {
  9731. // If send_request fails, it might be because the server closed the
  9732. // connection due to payload limit enforcement, which is acceptable
  9733. SUCCEED()
  9734. << "Server rejected oversized chunked request (connection closed)";
  9735. } else {
  9736. // If we got a response, check if it's an error response or connection was
  9737. // closed early Short response length indicates connection was closed due to
  9738. // payload limit
  9739. if (response.length() <= 10) {
  9740. SUCCEED() << "Server closed connection for oversized chunked request";
  9741. } else {
  9742. // Check for error status codes
  9743. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9744. response.find("Payload Too Large") != std::string::npos ||
  9745. response.find("400") != std::string::npos);
  9746. }
  9747. }
  9748. }
  9749. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  9750. // Test request without Content-Length header exceeding payload limit
  9751. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9752. "Host: " +
  9753. std::string(HOST) + ":" +
  9754. std::to_string(PORT) +
  9755. "\r\n"
  9756. "Connection: close\r\n"
  9757. "\r\n";
  9758. // Add payload exceeding the 8-byte limit
  9759. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  9760. request_without_content_length += large_payload;
  9761. std::string response;
  9762. bool result = send_request(1, request_without_content_length, &response);
  9763. if (!result) {
  9764. // If send_request fails, server likely closed connection due to payload
  9765. // limit
  9766. SUCCEED() << "Server rejected oversized request without Content-Length "
  9767. "(connection closed)";
  9768. } else {
  9769. // Check if server responded with error or closed connection early
  9770. if (response.length() <= 10) {
  9771. SUCCEED() << "Server closed connection for oversized request without "
  9772. "Content-Length";
  9773. } else {
  9774. // Check for error status codes
  9775. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9776. response.find("Payload Too Large") != std::string::npos ||
  9777. response.find("400") != std::string::npos);
  9778. }
  9779. }
  9780. }
  9781. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  9782. // Test request without Content-Length header within payload limit
  9783. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9784. "Host: " +
  9785. std::string(HOST) + ":" +
  9786. std::to_string(PORT) +
  9787. "\r\n"
  9788. "Connection: close\r\n"
  9789. "\r\n";
  9790. // Add payload within the 8-byte limit
  9791. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9792. request_without_content_length += small_payload;
  9793. std::string response;
  9794. bool result = send_request(1, request_without_content_length, &response);
  9795. // For requests without Content-Length, the server may have different behavior
  9796. // The key is that it should not reject due to payload limit for small
  9797. // payloads
  9798. if (result) {
  9799. // Check for any HTTP response (success or error, but not connection closed)
  9800. if (response.length() > 10) {
  9801. SUCCEED()
  9802. << "Server processed request without Content-Length within limit";
  9803. } else {
  9804. // Short response might indicate connection closed, which is acceptable
  9805. SUCCEED() << "Server closed connection for request without "
  9806. "Content-Length (acceptable behavior)";
  9807. }
  9808. } else {
  9809. // Connection failure might be due to protocol requirements
  9810. SUCCEED() << "Connection issue with request without Content-Length "
  9811. "(environment-specific)";
  9812. }
  9813. }
  9814. class LargePayloadMaxLengthTest : public ::testing::Test {
  9815. protected:
  9816. LargePayloadMaxLengthTest()
  9817. : cli_(HOST, PORT)
  9818. #ifdef CPPHTTPLIB_SSL_ENABLED
  9819. ,
  9820. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9821. #endif
  9822. {
  9823. #ifdef CPPHTTPLIB_SSL_ENABLED
  9824. cli_.enable_server_certificate_verification(false);
  9825. #endif
  9826. }
  9827. virtual void SetUp() {
  9828. // Set 10MB payload limit
  9829. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9830. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9831. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9832. res.set_content("Large payload test", "text/plain");
  9833. });
  9834. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9835. svr_.wait_until_ready();
  9836. }
  9837. virtual void TearDown() {
  9838. svr_.stop();
  9839. t_.join();
  9840. }
  9841. #ifdef CPPHTTPLIB_SSL_ENABLED
  9842. SSLClient cli_;
  9843. SSLServer svr_;
  9844. #else
  9845. Client cli_;
  9846. Server svr_;
  9847. #endif
  9848. thread t_;
  9849. };
  9850. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9851. // Test chunked encoding with payload within 10MB limit
  9852. std::string medium_payload(5 * 1024 * 1024,
  9853. 'A'); // 5MB payload, within 10MB limit
  9854. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9856. EXPECT_EQ(StatusCode::OK_200, res->status);
  9857. }
  9858. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9859. // Test chunked encoding with payload exceeding 10MB limit
  9860. std::string large_payload(12 * 1024 * 1024,
  9861. 'B'); // 12MB payload, exceeds 10MB limit
  9862. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9863. // Server may either return 413 or close the connection
  9864. if (res) {
  9865. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9866. } else {
  9867. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9868. }
  9869. }
  9870. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9871. // Test request without Content-Length header within 10MB limit
  9872. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9873. "Host: " +
  9874. std::string(HOST) + ":" +
  9875. std::to_string(PORT) +
  9876. "\r\n"
  9877. "Connection: close\r\n"
  9878. "\r\n";
  9879. // Add 1MB payload (within 10MB limit)
  9880. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9881. request_without_content_length += medium_payload;
  9882. std::string response;
  9883. bool result = send_request(5, request_without_content_length, &response);
  9884. if (result) {
  9885. // Should get a proper HTTP response for payloads within limit
  9886. if (response.length() > 10) {
  9887. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9888. "10MB limit";
  9889. } else {
  9890. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9891. "Content-Length)";
  9892. }
  9893. } else {
  9894. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9895. }
  9896. }
  9897. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9898. // Test request without Content-Length header exceeding 10MB limit
  9899. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9900. "Host: " +
  9901. std::string(HOST) + ":" +
  9902. std::to_string(PORT) +
  9903. "\r\n"
  9904. "Connection: close\r\n"
  9905. "\r\n";
  9906. // Add 12MB payload (exceeds 10MB limit)
  9907. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9908. request_without_content_length += large_payload;
  9909. std::string response;
  9910. bool result = send_request(10, request_without_content_length, &response);
  9911. if (!result) {
  9912. // Server should close connection due to payload limit
  9913. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9914. "(connection closed)";
  9915. } else {
  9916. // Check for error response
  9917. if (response.length() <= 10) {
  9918. SUCCEED()
  9919. << "Server closed connection for 12MB request exceeding 10MB limit";
  9920. } else {
  9921. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9922. response.find("Payload Too Large") != std::string::npos ||
  9923. response.find("400") != std::string::npos);
  9924. }
  9925. }
  9926. }
  9927. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9928. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9929. // path.
  9930. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9931. Server svr;
  9932. const size_t LIMIT = 64 * 1024; // 64KB
  9933. svr.set_payload_max_length(LIMIT);
  9934. size_t total = 0;
  9935. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9936. const ContentReader &content_reader) {
  9937. content_reader([&](const char * /*data*/, size_t len) {
  9938. total += len;
  9939. return true;
  9940. });
  9941. res.status = 200;
  9942. res.set_content("stream_ok", "text/plain");
  9943. });
  9944. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9945. auto se = detail::scope_exit([&] {
  9946. svr.stop();
  9947. thread.join();
  9948. ASSERT_FALSE(svr.is_running());
  9949. });
  9950. svr.wait_until_ready();
  9951. // Prepare 256KB raw data and gzip-compress it
  9952. std::string raw(256 * 1024, 'A');
  9953. std::string gz;
  9954. {
  9955. z_stream zs{};
  9956. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9957. Z_DEFAULT_STRATEGY);
  9958. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9959. zs.avail_in = static_cast<uInt>(raw.size());
  9960. char outbuf[4096];
  9961. int ret;
  9962. do {
  9963. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9964. zs.avail_out = sizeof(outbuf);
  9965. ret = deflate(&zs, Z_FINISH);
  9966. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9967. } while (ret != Z_STREAM_END);
  9968. deflateEnd(&zs);
  9969. }
  9970. Client cli(HOST, PORT);
  9971. cli.set_connection_timeout(std::chrono::seconds(5));
  9972. Headers headers = {{"Content-Encoding", "gzip"}};
  9973. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9974. "application/octet-stream");
  9975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9976. // Server must reject oversized decompressed payloads with 413.
  9977. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9978. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9979. EXPECT_LE(total, LIMIT);
  9980. }
  9981. #ifndef CPPHTTPLIB_SSL_ENABLED
  9982. // For a request with neither Content-Length nor Transfer-Encoding, the
  9983. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9984. // compressed wire bytes straight to the ContentReader without ever routing
  9985. // them through the decompressor, so payload_max_length_ only bounded the
  9986. // compressed size on the wire, not the decompressed size.
  9987. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9988. Server svr;
  9989. const size_t LIMIT = 64 * 1024; // 64KB
  9990. svr.set_payload_max_length(LIMIT);
  9991. size_t total = 0;
  9992. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9993. const ContentReader &content_reader) {
  9994. content_reader([&](const char * /*data*/, size_t len) {
  9995. total += len;
  9996. return true;
  9997. });
  9998. res.status = 200;
  9999. res.set_content("stream_ok", "text/plain");
  10000. });
  10001. auto port = svr.bind_to_any_port(HOST);
  10002. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10003. auto se = detail::scope_exit([&] {
  10004. svr.stop();
  10005. thread.join();
  10006. ASSERT_FALSE(svr.is_running());
  10007. });
  10008. svr.wait_until_ready();
  10009. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10010. // StreamingGzipDecompression test above.
  10011. std::string raw(256 * 1024, 'A');
  10012. std::string gz;
  10013. {
  10014. httplib::detail::gzip_compressor compressor;
  10015. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10016. [&](const char *chunk, size_t len) {
  10017. gz.append(chunk, len);
  10018. return true;
  10019. });
  10020. ASSERT_TRUE(result);
  10021. }
  10022. // Send the gzip body over raw TCP with neither Content-Length nor
  10023. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10024. // kicks in.
  10025. std::string req = "POST /stream HTTP/1.1\r\n"
  10026. "Host: " +
  10027. std::string(HOST) + ":" + std::to_string(port) +
  10028. "\r\n"
  10029. "Content-Encoding: gzip\r\n"
  10030. "Connection: close\r\n"
  10031. "\r\n" +
  10032. gz;
  10033. std::string response;
  10034. ASSERT_TRUE(send_request(5, req, &response, port));
  10035. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10036. EXPECT_LE(total, LIMIT);
  10037. }
  10038. #endif
  10039. #endif
  10040. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10041. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10042. // the payload must be passed through untouched instead of being rejected.
  10043. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10044. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10045. Server svr;
  10046. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10047. res.set_content(body, "image/jpeg");
  10048. res.set_header("Content-Encoding", "UTF-8");
  10049. });
  10050. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10051. res.set_content(body, "image/jpeg");
  10052. res.set_header("Content-Encoding", "identity");
  10053. });
  10054. svr.Post("/echo", [](const Request &req, Response &res) {
  10055. res.set_content(req.body, "image/jpeg");
  10056. });
  10057. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10058. auto se = detail::scope_exit([&] {
  10059. svr.stop();
  10060. t.join();
  10061. ASSERT_FALSE(svr.is_running());
  10062. });
  10063. svr.wait_until_ready();
  10064. Client cli(HOST, PORT);
  10065. {
  10066. auto res = cli.Get("/image");
  10067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10068. EXPECT_EQ(StatusCode::OK_200, res->status);
  10069. EXPECT_EQ(body, res->body);
  10070. }
  10071. {
  10072. auto res = cli.Get("/identity");
  10073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10074. EXPECT_EQ(StatusCode::OK_200, res->status);
  10075. EXPECT_EQ(body, res->body);
  10076. }
  10077. {
  10078. // The same applies to a request body reaching the server.
  10079. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10080. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10082. EXPECT_EQ(StatusCode::OK_200, res->status);
  10083. EXPECT_EQ(body, res->body);
  10084. }
  10085. }
  10086. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10087. // gzip-encoded response even when the build has no zlib support.
  10088. static const char GZIPPED_HELLO_WORLD[] = {
  10089. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10090. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10091. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10092. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10093. // A content coding is a whole token, not something the field value merely
  10094. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10095. // as "fibre" look like Brotli, and turned a multi-coding value like
  10096. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10097. // it was never meant to see.
  10098. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10099. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10100. Server svr;
  10101. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10102. res.set_content(body, "image/jpeg");
  10103. res.set_header("Content-Encoding", "fibre");
  10104. });
  10105. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10106. res.set_content(body, "image/jpeg");
  10107. res.set_header("Content-Encoding", "gzip, br");
  10108. });
  10109. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10110. res.set_content(body, "image/jpeg");
  10111. res.set_header("Content-Encoding", "x-zstd-ish");
  10112. });
  10113. auto port = svr.bind_to_any_port(HOST);
  10114. thread t = thread([&]() { svr.listen_after_bind(); });
  10115. auto se = detail::scope_exit([&] {
  10116. svr.stop();
  10117. t.join();
  10118. ASSERT_FALSE(svr.is_running());
  10119. });
  10120. svr.wait_until_ready();
  10121. Client cli(HOST, port);
  10122. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10123. auto res = cli.Get(path);
  10124. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10125. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10126. // Not a coding we recognize, so the payload comes back untouched
  10127. EXPECT_EQ(body, res->body) << path;
  10128. }
  10129. }
  10130. // A content coding cpp-httplib recognizes but was not built with must be
  10131. // reported as such. Handing the still-compressed payload back to the caller
  10132. // would silently corrupt it.
  10133. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10134. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10135. Server svr;
  10136. // "image/jpeg" keeps the server from applying a content coding of its own,
  10137. // so the hand-crafted Content-Encoding below survives.
  10138. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10139. res.set_content(gzipped, "image/jpeg");
  10140. res.set_header("Content-Encoding", "gzip");
  10141. });
  10142. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10143. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10144. res.set_content(gzipped, "image/jpeg");
  10145. res.set_header("Content-Encoding", "GZIP");
  10146. });
  10147. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10148. auto se = detail::scope_exit([&] {
  10149. svr.stop();
  10150. t.join();
  10151. ASSERT_FALSE(svr.is_running());
  10152. });
  10153. svr.wait_until_ready();
  10154. Client cli(HOST, PORT);
  10155. {
  10156. auto res = cli.Get("/gzipped");
  10157. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10159. EXPECT_EQ("Hello World!", res->body);
  10160. #else
  10161. ASSERT_FALSE(res);
  10162. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10163. #endif
  10164. }
  10165. {
  10166. // open_stream() must behave the same way.
  10167. auto handle = cli.open_stream("GET", "/gzipped");
  10168. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10169. ASSERT_TRUE(handle.is_valid());
  10170. std::string received;
  10171. char buf[256];
  10172. ssize_t n;
  10173. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10174. received.append(buf, static_cast<size_t>(n));
  10175. }
  10176. EXPECT_EQ("Hello World!", received);
  10177. #else
  10178. EXPECT_FALSE(handle.is_valid());
  10179. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10180. #endif
  10181. }
  10182. {
  10183. // A differently-cased coding must not be mistaken for an unknown one, or
  10184. // the body would be handed back still compressed.
  10185. auto res = cli.Get("/gzipped-uppercase");
  10186. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10188. EXPECT_EQ("Hello World!", res->body);
  10189. #else
  10190. ASSERT_FALSE(res);
  10191. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10192. #endif
  10193. }
  10194. }
  10195. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10196. // the same message as the comma-joined one, so both have to be read the same
  10197. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10198. // single gzip coding, and a body the sender says was encoded twice was handed
  10199. // back after one pass, still compressed but presented as decoded.
  10200. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10201. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10202. Server svr;
  10203. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10204. res.set_content(body, "image/jpeg");
  10205. res.headers.emplace("Content-Encoding", "gzip");
  10206. res.headers.emplace("Content-Encoding", "gzip");
  10207. });
  10208. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10209. res.set_content(body, "image/jpeg");
  10210. res.set_header("Content-Encoding", "gzip, gzip");
  10211. });
  10212. auto port = svr.bind_to_any_port(HOST);
  10213. thread t = thread([&]() { svr.listen_after_bind(); });
  10214. auto se = detail::scope_exit([&] {
  10215. svr.stop();
  10216. t.join();
  10217. ASSERT_FALSE(svr.is_running());
  10218. });
  10219. svr.wait_until_ready();
  10220. Client cli(HOST, port);
  10221. // Two codings is not something cpp-httplib decodes, so both representations
  10222. // take the pass-through path rather than one of them being gunzipped once.
  10223. for (const char *path : {"/split", "/joined"}) {
  10224. auto res = cli.Get(path);
  10225. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10226. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10227. EXPECT_EQ(body, res->body) << path;
  10228. }
  10229. }
  10230. // Regression test for DoS vulnerability: a malicious server sending a response
  10231. // without Content-Length header must not cause unbounded memory consumption on
  10232. // the client side. The client should stop reading after a reasonable limit,
  10233. // similar to the server-side set_payload_max_length protection.
  10234. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10235. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10236. #ifndef _WIN32
  10237. signal(SIGPIPE, SIG_IGN);
  10238. #endif
  10239. auto server_thread = std::thread([] {
  10240. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10241. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10242. default_socket_options(srv);
  10243. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10244. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10245. sockaddr_in addr{};
  10246. addr.sin_family = AF_INET;
  10247. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10248. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10249. int opt = 1;
  10250. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10251. #ifdef _WIN32
  10252. reinterpret_cast<const char *>(&opt),
  10253. #else
  10254. &opt,
  10255. #endif
  10256. sizeof(opt));
  10257. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10258. ::listen(srv, 1);
  10259. sockaddr_in cli_addr{};
  10260. socklen_t cli_len = sizeof(cli_addr);
  10261. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10262. if (cli != INVALID_SOCKET) {
  10263. char buf[4096];
  10264. ::recv(cli, buf, sizeof(buf), 0);
  10265. // Malicious response: no Content-Length, no chunked encoding
  10266. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10267. "Connection: close\r\n"
  10268. "\r\n";
  10269. ::send(cli,
  10270. #ifdef _WIN32
  10271. static_cast<const char *>(response_header.c_str()),
  10272. static_cast<int>(response_header.size()),
  10273. #else
  10274. response_header.c_str(), response_header.size(),
  10275. #endif
  10276. 0);
  10277. // Send 10MB of data
  10278. std::string chunk(64 * 1024, 'A');
  10279. size_t total_sent = 0;
  10280. while (total_sent < MALICIOUS_DATA_SIZE) {
  10281. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  10282. auto sent = ::send(cli,
  10283. #ifdef _WIN32
  10284. static_cast<const char *>(chunk.c_str()),
  10285. static_cast<int>(to_send),
  10286. #else
  10287. chunk.c_str(), to_send,
  10288. #endif
  10289. 0);
  10290. if (sent <= 0) break;
  10291. total_sent += static_cast<size_t>(sent);
  10292. }
  10293. detail::close_socket(cli);
  10294. }
  10295. detail::close_socket(srv);
  10296. });
  10297. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10298. size_t total_read = 0;
  10299. {
  10300. Client cli("127.0.0.1", PORT + 2);
  10301. cli.set_read_timeout(5, 0);
  10302. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10303. auto stream = cli.open_stream("GET", "/malicious");
  10304. ASSERT_TRUE(stream.is_valid());
  10305. char buffer[64 * 1024];
  10306. ssize_t n;
  10307. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10308. total_read += static_cast<size_t>(n);
  10309. }
  10310. } // StreamHandle and Client destroyed here, closing the socket
  10311. server_thread.join();
  10312. // With set_payload_max_length, the client must stop reading before consuming
  10313. // all 10MB. The read loop should be cut off at or near the configured limit.
  10314. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  10315. << "Client read " << total_read << " bytes, exceeding the configured "
  10316. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  10317. }
  10318. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  10319. // the entire response body without truncation.
  10320. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  10321. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  10322. #ifndef _WIN32
  10323. signal(SIGPIPE, SIG_IGN);
  10324. #endif
  10325. auto server_thread = std::thread([] {
  10326. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10327. default_socket_options(srv);
  10328. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10329. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10330. sockaddr_in addr{};
  10331. addr.sin_family = AF_INET;
  10332. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10333. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10334. int opt = 1;
  10335. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10336. #ifdef _WIN32
  10337. reinterpret_cast<const char *>(&opt),
  10338. #else
  10339. &opt,
  10340. #endif
  10341. sizeof(opt));
  10342. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10343. ::listen(srv, 1);
  10344. sockaddr_in cli_addr{};
  10345. socklen_t cli_len = sizeof(cli_addr);
  10346. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10347. if (cli != INVALID_SOCKET) {
  10348. char buf[4096];
  10349. ::recv(cli, buf, sizeof(buf), 0);
  10350. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10351. "Connection: close\r\n"
  10352. "\r\n";
  10353. ::send(cli,
  10354. #ifdef _WIN32
  10355. static_cast<const char *>(response_header.c_str()),
  10356. static_cast<int>(response_header.size()),
  10357. #else
  10358. response_header.c_str(), response_header.size(),
  10359. #endif
  10360. 0);
  10361. std::string chunk(64 * 1024, 'A');
  10362. size_t total_sent = 0;
  10363. while (total_sent < DATA_SIZE) {
  10364. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10365. auto sent = ::send(cli,
  10366. #ifdef _WIN32
  10367. static_cast<const char *>(chunk.c_str()),
  10368. static_cast<int>(to_send),
  10369. #else
  10370. chunk.c_str(), to_send,
  10371. #endif
  10372. 0);
  10373. if (sent <= 0) break;
  10374. total_sent += static_cast<size_t>(sent);
  10375. }
  10376. #ifdef _WIN32
  10377. ::shutdown(cli, SD_SEND);
  10378. #else
  10379. ::shutdown(cli, SHUT_WR);
  10380. #endif
  10381. // Drain until the client closes its end, ensuring all data is delivered
  10382. char drain[1024];
  10383. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10384. detail::close_socket(cli);
  10385. }
  10386. detail::close_socket(srv);
  10387. });
  10388. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10389. size_t total_read = 0;
  10390. {
  10391. Client cli("127.0.0.1", PORT + 2);
  10392. cli.set_read_timeout(5, 0);
  10393. cli.set_payload_max_length(0); // 0 means no limit
  10394. auto stream = cli.open_stream("GET", "/data");
  10395. ASSERT_TRUE(stream.is_valid());
  10396. char buffer[64 * 1024];
  10397. ssize_t n;
  10398. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10399. total_read += static_cast<size_t>(n);
  10400. }
  10401. }
  10402. server_thread.join();
  10403. EXPECT_EQ(total_read, DATA_SIZE)
  10404. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  10405. << " bytes without truncation, but only read " << total_read << " bytes.";
  10406. }
  10407. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  10408. // enormous Content-Length must not cause the client to pre-allocate a huge
  10409. // response body buffer. The reservation is capped at payload_max_length_, and
  10410. // the read itself fails when the body exceeds the limit.
  10411. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  10412. #ifndef _WIN32
  10413. signal(SIGPIPE, SIG_IGN);
  10414. #endif
  10415. auto server_thread = std::thread([] {
  10416. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10417. default_socket_options(srv);
  10418. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10419. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10420. sockaddr_in addr{};
  10421. addr.sin_family = AF_INET;
  10422. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10423. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10424. int opt = 1;
  10425. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10426. #ifdef _WIN32
  10427. reinterpret_cast<const char *>(&opt),
  10428. #else
  10429. &opt,
  10430. #endif
  10431. sizeof(opt));
  10432. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10433. ::listen(srv, 1);
  10434. sockaddr_in cli_addr{};
  10435. socklen_t cli_len = sizeof(cli_addr);
  10436. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10437. if (cli != INVALID_SOCKET) {
  10438. char buf[4096];
  10439. ::recv(cli, buf, sizeof(buf), 0);
  10440. // Malicious response: claim a 20GB body but send only a tiny payload.
  10441. std::string response = "HTTP/1.1 200 OK\r\n"
  10442. "Content-Length: 20000000000\r\n"
  10443. "\r\n"
  10444. "abc";
  10445. ::send(cli,
  10446. #ifdef _WIN32
  10447. static_cast<const char *>(response.c_str()),
  10448. static_cast<int>(response.size()),
  10449. #else
  10450. response.c_str(), response.size(),
  10451. #endif
  10452. 0);
  10453. detail::close_socket(cli);
  10454. }
  10455. detail::close_socket(srv);
  10456. });
  10457. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10458. {
  10459. Client cli("127.0.0.1", PORT + 2);
  10460. cli.set_read_timeout(5, 0);
  10461. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  10462. // result in a 20GB pre-allocation. The Get() call is expected to fail
  10463. // (server claims more bytes than payload_max_length permits), but it must
  10464. // not exhaust memory before getting there.
  10465. auto res = cli.Get("/malicious");
  10466. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  10467. }
  10468. server_thread.join();
  10469. }
  10470. // Verify that content_receiver bypasses the default payload_max_length,
  10471. // allowing streaming downloads larger than 100MB without requiring an explicit
  10472. // set_payload_max_length call.
  10473. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  10474. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10475. #ifndef _WIN32
  10476. signal(SIGPIPE, SIG_IGN);
  10477. #endif
  10478. auto server_thread = std::thread([] {
  10479. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10480. default_socket_options(srv);
  10481. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10482. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10483. sockaddr_in addr{};
  10484. addr.sin_family = AF_INET;
  10485. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10486. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10487. int opt = 1;
  10488. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10489. #ifdef _WIN32
  10490. reinterpret_cast<const char *>(&opt),
  10491. #else
  10492. &opt,
  10493. #endif
  10494. sizeof(opt));
  10495. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10496. ::listen(srv, 1);
  10497. sockaddr_in cli_addr{};
  10498. socklen_t cli_len = sizeof(cli_addr);
  10499. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10500. if (cli != INVALID_SOCKET) {
  10501. char buf[4096];
  10502. ::recv(cli, buf, sizeof(buf), 0);
  10503. // Response with Content-Length larger than default 100MB limit
  10504. auto content_length = std::to_string(DATA_SIZE);
  10505. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10506. "Content-Length: " +
  10507. content_length +
  10508. "\r\n"
  10509. "Connection: close\r\n"
  10510. "\r\n";
  10511. ::send(cli,
  10512. #ifdef _WIN32
  10513. static_cast<const char *>(response_header.c_str()),
  10514. static_cast<int>(response_header.size()),
  10515. #else
  10516. response_header.c_str(), response_header.size(),
  10517. #endif
  10518. 0);
  10519. std::string chunk(64 * 1024, 'A');
  10520. size_t total_sent = 0;
  10521. while (total_sent < DATA_SIZE) {
  10522. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10523. auto sent = ::send(cli,
  10524. #ifdef _WIN32
  10525. static_cast<const char *>(chunk.c_str()),
  10526. static_cast<int>(to_send),
  10527. #else
  10528. chunk.c_str(), to_send,
  10529. #endif
  10530. 0);
  10531. if (sent <= 0) break;
  10532. total_sent += static_cast<size_t>(sent);
  10533. }
  10534. detail::close_socket(cli);
  10535. }
  10536. detail::close_socket(srv);
  10537. });
  10538. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10539. size_t total_received = 0;
  10540. {
  10541. Client cli("127.0.0.1", PORT + 2);
  10542. cli.set_read_timeout(10, 0);
  10543. // Do NOT call set_payload_max_length — use the default 100MB limit
  10544. auto res =
  10545. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10546. total_received += data_length;
  10547. return true;
  10548. });
  10549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10550. EXPECT_EQ(StatusCode::OK_200, res->status);
  10551. }
  10552. server_thread.join();
  10553. EXPECT_EQ(total_received, DATA_SIZE)
  10554. << "With content_receiver, the client should read all " << DATA_SIZE
  10555. << " bytes despite the default 100MB payload_max_length, but only read "
  10556. << total_received << " bytes.";
  10557. }
  10558. // Verify that an explicit set_payload_max_length smaller than the response is
  10559. // enforced even when a content_receiver is used.
  10560. TEST(ClientVulnerabilityTest,
  10561. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  10562. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10563. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  10564. #ifndef _WIN32
  10565. signal(SIGPIPE, SIG_IGN);
  10566. #endif
  10567. auto server_thread = std::thread([] {
  10568. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10569. default_socket_options(srv);
  10570. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10571. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10572. sockaddr_in addr{};
  10573. addr.sin_family = AF_INET;
  10574. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10575. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10576. int opt = 1;
  10577. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10578. #ifdef _WIN32
  10579. reinterpret_cast<const char *>(&opt),
  10580. #else
  10581. &opt,
  10582. #endif
  10583. sizeof(opt));
  10584. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10585. ::listen(srv, 1);
  10586. sockaddr_in cli_addr{};
  10587. socklen_t cli_len = sizeof(cli_addr);
  10588. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10589. if (cli != INVALID_SOCKET) {
  10590. char buf[4096];
  10591. ::recv(cli, buf, sizeof(buf), 0);
  10592. auto content_length = std::to_string(DATA_SIZE);
  10593. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10594. "Content-Length: " +
  10595. content_length +
  10596. "\r\n"
  10597. "Connection: close\r\n"
  10598. "\r\n";
  10599. ::send(cli,
  10600. #ifdef _WIN32
  10601. static_cast<const char *>(response_header.c_str()),
  10602. static_cast<int>(response_header.size()),
  10603. #else
  10604. response_header.c_str(), response_header.size(),
  10605. #endif
  10606. 0);
  10607. std::string chunk(64 * 1024, 'A');
  10608. size_t total_sent = 0;
  10609. while (total_sent < DATA_SIZE) {
  10610. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10611. auto sent = ::send(cli,
  10612. #ifdef _WIN32
  10613. static_cast<const char *>(chunk.c_str()),
  10614. static_cast<int>(to_send),
  10615. #else
  10616. chunk.c_str(), to_send,
  10617. #endif
  10618. 0);
  10619. if (sent <= 0) break;
  10620. total_sent += static_cast<size_t>(sent);
  10621. }
  10622. detail::close_socket(cli);
  10623. }
  10624. detail::close_socket(srv);
  10625. });
  10626. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10627. size_t total_received = 0;
  10628. {
  10629. Client cli("127.0.0.1", PORT + 2);
  10630. cli.set_read_timeout(10, 0);
  10631. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  10632. auto res =
  10633. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10634. total_received += data_length;
  10635. return true;
  10636. });
  10637. // Should fail because 200MB exceeds the explicit 150MB limit
  10638. EXPECT_FALSE(res);
  10639. }
  10640. server_thread.join();
  10641. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  10642. << "Client with content_receiver should respect the explicit "
  10643. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  10644. << total_received << " bytes.";
  10645. }
  10646. // Verify that an explicit set_payload_max_length larger than the response
  10647. // allows the content_receiver to read all data successfully.
  10648. TEST(ClientVulnerabilityTest,
  10649. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  10650. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  10651. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  10652. #ifndef _WIN32
  10653. signal(SIGPIPE, SIG_IGN);
  10654. #endif
  10655. auto server_thread = std::thread([] {
  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. auto content_length = std::to_string(DATA_SIZE);
  10681. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10682. "Content-Length: " +
  10683. content_length +
  10684. "\r\n"
  10685. "Connection: close\r\n"
  10686. "\r\n";
  10687. ::send(cli,
  10688. #ifdef _WIN32
  10689. static_cast<const char *>(response_header.c_str()),
  10690. static_cast<int>(response_header.size()),
  10691. #else
  10692. response_header.c_str(), response_header.size(),
  10693. #endif
  10694. 0);
  10695. std::string chunk(64 * 1024, 'A');
  10696. size_t total_sent = 0;
  10697. while (total_sent < DATA_SIZE) {
  10698. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10699. auto sent = ::send(cli,
  10700. #ifdef _WIN32
  10701. static_cast<const char *>(chunk.c_str()),
  10702. static_cast<int>(to_send),
  10703. #else
  10704. chunk.c_str(), to_send,
  10705. #endif
  10706. 0);
  10707. if (sent <= 0) break;
  10708. total_sent += static_cast<size_t>(sent);
  10709. }
  10710. #ifdef _WIN32
  10711. ::shutdown(cli, SD_SEND);
  10712. #else
  10713. ::shutdown(cli, SHUT_WR);
  10714. #endif
  10715. char drain[1024];
  10716. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10717. detail::close_socket(cli);
  10718. }
  10719. detail::close_socket(srv);
  10720. });
  10721. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10722. size_t total_received = 0;
  10723. {
  10724. Client cli("127.0.0.1", PORT + 2);
  10725. cli.set_read_timeout(10, 0);
  10726. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  10727. auto res =
  10728. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10729. total_received += data_length;
  10730. return true;
  10731. });
  10732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10733. EXPECT_EQ(StatusCode::OK_200, res->status);
  10734. }
  10735. server_thread.join();
  10736. EXPECT_EQ(total_received, DATA_SIZE)
  10737. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  10738. << " bytes (larger than " << DATA_SIZE
  10739. << " bytes response), content_receiver should read all data, but only "
  10740. "read "
  10741. << total_received << " bytes.";
  10742. }
  10743. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  10744. // Regression test for "zip bomb" attack on the client side: a malicious server
  10745. // sends a small gzip-compressed response that decompresses to a huge payload.
  10746. // The client must enforce payload_max_length on the decompressed size.
  10747. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  10748. constexpr size_t DECOMPRESSED_SIZE =
  10749. 10 * 1024 * 1024; // 10MB after decompression
  10750. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10751. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  10752. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  10753. std::string compressed;
  10754. {
  10755. httplib::detail::gzip_compressor compressor;
  10756. bool ok =
  10757. compressor.compress(uncompressed.data(), uncompressed.size(),
  10758. /*last=*/true, [&](const char *buf, size_t len) {
  10759. compressed.append(buf, len);
  10760. return true;
  10761. });
  10762. ASSERT_TRUE(ok);
  10763. }
  10764. // Sanity: compressed data should be much smaller than the decompressed size
  10765. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  10766. #ifndef _WIN32
  10767. signal(SIGPIPE, SIG_IGN);
  10768. #endif
  10769. // Set up the listening socket in the main thread so the server is guaranteed
  10770. // to be ready before the client connects (eliminates race condition).
  10771. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10772. default_socket_options(srv);
  10773. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10774. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10775. sockaddr_in addr{};
  10776. addr.sin_family = AF_INET;
  10777. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  10778. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10779. int opt = 1;
  10780. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10781. #ifdef _WIN32
  10782. reinterpret_cast<const char *>(&opt),
  10783. #else
  10784. &opt,
  10785. #endif
  10786. sizeof(opt));
  10787. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  10788. ASSERT_EQ(0, ::listen(srv, 1));
  10789. auto server_thread = std::thread([&compressed, srv] {
  10790. sockaddr_in cli_addr{};
  10791. socklen_t cli_len = sizeof(cli_addr);
  10792. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10793. if (cli != INVALID_SOCKET) {
  10794. // Read the full HTTP request (until \r\n\r\n)
  10795. char buf[4096];
  10796. size_t total = 0;
  10797. while (total < sizeof(buf)) {
  10798. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  10799. if (n <= 0) break;
  10800. total += static_cast<size_t>(n);
  10801. // Check for end of headers
  10802. if (total >= 4) {
  10803. std::string req(buf, total);
  10804. if (req.find("\r\n\r\n") != std::string::npos) break;
  10805. }
  10806. }
  10807. // Malicious response: gzip-compressed body, no Content-Length
  10808. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10809. "Content-Encoding: gzip\r\n"
  10810. "Connection: close\r\n"
  10811. "\r\n";
  10812. ::send(cli,
  10813. #ifdef _WIN32
  10814. static_cast<const char *>(response_header.c_str()),
  10815. static_cast<int>(response_header.size()),
  10816. #else
  10817. response_header.c_str(), response_header.size(),
  10818. #endif
  10819. 0);
  10820. // Send the compressed payload (small on the wire, huge when decompressed)
  10821. size_t total_sent = 0;
  10822. while (total_sent < compressed.size()) {
  10823. auto to_send = std::min(compressed.size() - total_sent,
  10824. static_cast<size_t>(64 * 1024));
  10825. auto sent =
  10826. ::send(cli,
  10827. #ifdef _WIN32
  10828. static_cast<const char *>(compressed.c_str() + total_sent),
  10829. static_cast<int>(to_send),
  10830. #else
  10831. compressed.c_str() + total_sent, to_send,
  10832. #endif
  10833. 0);
  10834. if (sent <= 0) break;
  10835. total_sent += static_cast<size_t>(sent);
  10836. }
  10837. detail::close_socket(cli);
  10838. }
  10839. });
  10840. auto se = detail::scope_exit([&] {
  10841. detail::close_socket(srv);
  10842. server_thread.join();
  10843. });
  10844. size_t total_decompressed = 0;
  10845. {
  10846. Client cli("127.0.0.1", PORT + 3);
  10847. cli.set_read_timeout(5, 0);
  10848. cli.set_decompress(true);
  10849. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10850. auto stream = cli.open_stream("GET", "/zipbomb");
  10851. ASSERT_TRUE(stream.is_valid());
  10852. char buffer[64 * 1024];
  10853. ssize_t n;
  10854. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10855. total_decompressed += static_cast<size_t>(n);
  10856. }
  10857. }
  10858. // The decompressed size must be capped by payload_max_length. Without
  10859. // protection, the client would decompress the full 10MB from a tiny
  10860. // compressed payload, enabling a zip bomb DoS attack.
  10861. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10862. << "Client decompressed " << total_decompressed
  10863. << " bytes from a gzip response. The decompressed size should be "
  10864. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10865. }
  10866. #endif
  10867. TEST(HostAndPortPropertiesTest, NoSSL) {
  10868. httplib::Client cli("www.google.com", 1234);
  10869. ASSERT_EQ("www.google.com", cli.host());
  10870. ASSERT_EQ(1234, cli.port());
  10871. }
  10872. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10873. httplib::Client cli("www.google.com:1234");
  10874. ASSERT_EQ("www.google.com", cli.host());
  10875. ASSERT_EQ(1234, cli.port());
  10876. }
  10877. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10878. // Port number that overflows int — should not crash, client becomes invalid
  10879. httplib::Client cli("http://www.google.com:99999999999999999999");
  10880. ASSERT_FALSE(cli.is_valid());
  10881. }
  10882. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10883. // Port 99999 exceeds valid range (1-65535) — should not crash
  10884. httplib::Client cli("http://www.google.com:99999");
  10885. ASSERT_FALSE(cli.is_valid());
  10886. }
  10887. #ifdef CPPHTTPLIB_SSL_ENABLED
  10888. TEST(HostAndPortPropertiesTest, SSL) {
  10889. httplib::SSLClient cli("www.google.com");
  10890. ASSERT_EQ("www.google.com", cli.host());
  10891. ASSERT_EQ(443, cli.port());
  10892. }
  10893. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10894. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10895. std::string cert;
  10896. read_file(CA_CERT_FILE, cert);
  10897. httplib::SSLClient httplib_client("www.google.com");
  10898. // Load CA store first time
  10899. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10900. // Load CA store second time (update)
  10901. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10902. // Verify client is still valid and can make connections
  10903. httplib_client.enable_server_certificate_verification(true);
  10904. auto res = httplib_client.Get("/");
  10905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10906. // Google may return 200 or 301 depending on various factors
  10907. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10908. res->status == StatusCode::MovedPermanently_301);
  10909. }
  10910. TEST(SSLClientTest, ServerNameIndication_Online) {
  10911. auto host = "httpbingo.org";
  10912. auto path = std::string{"/get"};
  10913. SSLClient cli(host, 443);
  10914. auto res = cli.Get(path);
  10915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10916. ASSERT_EQ(StatusCode::OK_200, res->status);
  10917. }
  10918. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10919. // Use a site that will cause SSL verification failure due to self-signed cert
  10920. SSLClient cli("self-signed.badssl.com", 443);
  10921. cli.enable_server_certificate_verification(true);
  10922. auto res = cli.Get("/");
  10923. ASSERT_TRUE(!res);
  10924. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10925. // Verify backend error is captured for SSLServerVerification
  10926. // This occurs when certificate verification fails
  10927. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10928. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10929. EXPECT_NE(0UL, res.ssl_backend_error());
  10930. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10931. // For OpenSSL, ssl_error is 0 for verification errors
  10932. EXPECT_EQ(0, res.ssl_error());
  10933. #if !defined(_WIN32) || \
  10934. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10935. // On non-Windows or when Windows Schannel is disabled, the error comes
  10936. // from OpenSSL's verification
  10937. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10938. res.ssl_backend_error());
  10939. #endif
  10940. #endif
  10941. }
  10942. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10943. // Use a site where hostname doesn't match the certificate
  10944. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10945. SSLClient cli("wrong.host.badssl.com", 443);
  10946. cli.enable_server_certificate_verification(true);
  10947. cli.enable_server_hostname_verification(true);
  10948. auto res = cli.Get("/");
  10949. ASSERT_TRUE(!res);
  10950. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10951. // Verify backend error is captured for hostname verification failure
  10952. EXPECT_NE(0UL, res.ssl_backend_error());
  10953. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10954. // For OpenSSL, ssl_error is 0 for verification errors
  10955. EXPECT_EQ(0, res.ssl_error());
  10956. #if !defined(_WIN32) || \
  10957. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10958. // On non-Windows or when Windows Schannel is disabled, the error comes
  10959. // from OpenSSL's hostname verification
  10960. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10961. res.ssl_backend_error());
  10962. #endif
  10963. #endif
  10964. }
  10965. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10966. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10967. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10968. SSLClient cli("www.google.com", 443);
  10969. cli.enable_server_certificate_verification(true);
  10970. auto res = cli.Get("/");
  10971. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10972. }
  10973. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10974. SSLClient cli("www.google.com", 443);
  10975. cli.enable_server_certificate_verification(true);
  10976. cli.enable_windows_certificate_verification(false);
  10977. auto res = cli.Get("/");
  10978. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10979. }
  10980. #endif
  10981. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10982. Client cli("https://google.com");
  10983. auto res = cli.Get("/");
  10984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10985. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10986. }
  10987. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10988. SSLClient cli("google.com");
  10989. cli.set_ca_cert_path(CA_CERT_FILE);
  10990. auto res = cli.Get("/");
  10991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10992. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10993. }
  10994. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10995. SSLClient cli("google.com");
  10996. cli.enable_server_certificate_verification(true);
  10997. cli.set_ca_cert_path("hello");
  10998. auto res = cli.Get("/");
  10999. ASSERT_TRUE(!res);
  11000. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11001. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11002. // should be set
  11003. EXPECT_EQ(0, res.ssl_error());
  11004. // Verify backend error is captured for SSLLoadingCerts
  11005. // This error occurs when loading CA certificates fails
  11006. EXPECT_NE(0UL, res.ssl_backend_error());
  11007. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11008. // OpenSSL specific error codes:
  11009. // > openssl errstr 0x80000002
  11010. // error:80000002:system library::No such file or directory
  11011. // > openssl errstr 0xA000126
  11012. // error:0A000126:SSL routines::unexpected eof while reading
  11013. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11014. res.ssl_backend_error() == 0xA000126);
  11015. #endif
  11016. }
  11017. TEST(SSLClientTest, ServerCertificateVerification4) {
  11018. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11019. ASSERT_TRUE(svr.is_valid());
  11020. svr.Get("/test", [&](const Request &, Response &res) {
  11021. res.set_content("test", "text/plain");
  11022. svr.stop();
  11023. ASSERT_TRUE(true);
  11024. });
  11025. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11026. auto se = detail::scope_exit([&] {
  11027. t.join();
  11028. ASSERT_FALSE(svr.is_running());
  11029. });
  11030. svr.wait_until_ready();
  11031. SSLClient cli("127.0.0.1", PORT);
  11032. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11033. cli.enable_server_certificate_verification(true);
  11034. cli.set_connection_timeout(30);
  11035. auto res = cli.Get("/test");
  11036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11037. ASSERT_EQ(StatusCode::OK_200, res->status);
  11038. }
  11039. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11040. std::string cert;
  11041. read_file(CA_CERT_FILE, cert);
  11042. SSLClient cli("google.com");
  11043. cli.load_ca_cert_store(cert.data(), cert.size());
  11044. const auto res = cli.Get("/");
  11045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11046. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11047. }
  11048. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11049. // clang-format off
  11050. static constexpr char cert[] =
  11051. "GlobalSign Root CA\n"
  11052. "==================\n"
  11053. "-----BEGIN CERTIFICATE-----\n"
  11054. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11055. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11056. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11057. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11058. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11059. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11060. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11061. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11062. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11063. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11064. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11065. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11066. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11067. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11068. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11069. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11070. "-----END CERTIFICATE-----\n";
  11071. // clang-format on
  11072. SSLClient cli("google.com");
  11073. cli.load_ca_cert_store(cert, sizeof(cert));
  11074. const auto res = cli.Get("/");
  11075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11076. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11077. }
  11078. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11079. SSLClient cli("www.youtube.com");
  11080. cli.set_ca_cert_path(CA_CERT_FILE);
  11081. cli.enable_server_certificate_verification(true);
  11082. cli.set_follow_location(true);
  11083. auto res = cli.Get("/");
  11084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11085. ASSERT_EQ(StatusCode::OK_200, res->status);
  11086. }
  11087. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11088. SSLClient cli("wWw.YouTube.Com");
  11089. cli.set_ca_cert_path(CA_CERT_FILE);
  11090. cli.enable_server_certificate_verification(true);
  11091. cli.enable_server_hostname_verification(true);
  11092. cli.set_follow_location(true);
  11093. auto res = cli.Get("/");
  11094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11095. ASSERT_EQ(StatusCode::OK_200, res->status);
  11096. }
  11097. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11098. SSLClient cli("gOoGlE.COm");
  11099. cli.enable_server_certificate_verification(true);
  11100. cli.enable_server_hostname_verification(true);
  11101. cli.set_follow_location(true);
  11102. auto res = cli.Get("/");
  11103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11104. ASSERT_EQ(StatusCode::OK_200, res->status);
  11105. }
  11106. TEST(SSLClientTest, Issue2004_Online) {
  11107. Client client("https://google.com");
  11108. client.set_follow_location(true);
  11109. auto res = client.Get("/");
  11110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11111. ASSERT_EQ(StatusCode::OK_200, res->status);
  11112. auto body = res->body;
  11113. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11114. }
  11115. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11116. // Create SSLClient with invalid cert/key to make is_valid() return false
  11117. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11118. "nonexistent_key.pem");
  11119. // is_valid() should be false due to cert loading failure
  11120. ASSERT_FALSE(cli.is_valid());
  11121. auto res = cli.Get("/");
  11122. ASSERT_FALSE(res);
  11123. EXPECT_EQ(Error::SSLConnection, res.error());
  11124. }
  11125. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11126. // Test for Issue #2251: SSL error not properly reported when client cert
  11127. // and key paths are swapped or mismatched
  11128. // This simulates the scenario where user accidentally swaps the cert and key
  11129. // files
  11130. // Using client cert file as private key and vice versa (completely wrong)
  11131. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11132. // Should fail validation due to cert/key mismatch
  11133. ASSERT_FALSE(cli.is_valid());
  11134. // Attempt to make a request should fail with proper error
  11135. auto res = cli.Get("/");
  11136. ASSERT_FALSE(res);
  11137. EXPECT_EQ(Error::SSLConnection, res.error());
  11138. // SSL error should be recorded in the Result object (this is the key fix for
  11139. // Issue #2251)
  11140. auto backend_error = res.ssl_backend_error();
  11141. EXPECT_NE(0u, backend_error);
  11142. }
  11143. // Tests cert/key mismatch detection at the TLS context level
  11144. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11145. // Test that using mismatched cert/key causes connection failure.
  11146. // We verify this at the SSLClient level rather than through internal
  11147. // TLS API functions.
  11148. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11149. cli.enable_server_certificate_verification(false);
  11150. cli.set_connection_timeout(2);
  11151. // The mismatch should cause a connection or handshake error
  11152. auto res = cli.Get("/test");
  11153. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11154. // Either way, the request should fail
  11155. EXPECT_FALSE(res);
  11156. }
  11157. #endif
  11158. #if 0
  11159. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11160. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11161. ASSERT_TRUE(cli != nullptr);
  11162. cli->set_address_family(AF_INET6);
  11163. cli->set_interface("en0");
  11164. auto res = cli->Get("/get");
  11165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11166. ASSERT_EQ(StatusCode::OK_200, res->status);
  11167. }
  11168. #endif
  11169. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11170. #ifdef CPPHTTPLIB_SSL_ENABLED
  11171. void ClientCertPresent(
  11172. const std::string &client_cert_file,
  11173. const std::string &client_private_key_file,
  11174. const std::string &client_encrypted_private_key_pass = std::string()) {
  11175. using namespace httplib::tls;
  11176. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11177. CLIENT_CA_CERT_DIR);
  11178. ASSERT_TRUE(svr.is_valid());
  11179. svr.Get("/test", [&](const Request &req, Response &res) {
  11180. res.set_content("test", "text/plain");
  11181. auto cert = req.peer_cert();
  11182. ASSERT_TRUE(static_cast<bool>(cert));
  11183. std::string common_name = cert.subject_cn();
  11184. EXPECT_EQ("Common Name", common_name);
  11185. });
  11186. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11187. auto se = detail::scope_exit([&] {
  11188. svr.stop();
  11189. t.join();
  11190. ASSERT_FALSE(svr.is_running());
  11191. });
  11192. svr.wait_until_ready();
  11193. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11194. client_encrypted_private_key_pass);
  11195. cli.enable_server_certificate_verification(false);
  11196. cli.set_connection_timeout(30);
  11197. auto res = cli.Get("/test");
  11198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11199. ASSERT_EQ(StatusCode::OK_200, res->status);
  11200. }
  11201. TEST(SSLClientServerTest, ClientCertPresent) {
  11202. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11203. }
  11204. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11205. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11206. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11207. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11208. }
  11209. // PEM memory-based constructor tests (works with all TLS backends)
  11210. void PemMemoryClientCertPresent(
  11211. const std::string &client_cert_file,
  11212. const std::string &client_private_key_file,
  11213. const std::string &client_encrypted_private_key_pass = std::string()) {
  11214. // Read PEM files into memory
  11215. std::string server_cert_pem, server_key_pem;
  11216. std::string client_ca_pem;
  11217. std::string client_cert_pem, client_key_pem;
  11218. read_file(SERVER_CERT_FILE, server_cert_pem);
  11219. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11220. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11221. read_file(client_cert_file, client_cert_pem);
  11222. read_file(client_private_key_file, client_key_pem);
  11223. // Create server with PEM memory
  11224. SSLServer::PemMemory server_pem = {
  11225. server_cert_pem.c_str(),
  11226. server_cert_pem.size(),
  11227. server_key_pem.c_str(),
  11228. server_key_pem.size(),
  11229. client_ca_pem.c_str(),
  11230. client_ca_pem.size(),
  11231. nullptr // no password for server key
  11232. };
  11233. SSLServer svr(server_pem);
  11234. ASSERT_TRUE(svr.is_valid());
  11235. svr.Get("/test", [&](const Request &, Response &res) {
  11236. res.set_content("test", "text/plain");
  11237. });
  11238. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11239. auto se = detail::scope_exit([&] {
  11240. svr.stop();
  11241. t.join();
  11242. ASSERT_FALSE(svr.is_running());
  11243. });
  11244. svr.wait_until_ready();
  11245. // Create client with PEM memory
  11246. const char *password = client_encrypted_private_key_pass.empty()
  11247. ? nullptr
  11248. : client_encrypted_private_key_pass.c_str();
  11249. SSLClient::PemMemory client_pem = {
  11250. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  11251. client_key_pem.size(), password};
  11252. SSLClient cli(HOST, PORT, client_pem);
  11253. cli.enable_server_certificate_verification(false);
  11254. cli.set_connection_timeout(30);
  11255. auto res = cli.Get("/test");
  11256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11257. ASSERT_EQ(StatusCode::OK_200, res->status);
  11258. }
  11259. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  11260. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11261. }
  11262. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  11263. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11264. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11265. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11266. }
  11267. TEST(SSLClientServerTest, ClientCertMissing) {
  11268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11269. CLIENT_CA_CERT_DIR);
  11270. ASSERT_TRUE(svr.is_valid());
  11271. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  11272. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11273. auto se = detail::scope_exit([&] {
  11274. svr.stop();
  11275. t.join();
  11276. ASSERT_FALSE(svr.is_running());
  11277. });
  11278. svr.wait_until_ready();
  11279. SSLClient cli(HOST, PORT);
  11280. cli.set_connection_timeout(30);
  11281. auto res = cli.Get("/test");
  11282. ASSERT_TRUE(!res);
  11283. // When client cert is missing and server requires it, connection fails
  11284. // Error type depends on backend implementation
  11285. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11286. res.error() == Error::SSLConnection);
  11287. // Verify backend error is captured
  11288. // Note: This test may have different error codes depending on the exact
  11289. // verification failure
  11290. EXPECT_NE(0UL, res.ssl_backend_error());
  11291. }
  11292. TEST(SSLClientServerTest, TrustDirOptional) {
  11293. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11294. ASSERT_TRUE(svr.is_valid());
  11295. svr.Get("/test", [&](const Request &, Response &res) {
  11296. res.set_content("test", "text/plain");
  11297. });
  11298. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11299. auto se = detail::scope_exit([&] {
  11300. svr.stop();
  11301. t.join();
  11302. ASSERT_FALSE(svr.is_running());
  11303. });
  11304. svr.wait_until_ready();
  11305. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11306. cli.enable_server_certificate_verification(false);
  11307. cli.set_connection_timeout(30);
  11308. auto res = cli.Get("/test");
  11309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11310. ASSERT_EQ(StatusCode::OK_200, res->status);
  11311. }
  11312. TEST(SSLClientServerTest, SSLConnectTimeout) {
  11313. class NoListenSSLServer : public SSLServer {
  11314. public:
  11315. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  11316. const char *client_ca_cert_file_path,
  11317. const char *client_ca_cert_dir_path = nullptr)
  11318. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  11319. client_ca_cert_dir_path),
  11320. stop_(false) {}
  11321. std::atomic_bool stop_;
  11322. private:
  11323. bool process_and_close_socket(socket_t /*sock*/) override {
  11324. // Don't create SSL context
  11325. while (!stop_.load()) {
  11326. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11327. }
  11328. return true;
  11329. }
  11330. };
  11331. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11332. CLIENT_CA_CERT_FILE);
  11333. ASSERT_TRUE(svr.is_valid());
  11334. svr.Get("/test", [&](const Request &, Response &res) {
  11335. res.set_content("test", "text/plain");
  11336. });
  11337. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11338. auto se = detail::scope_exit([&] {
  11339. svr.stop_ = true;
  11340. svr.stop();
  11341. t.join();
  11342. ASSERT_FALSE(svr.is_running());
  11343. });
  11344. svr.wait_until_ready();
  11345. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11346. cli.enable_server_certificate_verification(false);
  11347. cli.set_connection_timeout(1);
  11348. auto res = cli.Get("/test");
  11349. ASSERT_TRUE(!res);
  11350. EXPECT_EQ(Error::SSLConnection, res.error());
  11351. // Timeout results in WantRead error code (maps to backend-specific value)
  11352. EXPECT_NE(0, res.ssl_error());
  11353. }
  11354. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  11355. // Test SSLServer with client certificate verification using the standard
  11356. // constructor (ContextSetupCallback is tested by backend-specific tests)
  11357. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11358. CLIENT_CA_CERT_DIR);
  11359. ASSERT_TRUE(svr.is_valid());
  11360. svr.Get("/test", [&](const Request &req, Response &res) {
  11361. res.set_content("test", "text/plain");
  11362. auto cert = req.peer_cert();
  11363. ASSERT_TRUE(static_cast<bool>(cert));
  11364. auto common_name = cert.subject_cn();
  11365. EXPECT_EQ("Common Name", common_name);
  11366. });
  11367. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11368. auto se = detail::scope_exit([&] {
  11369. svr.stop();
  11370. t.join();
  11371. ASSERT_FALSE(svr.is_running());
  11372. });
  11373. svr.wait_until_ready();
  11374. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11375. cli.enable_server_certificate_verification(false);
  11376. cli.set_connection_timeout(30);
  11377. auto res = cli.Get("/test");
  11378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11379. ASSERT_EQ(StatusCode::OK_200, res->status);
  11380. }
  11381. // Test verify_hostname for both OpenSSL and MbedTLS backends
  11382. // Verifies that wildcard matching and exact matching work consistently
  11383. TEST(SSLClientServerTest, TlsVerifyHostname) {
  11384. using namespace httplib::tls;
  11385. // We need a running server to test against
  11386. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11387. ASSERT_TRUE(svr.is_valid());
  11388. svr.Get("/test", [](const Request &, Response &res) {
  11389. res.set_content("ok", "text/plain");
  11390. });
  11391. thread t([&]() { svr.listen(HOST, PORT); });
  11392. auto se = detail::scope_exit([&] {
  11393. svr.stop();
  11394. t.join();
  11395. });
  11396. svr.wait_until_ready();
  11397. bool verify_callback_called = false;
  11398. bool verify_result_wrong = false;
  11399. SSLClient cli(HOST, PORT);
  11400. cli.enable_server_certificate_verification(true);
  11401. cli.set_ca_cert_path(CA_CERT_FILE);
  11402. cli.set_connection_timeout(5);
  11403. // Note: Test certificate has CN="Common Name", not "localhost"
  11404. bool verify_result_cn = false;
  11405. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11406. verify_callback_called = true;
  11407. if (!ctx.cert) return false;
  11408. // Test 1: "Common Name" should match (our test server cert CN)
  11409. verify_result_cn = ctx.check_hostname("Common Name");
  11410. // Test 2: wrong hostname should not match
  11411. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  11412. return true; // Accept for the purpose of this test
  11413. });
  11414. auto res = cli.Get("/test");
  11415. // The request may succeed or fail depending on cert configuration
  11416. // but the callback should have been called
  11417. ASSERT_TRUE(verify_callback_called)
  11418. << "Verify callback should have been called";
  11419. // CN="Common Name" should match our test certificate
  11420. //
  11421. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  11422. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  11423. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  11424. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  11425. // <openssl/base.h>, which is included transitively when
  11426. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  11427. #if defined(OPENSSL_IS_BORINGSSL)
  11428. EXPECT_FALSE(verify_result_cn)
  11429. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  11430. #else
  11431. EXPECT_TRUE(verify_result_cn)
  11432. << "verify_hostname should match 'Common Name' (certificate CN)";
  11433. #endif
  11434. // Wrong hostname should not match
  11435. EXPECT_FALSE(verify_result_wrong)
  11436. << "verify_hostname should not match 'wronghost.example.com'";
  11437. }
  11438. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  11439. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  11440. // X509_check_ip behavior and must hold for every backend.
  11441. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  11442. using namespace httplib::tls;
  11443. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  11444. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  11445. ASSERT_TRUE(svr.is_valid());
  11446. svr.Get("/test", [](const Request &, Response &res) {
  11447. res.set_content("ok", "text/plain");
  11448. });
  11449. thread t([&]() { svr.listen(HOST, PORT); });
  11450. auto se = detail::scope_exit([&] {
  11451. svr.stop();
  11452. t.join();
  11453. });
  11454. svr.wait_until_ready();
  11455. bool verify_callback_called = false;
  11456. bool ip_matched_via_cn = true;
  11457. SSLClient cli(HOST, PORT);
  11458. cli.enable_server_certificate_verification(true);
  11459. cli.set_ca_cert_path(CA_CERT_FILE);
  11460. cli.set_connection_timeout(5);
  11461. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11462. verify_callback_called = true;
  11463. if (!ctx.cert) return false;
  11464. // The IP appears only in the CN, so it must NOT be accepted.
  11465. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  11466. return true; // Accept for the purpose of this test
  11467. });
  11468. cli.Get("/test");
  11469. ASSERT_TRUE(verify_callback_called)
  11470. << "Verify callback should have been called";
  11471. EXPECT_FALSE(ip_matched_via_cn)
  11472. << "An IP host must not be authenticated via the certificate CN";
  11473. }
  11474. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  11475. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  11476. using namespace httplib::tls;
  11477. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  11478. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  11479. ASSERT_TRUE(svr.is_valid());
  11480. svr.Get("/test", [](const Request &, Response &res) {
  11481. res.set_content("ok", "text/plain");
  11482. });
  11483. thread t([&]() { svr.listen(HOST, PORT); });
  11484. auto se = detail::scope_exit([&] {
  11485. svr.stop();
  11486. t.join();
  11487. });
  11488. svr.wait_until_ready();
  11489. bool verify_callback_called = false;
  11490. bool san_matched = false;
  11491. bool wrong_ipv6_matched = true;
  11492. bool cn_ipv6_matched = true;
  11493. SSLClient cli(HOST, PORT);
  11494. cli.enable_server_certificate_verification(true);
  11495. cli.set_ca_cert_path(CA_CERT_FILE);
  11496. cli.set_connection_timeout(5);
  11497. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11498. verify_callback_called = true;
  11499. if (!ctx.cert) return false;
  11500. // Matches the IPv6 iPAddress SAN.
  11501. san_matched = ctx.check_hostname("2001:db8::1");
  11502. // A different IPv6 address must not match.
  11503. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  11504. // "::1" lives only in the CN, so it must not be accepted.
  11505. cn_ipv6_matched = ctx.check_hostname("::1");
  11506. return true; // Accept for the purpose of this test
  11507. });
  11508. cli.Get("/test");
  11509. ASSERT_TRUE(verify_callback_called)
  11510. << "Verify callback should have been called";
  11511. EXPECT_TRUE(san_matched)
  11512. << "verify_hostname should match an IPv6 iPAddress SAN";
  11513. EXPECT_FALSE(wrong_ipv6_matched)
  11514. << "verify_hostname should not match a non-matching IPv6 address";
  11515. EXPECT_FALSE(cn_ipv6_matched)
  11516. << "An IPv6 host must not be authenticated via the certificate CN";
  11517. }
  11518. #endif
  11519. // mbedTLS-specific callback constructor test
  11520. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  11521. #ifdef CPPHTTPLIB_SSL_ENABLED
  11522. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  11523. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11524. ASSERT_TRUE(svr.is_valid());
  11525. // Set up a handler to verify client certificate is present
  11526. bool client_cert_verified = false;
  11527. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11528. // Verify that client certificate was provided
  11529. client_cert_verified = true;
  11530. res.set_content("success", "text/plain");
  11531. });
  11532. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11533. auto se = detail::scope_exit([&] {
  11534. svr.stop();
  11535. t.join();
  11536. ASSERT_FALSE(svr.is_running());
  11537. });
  11538. svr.wait_until_ready();
  11539. // Client with certificate
  11540. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11541. cli.enable_server_certificate_verification(false);
  11542. cli.set_connection_timeout(30);
  11543. auto res = cli.Get("/test");
  11544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11545. ASSERT_EQ(StatusCode::OK_200, res->status);
  11546. ASSERT_TRUE(client_cert_verified);
  11547. EXPECT_EQ("success", res->body);
  11548. }
  11549. #endif
  11550. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  11551. // backends
  11552. #ifdef CPPHTTPLIB_SSL_ENABLED
  11553. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  11554. using namespace httplib::tls;
  11555. // Test that when client CA cert file is provided,
  11556. // the server properly requests and validates client certificates
  11557. // Create a server with client authentication
  11558. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11559. ASSERT_TRUE(svr.is_valid());
  11560. bool handler_called = false;
  11561. svr.Get("/test", [&](const Request &req, Response &res) {
  11562. handler_called = true;
  11563. // Verify that a client certificate was provided
  11564. auto cert = req.peer_cert();
  11565. ASSERT_TRUE(static_cast<bool>(cert));
  11566. // Get the issuer name
  11567. std::string issuer_str = cert.issuer_name();
  11568. ASSERT_FALSE(issuer_str.empty());
  11569. // The client certificate should be issued by our test CA
  11570. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  11571. res.set_content("authenticated", "text/plain");
  11572. });
  11573. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11574. auto se = detail::scope_exit([&] {
  11575. svr.stop();
  11576. t.join();
  11577. ASSERT_FALSE(svr.is_running());
  11578. });
  11579. svr.wait_until_ready();
  11580. // Connect with a client certificate issued by the CA
  11581. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11582. cli.enable_server_certificate_verification(false);
  11583. cli.set_connection_timeout(30);
  11584. auto res = cli.Get("/test");
  11585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11586. ASSERT_EQ(StatusCode::OK_200, res->status);
  11587. ASSERT_TRUE(handler_called);
  11588. EXPECT_EQ("authenticated", res->body);
  11589. }
  11590. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  11591. using namespace httplib::tls;
  11592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11593. ASSERT_TRUE(svr.is_valid());
  11594. svr.Get("/test", [](const Request &, Response &res) {
  11595. res.set_content("ok", "text/plain");
  11596. });
  11597. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11598. auto se = detail::scope_exit([&] {
  11599. svr.stop();
  11600. t.join();
  11601. });
  11602. svr.wait_until_ready();
  11603. SSLClient cli(HOST, PORT);
  11604. cli.enable_server_certificate_verification(false);
  11605. cli.set_connection_timeout(30);
  11606. bool cert_checked = false;
  11607. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11608. if (ctx.cert) {
  11609. auto sans = ctx.sans();
  11610. // Test certificate may or may not have SANs - just verify the API
  11611. // works If SANs exist, verify the types are valid
  11612. for (const auto &san : sans) {
  11613. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  11614. san.type == SanType::EMAIL || san.type == SanType::URI ||
  11615. san.type == SanType::OTHER);
  11616. EXPECT_FALSE(san.value.empty());
  11617. }
  11618. cert_checked = true;
  11619. }
  11620. return true;
  11621. });
  11622. auto res = cli.Get("/test");
  11623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11624. EXPECT_TRUE(cert_checked);
  11625. }
  11626. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  11627. using namespace httplib::tls;
  11628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11629. ASSERT_TRUE(svr.is_valid());
  11630. svr.Get("/test", [](const Request &, Response &res) {
  11631. res.set_content("ok", "text/plain");
  11632. });
  11633. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11634. auto se = detail::scope_exit([&] {
  11635. svr.stop();
  11636. t.join();
  11637. });
  11638. svr.wait_until_ready();
  11639. SSLClient cli(HOST, PORT);
  11640. cli.enable_server_certificate_verification(false);
  11641. cli.set_connection_timeout(30);
  11642. bool validity_checked = false;
  11643. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11644. if (ctx.cert) {
  11645. time_t not_before = 0, not_after = 0;
  11646. bool result = ctx.validity(not_before, not_after);
  11647. EXPECT_TRUE(result);
  11648. // Verify that not_before < now < not_after for a valid cert
  11649. time_t now = time(nullptr);
  11650. EXPECT_LT(not_before, now);
  11651. EXPECT_GT(not_after, now);
  11652. validity_checked = true;
  11653. }
  11654. return true;
  11655. });
  11656. auto res = cli.Get("/test");
  11657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11658. EXPECT_TRUE(validity_checked);
  11659. }
  11660. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  11661. using namespace httplib::tls;
  11662. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11663. ASSERT_TRUE(svr.is_valid());
  11664. svr.Get("/test", [](const Request &, Response &res) {
  11665. res.set_content("ok", "text/plain");
  11666. });
  11667. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11668. auto se = detail::scope_exit([&] {
  11669. svr.stop();
  11670. t.join();
  11671. });
  11672. svr.wait_until_ready();
  11673. SSLClient cli(HOST, PORT);
  11674. cli.enable_server_certificate_verification(false);
  11675. cli.set_connection_timeout(30);
  11676. bool serial_checked = false;
  11677. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11678. if (ctx.cert) {
  11679. std::string serial = ctx.serial();
  11680. EXPECT_FALSE(serial.empty());
  11681. // Serial should be a hex string
  11682. for (char c : serial) {
  11683. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  11684. (c >= 'a' && c <= 'f'));
  11685. }
  11686. serial_checked = true;
  11687. }
  11688. return true;
  11689. });
  11690. auto res = cli.Get("/test");
  11691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11692. EXPECT_TRUE(serial_checked);
  11693. }
  11694. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  11695. // Test 1: Valid CA file - no error should be recorded
  11696. {
  11697. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11698. CLIENT_CA_CERT_FILE);
  11699. ASSERT_TRUE(svr.is_valid());
  11700. // With valid setup, last_ssl_error should be 0
  11701. EXPECT_EQ(0, svr.ssl_last_error());
  11702. }
  11703. // Test 2: Invalid CA file content
  11704. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  11705. {
  11706. // Create a temporary file with completely invalid content
  11707. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  11708. {
  11709. std::ofstream ofs(temp_invalid_ca);
  11710. ofs << "This is not a certificate file at all\n";
  11711. ofs << "Just plain text content\n";
  11712. }
  11713. // Create server with invalid CA file
  11714. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  11715. // Clean up temporary file
  11716. std::remove(temp_invalid_ca);
  11717. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  11718. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  11719. // Note: SSL_CTX_load_verify_locations typically fails first,
  11720. // but our error handling code path is still exercised
  11721. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  11722. }
  11723. }
  11724. TEST(VerifyCallbackTest, VerifyContextFields) {
  11725. using namespace httplib::tls;
  11726. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11727. ASSERT_TRUE(svr.is_valid());
  11728. svr.Get("/test", [](const Request &, Response &res) {
  11729. res.set_content("ok", "text/plain");
  11730. });
  11731. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11732. auto se = detail::scope_exit([&] {
  11733. svr.stop();
  11734. t.join();
  11735. });
  11736. svr.wait_until_ready();
  11737. SSLClient cli(HOST, PORT);
  11738. cli.enable_server_certificate_verification(false);
  11739. cli.set_connection_timeout(30);
  11740. int callback_count = 0;
  11741. bool saw_leaf_cert = false;
  11742. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11743. if (ctx.cert) {
  11744. callback_count++;
  11745. // We should see at least one certificate (the leaf)
  11746. std::string cn = ctx.subject_cn();
  11747. if (!cn.empty()) { saw_leaf_cert = true; }
  11748. // Verify context fields are populated
  11749. EXPECT_NE(ctx.session, nullptr);
  11750. EXPECT_GE(ctx.depth, 0);
  11751. }
  11752. return true;
  11753. });
  11754. auto res = cli.Get("/test");
  11755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11756. EXPECT_GT(callback_count, 0);
  11757. EXPECT_TRUE(saw_leaf_cert);
  11758. }
  11759. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  11760. using httplib::tls::TlsError;
  11761. // Test that verify_error_to_string returns empty for success
  11762. std::string success_str = TlsError::verify_error_to_string(0);
  11763. EXPECT_TRUE(success_str.empty());
  11764. // Test that verify_error_to_string returns non-empty for error codes
  11765. // Using a common error code (certificate expired)
  11766. std::string error_str =
  11767. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  11768. EXPECT_FALSE(error_str.empty());
  11769. }
  11770. TEST(SessionVerifierTest, CertificateAccepted) {
  11771. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11772. ASSERT_TRUE(svr.is_valid());
  11773. svr.Get("/test", [](const Request &, Response &res) {
  11774. res.set_content("ok", "text/plain");
  11775. });
  11776. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11777. auto se = detail::scope_exit([&] {
  11778. svr.stop();
  11779. t.join();
  11780. });
  11781. svr.wait_until_ready();
  11782. SSLClient cli(HOST, PORT);
  11783. cli.enable_server_certificate_verification(false);
  11784. cli.set_connection_timeout(30);
  11785. bool callback_called = false;
  11786. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11787. EXPECT_NE(session, nullptr);
  11788. callback_called = true;
  11789. return SSLVerifierResponse::CertificateAccepted;
  11790. });
  11791. auto res = cli.Get("/test");
  11792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11793. EXPECT_EQ(200, res->status);
  11794. EXPECT_TRUE(callback_called);
  11795. }
  11796. TEST(SessionVerifierTest, CertificateRejected) {
  11797. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11798. ASSERT_TRUE(svr.is_valid());
  11799. svr.Get("/test", [](const Request &, Response &res) {
  11800. res.set_content("ok", "text/plain");
  11801. });
  11802. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11803. auto se = detail::scope_exit([&] {
  11804. svr.stop();
  11805. t.join();
  11806. });
  11807. svr.wait_until_ready();
  11808. SSLClient cli(HOST, PORT);
  11809. cli.enable_server_certificate_verification(false);
  11810. cli.set_connection_timeout(30);
  11811. bool callback_called = false;
  11812. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11813. EXPECT_NE(session, nullptr);
  11814. callback_called = true;
  11815. return SSLVerifierResponse::CertificateRejected;
  11816. });
  11817. auto res = cli.Get("/test");
  11818. EXPECT_FALSE(res);
  11819. EXPECT_TRUE(callback_called);
  11820. }
  11821. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11822. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11823. ASSERT_TRUE(svr.is_valid());
  11824. svr.Get("/test", [](const Request &, Response &res) {
  11825. res.set_content("ok", "text/plain");
  11826. });
  11827. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11828. auto se = detail::scope_exit([&] {
  11829. svr.stop();
  11830. t.join();
  11831. });
  11832. svr.wait_until_ready();
  11833. // NoDecisionMade with verification disabled should succeed (no default check)
  11834. SSLClient cli(HOST, PORT);
  11835. cli.enable_server_certificate_verification(false);
  11836. cli.set_connection_timeout(30);
  11837. bool callback_called = false;
  11838. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11839. EXPECT_NE(session, nullptr);
  11840. callback_called = true;
  11841. return SSLVerifierResponse::NoDecisionMade;
  11842. });
  11843. auto res = cli.Get("/test");
  11844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11845. EXPECT_EQ(200, res->status);
  11846. EXPECT_TRUE(callback_called);
  11847. }
  11848. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11849. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11850. ASSERT_TRUE(svr.is_valid());
  11851. svr.Get("/test", [](const Request &, Response &res) {
  11852. res.set_content("ok", "text/plain");
  11853. });
  11854. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11855. auto se = detail::scope_exit([&] {
  11856. svr.stop();
  11857. t.join();
  11858. });
  11859. svr.wait_until_ready();
  11860. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11861. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11862. // so we only check that the request fails, not whether the callback was
  11863. // called.
  11864. SSLClient cli(HOST, PORT);
  11865. cli.enable_server_certificate_verification(true);
  11866. cli.set_connection_timeout(30);
  11867. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11868. EXPECT_NE(session, nullptr);
  11869. return SSLVerifierResponse::NoDecisionMade;
  11870. });
  11871. auto res = cli.Get("/test");
  11872. EXPECT_FALSE(res);
  11873. }
  11874. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11875. // Test SSL server using PemMemory constructor with client CA certificates
  11876. // Read PEM files
  11877. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11878. read_file(SERVER_CERT_FILE, server_cert_pem);
  11879. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11880. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11881. // Create SSLServer with PemMemory constructor including client CA
  11882. SSLServer::PemMemory server_pem = {
  11883. server_cert_pem.c_str(),
  11884. server_cert_pem.size(),
  11885. server_key_pem.c_str(),
  11886. server_key_pem.size(),
  11887. client_ca_pem.c_str(),
  11888. client_ca_pem.size(),
  11889. nullptr // no password for server key
  11890. };
  11891. SSLServer svr(server_pem);
  11892. ASSERT_TRUE(svr.is_valid());
  11893. // No SSL error should be recorded for valid setup
  11894. EXPECT_EQ(0, svr.ssl_last_error());
  11895. // Set up server endpoints
  11896. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11897. res.set_content("ok", "text/plain");
  11898. });
  11899. // Start server in a thread
  11900. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11901. svr.wait_until_ready();
  11902. // Connect with client certificate (using constructor with paths)
  11903. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11904. cli.enable_server_certificate_verification(false);
  11905. auto res = cli.Get("/test-pem-ca");
  11906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11907. EXPECT_EQ(200, res->status);
  11908. EXPECT_EQ("ok", res->body);
  11909. svr.stop();
  11910. server_thread.join();
  11911. }
  11912. #endif
  11913. #ifdef _WIN32
  11914. TEST(CleanupTest, WSACleanup) {
  11915. int ret = WSACleanup();
  11916. ASSERT_EQ(0, ret);
  11917. }
  11918. #endif
  11919. #ifndef CPPHTTPLIB_SSL_ENABLED
  11920. TEST(NoSSLSupport, SimpleInterface) {
  11921. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11922. }
  11923. #endif
  11924. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11925. TEST(InvalidScheme, SimpleInterface) {
  11926. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11927. }
  11928. #endif
  11929. TEST(NoScheme, SimpleInterface) {
  11930. Client cli("yahoo.com:80");
  11931. ASSERT_TRUE(cli.is_valid());
  11932. }
  11933. TEST(SendAPI, SimpleInterface_Online) {
  11934. Client cli("http://yahoo.com");
  11935. Request req;
  11936. req.method = "GET";
  11937. req.path = "/";
  11938. auto res = cli.send(req);
  11939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11940. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11941. }
  11942. TEST(SendAPI, WithParamsInRequest) {
  11943. Server svr;
  11944. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11945. EXPECT_TRUE(req.has_param("test"));
  11946. EXPECT_EQ("test_value", req.get_param_value("test"));
  11947. });
  11948. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11949. auto se = detail::scope_exit([&] {
  11950. svr.stop();
  11951. t.join();
  11952. ASSERT_FALSE(svr.is_running());
  11953. });
  11954. svr.wait_until_ready();
  11955. Client cli(HOST, PORT);
  11956. {
  11957. Request req;
  11958. req.method = "GET";
  11959. req.path = "/";
  11960. req.params.emplace("test", "test_value");
  11961. auto res = cli.send(req);
  11962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11963. }
  11964. {
  11965. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11967. }
  11968. }
  11969. TEST(ClientImplMethods, GetSocketTest) {
  11970. httplib::Server svr;
  11971. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11972. res.status = StatusCode::OK_200;
  11973. });
  11974. auto port = svr.bind_to_any_port("127.0.0.1");
  11975. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11976. auto se = detail::scope_exit([&] {
  11977. svr.stop();
  11978. thread.join();
  11979. ASSERT_FALSE(svr.is_running());
  11980. });
  11981. svr.wait_until_ready();
  11982. {
  11983. httplib::Client cli("127.0.0.1", port);
  11984. cli.set_keep_alive(true);
  11985. // Use the behavior of cpp-httplib of opening the connection
  11986. // only when the first request happens. If that changes,
  11987. // this test would be obsolete.
  11988. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11989. // This also implicitly tests the server. But other tests would fail much
  11990. // earlier than this one to be considered.
  11991. auto res = cli.Get("/");
  11992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11993. EXPECT_EQ(StatusCode::OK_200, res->status);
  11994. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11995. }
  11996. }
  11997. #ifdef CPPHTTPLIB_SSL_ENABLED
  11998. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11999. Client cli("http://yahoo.com");
  12000. auto res = cli.Get("/");
  12001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12002. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12003. cli.set_follow_location(true);
  12004. res = cli.Get("/");
  12005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12006. EXPECT_EQ(StatusCode::OK_200, res->status);
  12007. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12008. }
  12009. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12010. Client cli("https://yahoo.com");
  12011. auto res = cli.Get("/");
  12012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12013. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12014. cli.set_follow_location(true);
  12015. res = cli.Get("/");
  12016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12017. EXPECT_EQ(StatusCode::OK_200, res->status);
  12018. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12019. }
  12020. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12021. Client cli("https://yahoo.com");
  12022. auto res = cli.Get("/");
  12023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12024. ASSERT_FALSE(!res);
  12025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12026. ASSERT_FALSE(res == nullptr);
  12027. ASSERT_TRUE(res != nullptr);
  12028. EXPECT_EQ(Error::Success, res.error());
  12029. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12030. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12031. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12032. cli.set_follow_location(true);
  12033. res = cli.Get("/");
  12034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12035. EXPECT_EQ(Error::Success, res.error());
  12036. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12037. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12038. EXPECT_EQ(StatusCode::OK_200, res->status);
  12039. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12040. }
  12041. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12042. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12043. Client cli("https://cdnjs.cloudflare.com");
  12044. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12045. Headers{{"Accept-Encoding", "br"}});
  12046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12047. EXPECT_EQ(StatusCode::OK_200, res->status);
  12048. EXPECT_EQ(287630U, res->body.size());
  12049. EXPECT_EQ("application/javascript; charset=utf-8",
  12050. res->get_header_value("Content-Type"));
  12051. }
  12052. #endif
  12053. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12054. #undef REDIR_HOST // Silence compiler warning
  12055. #define REDIR_HOST "https://httpbingo.org"
  12056. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12057. Client cli(REDIR_HOST);
  12058. cli.set_follow_location(true);
  12059. auto res =
  12060. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12062. EXPECT_EQ(StatusCode::OK_200, res->status);
  12063. }
  12064. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12065. Client cli(REDIR_HOST);
  12066. cli.set_follow_location(true);
  12067. Params params;
  12068. params.emplace("url", "http://example.com");
  12069. params.emplace("status_code", "302");
  12070. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12072. EXPECT_EQ(StatusCode::OK_200, res->status);
  12073. }
  12074. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12075. Client cli(REDIR_HOST);
  12076. cli.set_follow_location(true);
  12077. Params params;
  12078. params.emplace("url", "http://example.com");
  12079. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12081. EXPECT_EQ(StatusCode::OK_200, res->status);
  12082. }
  12083. TEST(HttpToHttpsRedirectTest, CertFile) {
  12084. auto ssl_port = PORT + 1;
  12085. Server svr;
  12086. ASSERT_TRUE(svr.is_valid());
  12087. svr.Get("/index", [&](const Request &, Response &res) {
  12088. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12089. "/index");
  12090. svr.stop();
  12091. });
  12092. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12093. ASSERT_TRUE(ssl_svr.is_valid());
  12094. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12095. res.set_content("test", "text/plain");
  12096. ssl_svr.stop();
  12097. });
  12098. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12099. thread t2 =
  12100. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12101. auto se = detail::scope_exit([&] {
  12102. t2.join();
  12103. t.join();
  12104. ASSERT_FALSE(svr.is_running());
  12105. });
  12106. svr.wait_until_ready();
  12107. ssl_svr.wait_until_ready();
  12108. Client cli("127.0.0.1", PORT);
  12109. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12110. cli.enable_server_certificate_verification(true);
  12111. cli.set_follow_location(true);
  12112. cli.set_connection_timeout(30);
  12113. auto res = cli.Get("/index");
  12114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12115. ASSERT_EQ(StatusCode::OK_200, res->status);
  12116. }
  12117. TEST(SSLClientRedirectTest, CertFile) {
  12118. auto ssl_port = PORT + 1;
  12119. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12120. ASSERT_TRUE(ssl_svr1.is_valid());
  12121. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12122. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12123. "/index");
  12124. ssl_svr1.stop();
  12125. });
  12126. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12127. ASSERT_TRUE(ssl_svr2.is_valid());
  12128. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12129. res.set_content("test", "text/plain");
  12130. ssl_svr2.stop();
  12131. });
  12132. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12133. thread t2 =
  12134. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12135. auto se = detail::scope_exit([&] {
  12136. t2.join();
  12137. t.join();
  12138. ASSERT_FALSE(ssl_svr1.is_running());
  12139. });
  12140. ssl_svr1.wait_until_ready();
  12141. ssl_svr2.wait_until_ready();
  12142. SSLClient cli("127.0.0.1", PORT);
  12143. std::string cert;
  12144. read_file(SERVER_CERT2_FILE, cert);
  12145. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12146. cli.enable_server_certificate_verification(true);
  12147. cli.set_follow_location(true);
  12148. cli.set_connection_timeout(30);
  12149. auto res = cli.Get("/index");
  12150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12151. ASSERT_EQ(StatusCode::OK_200, res->status);
  12152. }
  12153. #endif
  12154. #ifdef CPPHTTPLIB_SSL_ENABLED
  12155. // Test that set_ca_cert_store() skips system certs (consistent with
  12156. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12157. // should be trusted - system certs should NOT be loaded.
  12158. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12159. // Load a specific cert that is NOT a system CA cert
  12160. std::string cert;
  12161. read_file(SERVER_CERT2_FILE, cert);
  12162. SSLClient cli("google.com");
  12163. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12164. cli.enable_server_certificate_verification(true);
  12165. // This should FAIL because:
  12166. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12167. // 2. System certs should NOT be loaded when custom store is set
  12168. // If system certs WERE loaded, this would succeed
  12169. auto res = cli.Get("/");
  12170. ASSERT_FALSE(res);
  12171. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12172. }
  12173. // Same as above, but through the native store handle path. Regression test:
  12174. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12175. // merged system certs into the user-provided store.
  12176. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12177. std::string cert;
  12178. read_file(SERVER_CERT2_FILE, cert);
  12179. SSLClient cli("google.com");
  12180. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12181. cli.enable_server_certificate_verification(true);
  12182. auto res = cli.Get("/");
  12183. ASSERT_FALSE(res);
  12184. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12185. }
  12186. // A custom store set via the native handle must still verify a server whose
  12187. // cert it does contain.
  12188. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12189. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12190. ASSERT_TRUE(svr.is_valid());
  12191. svr.Get("/test", [&](const Request &, Response &res) {
  12192. res.set_content("test", "text/plain");
  12193. });
  12194. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12195. auto se = detail::scope_exit([&] {
  12196. svr.stop();
  12197. t.join();
  12198. ASSERT_FALSE(svr.is_running());
  12199. });
  12200. svr.wait_until_ready();
  12201. SSLClient cli("127.0.0.1", PORT);
  12202. std::string cert;
  12203. read_file(SERVER_CERT2_FILE, cert);
  12204. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12205. cli.enable_server_certificate_verification(true);
  12206. cli.set_connection_timeout(30);
  12207. auto res = cli.Get("/test");
  12208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12209. ASSERT_EQ(StatusCode::OK_200, res->status);
  12210. }
  12211. // CA certs loaded through the universal Client must be transferred to the
  12212. // client created internally for following an HTTPS redirect. Regression test:
  12213. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12214. // the CA data for redirect transfer.
  12215. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12216. auto ssl_port = PORT + 1;
  12217. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12218. ASSERT_TRUE(ssl_svr1.is_valid());
  12219. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12220. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12221. "/index");
  12222. });
  12223. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12224. ASSERT_TRUE(ssl_svr2.is_valid());
  12225. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12226. res.set_content("test", "text/plain");
  12227. });
  12228. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12229. thread t2 =
  12230. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12231. auto se = detail::scope_exit([&] {
  12232. ssl_svr2.stop();
  12233. ssl_svr1.stop();
  12234. t2.join();
  12235. t.join();
  12236. ASSERT_FALSE(ssl_svr1.is_running());
  12237. });
  12238. ssl_svr1.wait_until_ready();
  12239. ssl_svr2.wait_until_ready();
  12240. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12241. std::string cert;
  12242. read_file(SERVER_CERT2_FILE, cert);
  12243. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12244. cli.enable_server_certificate_verification(true);
  12245. cli.set_follow_location(true);
  12246. cli.set_connection_timeout(30);
  12247. auto res = cli.Get("/index");
  12248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12249. ASSERT_EQ(StatusCode::OK_200, res->status);
  12250. }
  12251. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  12252. // so a host signed by a system CA verifies even though a custom CA is set
  12253. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  12254. std::string cert;
  12255. read_file(SERVER_CERT2_FILE, cert);
  12256. SSLClient cli("google.com");
  12257. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12258. cli.enable_system_ca(true);
  12259. cli.enable_server_certificate_verification(true);
  12260. auto res = cli.Get("/");
  12261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12262. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12263. }
  12264. // The custom CA remains effective when combined with the system CA
  12265. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  12266. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12267. ASSERT_TRUE(svr.is_valid());
  12268. svr.Get("/test", [&](const Request &, Response &res) {
  12269. res.set_content("test", "text/plain");
  12270. });
  12271. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12272. auto se = detail::scope_exit([&] {
  12273. svr.stop();
  12274. t.join();
  12275. ASSERT_FALSE(svr.is_running());
  12276. });
  12277. svr.wait_until_ready();
  12278. SSLClient cli("127.0.0.1", PORT);
  12279. std::string cert;
  12280. read_file(SERVER_CERT2_FILE, cert);
  12281. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12282. cli.enable_system_ca(true);
  12283. cli.enable_server_certificate_verification(true);
  12284. cli.set_connection_timeout(30);
  12285. auto res = cli.Get("/test");
  12286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12287. ASSERT_EQ(StatusCode::OK_200, res->status);
  12288. }
  12289. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  12290. // skip chain verification entirely (only the certificate identity was
  12291. // checked), so a server presenting an untrusted certificate with a matching
  12292. // IP SAN was accepted. The chain must be validated for IP hosts too.
  12293. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  12294. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12295. ASSERT_TRUE(svr.is_valid());
  12296. svr.Get("/test", [&](const Request &, Response &res) {
  12297. res.set_content("test", "text/plain");
  12298. });
  12299. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12300. auto se = detail::scope_exit([&] {
  12301. svr.stop();
  12302. t.join();
  12303. ASSERT_FALSE(svr.is_running());
  12304. });
  12305. svr.wait_until_ready();
  12306. SSLClient cli("127.0.0.1", PORT);
  12307. std::string cert;
  12308. // A trusted CA that did not sign the server certificate. The server cert
  12309. // (cert2) carries the matching IP SAN, so only chain validation can reject
  12310. // this connection.
  12311. read_file(CLIENT_CA_CERT_FILE, cert);
  12312. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12313. cli.enable_server_certificate_verification(true);
  12314. cli.set_connection_timeout(30);
  12315. auto res = cli.Get("/test");
  12316. ASSERT_FALSE(res);
  12317. }
  12318. // enable_system_ca(false) prevents system CA loading entirely
  12319. TEST(SSLClientTest, DisableSystemCa_Online) {
  12320. SSLClient cli("google.com");
  12321. cli.enable_system_ca(false);
  12322. cli.enable_server_certificate_verification(true);
  12323. auto res = cli.Get("/");
  12324. ASSERT_FALSE(res);
  12325. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  12326. // itself when the CA chain is empty
  12327. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12328. res.error() == Error::SSLConnection);
  12329. }
  12330. // The universal Client forwards enable_system_ca()
  12331. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  12332. std::string cert;
  12333. read_file(SERVER_CERT2_FILE, cert);
  12334. Client cli("https://google.com");
  12335. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12336. cli.enable_system_ca(true);
  12337. cli.enable_server_certificate_verification(true);
  12338. auto res = cli.Get("/");
  12339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12340. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12341. }
  12342. // The system CA policy must carry over to the client created internally for
  12343. // following a cross-host HTTPS redirect
  12344. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  12345. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12346. ASSERT_TRUE(svr.is_valid());
  12347. svr.Get("/index", [&](const Request &, Response &res) {
  12348. res.set_redirect("https://www.google.com/");
  12349. });
  12350. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12351. auto se = detail::scope_exit([&] {
  12352. svr.stop();
  12353. t.join();
  12354. ASSERT_FALSE(svr.is_running());
  12355. });
  12356. svr.wait_until_ready();
  12357. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12358. std::string cert;
  12359. read_file(SERVER_CERT2_FILE, cert);
  12360. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12361. cli.enable_system_ca(true);
  12362. cli.enable_server_certificate_verification(true);
  12363. cli.set_follow_location(true);
  12364. cli.set_connection_timeout(30);
  12365. // Receiving any response proves the redirect client completed the TLS
  12366. // handshake with a system-CA-signed host
  12367. auto res = cli.Get("/index");
  12368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12369. }
  12370. TEST(MultipartFormDataTest, LargeData) {
  12371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12372. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  12373. const ContentReader &content_reader) {
  12374. if (req.is_multipart_form_data()) {
  12375. std::vector<FormData> items;
  12376. content_reader(
  12377. [&](const FormData &file) {
  12378. items.push_back(file);
  12379. return true;
  12380. },
  12381. [&](const char *data, size_t data_length) {
  12382. items.back().content.append(data, data_length);
  12383. return true;
  12384. });
  12385. EXPECT_TRUE(std::string(items[0].name) == "document");
  12386. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12387. EXPECT_TRUE(items[0].filename == "2MB_data");
  12388. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12389. EXPECT_TRUE(items[1].name == "hello");
  12390. EXPECT_TRUE(items[1].content == "world");
  12391. EXPECT_TRUE(items[1].filename == "");
  12392. EXPECT_TRUE(items[1].content_type == "");
  12393. } else {
  12394. std::string body;
  12395. content_reader([&](const char *data, size_t data_length) {
  12396. body.append(data, data_length);
  12397. return true;
  12398. });
  12399. }
  12400. });
  12401. auto port = svr.bind_to_any_port(HOST);
  12402. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12403. auto se = detail::scope_exit([&] {
  12404. svr.stop();
  12405. t.join();
  12406. ASSERT_FALSE(svr.is_running());
  12407. });
  12408. svr.wait_until_ready();
  12409. {
  12410. std::string data(1024 * 1024 * 2, '.');
  12411. std::stringstream buffer;
  12412. buffer << data;
  12413. SSLClient cli(HOST, port);
  12414. cli.enable_server_certificate_verification(false);
  12415. UploadFormDataItems items{
  12416. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12417. {"hello", "world", "", ""},
  12418. };
  12419. auto res = cli.Post("/post", items);
  12420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12421. ASSERT_EQ(StatusCode::OK_200, res->status);
  12422. }
  12423. }
  12424. TEST(MultipartFormDataTest, DataProviderItems) {
  12425. std::random_device seed_gen;
  12426. std::mt19937 random(seed_gen());
  12427. std::string rand1;
  12428. rand1.resize(1000);
  12429. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  12430. std::string rand2;
  12431. rand2.resize(3000);
  12432. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  12433. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12434. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  12435. const ContentReader &content_reader) {
  12436. ASSERT_FALSE(req.is_multipart_form_data());
  12437. std::string body;
  12438. content_reader([&](const char *data, size_t data_length) {
  12439. body.append(data, data_length);
  12440. return true;
  12441. });
  12442. EXPECT_EQ(body, "");
  12443. });
  12444. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  12445. const ContentReader &content_reader) {
  12446. ASSERT_TRUE(req.is_multipart_form_data());
  12447. std::vector<FormData> items;
  12448. content_reader(
  12449. [&](const FormData &file) {
  12450. items.push_back(file);
  12451. return true;
  12452. },
  12453. [&](const char *data, size_t data_length) {
  12454. items.back().content.append(data, data_length);
  12455. return true;
  12456. });
  12457. ASSERT_TRUE(items.size() == 2);
  12458. EXPECT_EQ(std::string(items[0].name), "name1");
  12459. EXPECT_EQ(items[0].content, "Testing123");
  12460. EXPECT_EQ(items[0].filename, "filename1");
  12461. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12462. EXPECT_EQ(items[1].name, "name2");
  12463. EXPECT_EQ(items[1].content, "Testing456");
  12464. EXPECT_EQ(items[1].filename, "");
  12465. EXPECT_EQ(items[1].content_type, "");
  12466. });
  12467. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  12468. const ContentReader &content_reader) {
  12469. ASSERT_TRUE(req.is_multipart_form_data());
  12470. std::vector<FormData> items;
  12471. content_reader(
  12472. [&](const FormData &file) {
  12473. items.push_back(file);
  12474. return true;
  12475. },
  12476. [&](const char *data, size_t data_length) {
  12477. items.back().content.append(data, data_length);
  12478. return true;
  12479. });
  12480. ASSERT_TRUE(items.size() == 2);
  12481. EXPECT_EQ(items[0].name, "name3");
  12482. EXPECT_EQ(items[0].content, rand1);
  12483. EXPECT_EQ(items[0].filename, "filename3");
  12484. EXPECT_EQ(items[0].content_type, "");
  12485. EXPECT_EQ(items[1].name, "name4");
  12486. EXPECT_EQ(items[1].content, rand2);
  12487. EXPECT_EQ(items[1].filename, "filename4");
  12488. EXPECT_EQ(items[1].content_type, "");
  12489. });
  12490. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  12491. const ContentReader &content_reader) {
  12492. ASSERT_TRUE(req.is_multipart_form_data());
  12493. std::vector<FormData> items;
  12494. content_reader(
  12495. [&](const FormData &file) {
  12496. items.push_back(file);
  12497. return true;
  12498. },
  12499. [&](const char *data, size_t data_length) {
  12500. items.back().content.append(data, data_length);
  12501. return true;
  12502. });
  12503. ASSERT_TRUE(items.size() == 4);
  12504. EXPECT_EQ(std::string(items[0].name), "name1");
  12505. EXPECT_EQ(items[0].content, "Testing123");
  12506. EXPECT_EQ(items[0].filename, "filename1");
  12507. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  12508. EXPECT_EQ(items[1].name, "name2");
  12509. EXPECT_EQ(items[1].content, "Testing456");
  12510. EXPECT_EQ(items[1].filename, "");
  12511. EXPECT_EQ(items[1].content_type, "");
  12512. EXPECT_EQ(items[2].name, "name3");
  12513. EXPECT_EQ(items[2].content, rand1);
  12514. EXPECT_EQ(items[2].filename, "filename3");
  12515. EXPECT_EQ(items[2].content_type, "");
  12516. EXPECT_EQ(items[3].name, "name4");
  12517. EXPECT_EQ(items[3].content, rand2);
  12518. EXPECT_EQ(items[3].filename, "filename4");
  12519. EXPECT_EQ(items[3].content_type, "");
  12520. });
  12521. auto port = svr.bind_to_any_port("localhost");
  12522. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12523. auto se = detail::scope_exit([&] {
  12524. svr.stop();
  12525. t.join();
  12526. ASSERT_FALSE(svr.is_running());
  12527. });
  12528. svr.wait_until_ready();
  12529. {
  12530. SSLClient cli("localhost", port);
  12531. cli.enable_server_certificate_verification(false);
  12532. UploadFormDataItems items{
  12533. {"name1", "Testing123", "filename1", "application/octet-stream"},
  12534. {"name2", "Testing456", "", ""}, // not a file
  12535. };
  12536. {
  12537. auto res = cli.Post("/post-none", {}, {}, {});
  12538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12539. ASSERT_EQ(StatusCode::OK_200, res->status);
  12540. }
  12541. FormDataProviderItems providers;
  12542. {
  12543. auto res =
  12544. cli.Post("/post-items", {}, items, providers); // empty providers
  12545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12546. ASSERT_EQ(StatusCode::OK_200, res->status);
  12547. }
  12548. providers.push_back({"name3",
  12549. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12550. // test the offset is given correctly at each step
  12551. if (!offset)
  12552. sink.os.write(rand1.data(), 30);
  12553. else if (offset == 30)
  12554. sink.os.write(rand1.data() + 30, 300);
  12555. else if (offset == 330)
  12556. sink.os.write(rand1.data() + 330, 670);
  12557. else if (offset == rand1.size())
  12558. sink.done();
  12559. return true;
  12560. },
  12561. "filename3",
  12562. {}});
  12563. providers.push_back({"name4",
  12564. [&](size_t offset, httplib::DataSink &sink) -> bool {
  12565. // test the offset is given correctly at each step
  12566. if (!offset)
  12567. sink.os.write(rand2.data(), 2000);
  12568. else if (offset == 2000)
  12569. sink.os.write(rand2.data() + 2000, 1);
  12570. else if (offset == 2001)
  12571. sink.os.write(rand2.data() + 2001, 999);
  12572. else if (offset == rand2.size())
  12573. sink.done();
  12574. return true;
  12575. },
  12576. "filename4",
  12577. {}});
  12578. {
  12579. auto res = cli.Post("/post-providers", {}, {}, providers);
  12580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12581. ASSERT_EQ(StatusCode::OK_200, res->status);
  12582. }
  12583. {
  12584. auto res = cli.Post("/post-both", {}, items, providers);
  12585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12586. ASSERT_EQ(StatusCode::OK_200, res->status);
  12587. }
  12588. }
  12589. }
  12590. TEST(MultipartFormDataTest, BadHeader) {
  12591. Server svr;
  12592. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12593. res.set_content("ok", "text/plain");
  12594. });
  12595. thread t = thread([&] { svr.listen(HOST, PORT); });
  12596. auto se = detail::scope_exit([&] {
  12597. svr.stop();
  12598. t.join();
  12599. ASSERT_FALSE(svr.is_running());
  12600. });
  12601. svr.wait_until_ready();
  12602. const std::string body =
  12603. "This is the preamble. It is to be ignored, though it\r\n"
  12604. "is a handy place for composition agents to include an\r\n"
  12605. "explanatory note to non-MIME conformant readers.\r\n"
  12606. "\r\n"
  12607. "\r\n"
  12608. "--simple boundary\r\n"
  12609. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12610. ": BAD...\r\n"
  12611. "\r\n"
  12612. "value1\r\n"
  12613. "--simple boundary\r\n"
  12614. "Content-Disposition: form-data; name=\"field2\"; "
  12615. "filename=\"example.txt\"\r\n"
  12616. "\r\n"
  12617. "value2\r\n"
  12618. "--simple boundary--\r\n"
  12619. "This is the epilogue. It is also to be ignored.\r\n";
  12620. std::string content_type =
  12621. R"(multipart/form-data; boundary="simple boundary")";
  12622. Client cli(HOST, PORT);
  12623. auto res = cli.Post("/post", body, content_type.c_str());
  12624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12625. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12626. }
  12627. TEST(MultipartFormDataTest, WithPreamble) {
  12628. Server svr;
  12629. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12630. res.set_content("ok", "text/plain");
  12631. });
  12632. thread t = thread([&] { svr.listen(HOST, PORT); });
  12633. auto se = detail::scope_exit([&] {
  12634. svr.stop();
  12635. t.join();
  12636. ASSERT_FALSE(svr.is_running());
  12637. });
  12638. svr.wait_until_ready();
  12639. const std::string body =
  12640. "This is the preamble. It is to be ignored, though it\r\n"
  12641. "is a handy place for composition agents to include an\r\n"
  12642. "explanatory note to non-MIME conformant readers.\r\n"
  12643. "\r\n"
  12644. "\r\n"
  12645. "--simple boundary\r\n"
  12646. "Content-Disposition: form-data; name=\"field1\"\r\n"
  12647. "\r\n"
  12648. "value1\r\n"
  12649. "--simple boundary\r\n"
  12650. "Content-Disposition: form-data; name=\"field2\"; "
  12651. "filename=\"example.txt\"\r\n"
  12652. "\r\n"
  12653. "value2\r\n"
  12654. "--simple boundary--\r\n"
  12655. "This is the epilogue. It is also to be ignored.\r\n";
  12656. std::string content_type =
  12657. R"(multipart/form-data; boundary="simple boundary")";
  12658. Client cli(HOST, PORT);
  12659. auto res = cli.Post("/post", body, content_type.c_str());
  12660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12661. EXPECT_EQ(StatusCode::OK_200, res->status);
  12662. }
  12663. TEST(MultipartFormDataTest, PostCustomBoundary) {
  12664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12665. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  12666. const ContentReader &content_reader) {
  12667. if (req.is_multipart_form_data()) {
  12668. std::vector<FormData> items;
  12669. content_reader(
  12670. [&](const FormData &file) {
  12671. items.push_back(file);
  12672. return true;
  12673. },
  12674. [&](const char *data, size_t data_length) {
  12675. items.back().content.append(data, data_length);
  12676. return true;
  12677. });
  12678. EXPECT_TRUE(std::string(items[0].name) == "document");
  12679. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12680. EXPECT_TRUE(items[0].filename == "2MB_data");
  12681. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12682. EXPECT_TRUE(items[1].name == "hello");
  12683. EXPECT_TRUE(items[1].content == "world");
  12684. EXPECT_TRUE(items[1].filename == "");
  12685. EXPECT_TRUE(items[1].content_type == "");
  12686. } else {
  12687. std::string body;
  12688. content_reader([&](const char *data, size_t data_length) {
  12689. body.append(data, data_length);
  12690. return true;
  12691. });
  12692. }
  12693. });
  12694. auto port = svr.bind_to_any_port("localhost");
  12695. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12696. auto se = detail::scope_exit([&] {
  12697. svr.stop();
  12698. t.join();
  12699. ASSERT_FALSE(svr.is_running());
  12700. });
  12701. svr.wait_until_ready();
  12702. {
  12703. std::string data(1024 * 1024 * 2, '.');
  12704. std::stringstream buffer;
  12705. buffer << data;
  12706. SSLClient cli("localhost", port);
  12707. cli.enable_server_certificate_verification(false);
  12708. UploadFormDataItems items{
  12709. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12710. {"hello", "world", "", ""},
  12711. };
  12712. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  12713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12714. ASSERT_EQ(StatusCode::OK_200, res->status);
  12715. }
  12716. }
  12717. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  12718. std::string data(1024 * 1024 * 2, '&');
  12719. std::stringstream buffer;
  12720. buffer << data;
  12721. Client cli("https://localhost:8080");
  12722. UploadFormDataItems items{
  12723. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12724. {"hello", "world", "", ""},
  12725. };
  12726. for (const char &c : " \t\r\n") {
  12727. auto res =
  12728. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  12729. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12730. ASSERT_FALSE(res);
  12731. }
  12732. }
  12733. TEST(MultipartFormDataTest, PutFormData) {
  12734. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12735. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  12736. const ContentReader &content_reader) {
  12737. if (req.is_multipart_form_data()) {
  12738. std::vector<FormData> items;
  12739. content_reader(
  12740. [&](const FormData &file) {
  12741. items.push_back(file);
  12742. return true;
  12743. },
  12744. [&](const char *data, size_t data_length) {
  12745. items.back().content.append(data, data_length);
  12746. return true;
  12747. });
  12748. EXPECT_TRUE(std::string(items[0].name) == "document");
  12749. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12750. EXPECT_TRUE(items[0].filename == "2MB_data");
  12751. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12752. EXPECT_TRUE(items[1].name == "hello");
  12753. EXPECT_TRUE(items[1].content == "world");
  12754. EXPECT_TRUE(items[1].filename == "");
  12755. EXPECT_TRUE(items[1].content_type == "");
  12756. } else {
  12757. std::string body;
  12758. content_reader([&](const char *data, size_t data_length) {
  12759. body.append(data, data_length);
  12760. return true;
  12761. });
  12762. }
  12763. });
  12764. auto port = svr.bind_to_any_port("localhost");
  12765. auto t = std::thread([&]() { svr.listen_after_bind(); });
  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. {
  12773. std::string data(1024 * 1024 * 2, '&');
  12774. std::stringstream buffer;
  12775. buffer << data;
  12776. SSLClient cli("localhost", port);
  12777. cli.enable_server_certificate_verification(false);
  12778. UploadFormDataItems items{
  12779. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12780. {"hello", "world", "", ""},
  12781. };
  12782. auto res = cli.Put("/put", items);
  12783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12784. ASSERT_EQ(StatusCode::OK_200, res->status);
  12785. }
  12786. }
  12787. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  12788. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12789. svr.Put("/put_customboundary",
  12790. [&](const Request &req, const Response & /*res*/,
  12791. const ContentReader &content_reader) {
  12792. if (req.is_multipart_form_data()) {
  12793. std::vector<FormData> items;
  12794. content_reader(
  12795. [&](const FormData &file) {
  12796. items.push_back(file);
  12797. return true;
  12798. },
  12799. [&](const char *data, size_t data_length) {
  12800. items.back().content.append(data, data_length);
  12801. return true;
  12802. });
  12803. EXPECT_TRUE(std::string(items[0].name) == "document");
  12804. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12805. EXPECT_TRUE(items[0].filename == "2MB_data");
  12806. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12807. EXPECT_TRUE(items[1].name == "hello");
  12808. EXPECT_TRUE(items[1].content == "world");
  12809. EXPECT_TRUE(items[1].filename == "");
  12810. EXPECT_TRUE(items[1].content_type == "");
  12811. } else {
  12812. std::string body;
  12813. content_reader([&](const char *data, size_t data_length) {
  12814. body.append(data, data_length);
  12815. return true;
  12816. });
  12817. }
  12818. });
  12819. auto port = svr.bind_to_any_port("localhost");
  12820. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12821. auto se = detail::scope_exit([&] {
  12822. svr.stop();
  12823. t.join();
  12824. ASSERT_FALSE(svr.is_running());
  12825. });
  12826. svr.wait_until_ready();
  12827. {
  12828. std::string data(1024 * 1024 * 2, '&');
  12829. std::stringstream buffer;
  12830. buffer << data;
  12831. SSLClient cli("localhost", port);
  12832. cli.enable_server_certificate_verification(false);
  12833. UploadFormDataItems items{
  12834. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12835. {"hello", "world", "", ""},
  12836. };
  12837. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12839. ASSERT_EQ(StatusCode::OK_200, res->status);
  12840. }
  12841. }
  12842. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12843. std::string data(1024 * 1024 * 2, '&');
  12844. std::stringstream buffer;
  12845. buffer << data;
  12846. Client cli("https://localhost:8080");
  12847. cli.enable_server_certificate_verification(false);
  12848. UploadFormDataItems items{
  12849. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12850. {"hello", "world", "", ""},
  12851. };
  12852. for (const char &c : " \t\r\n") {
  12853. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12854. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12855. ASSERT_FALSE(res);
  12856. }
  12857. }
  12858. TEST(MultipartFormDataTest, AlternateFilename) {
  12859. auto handled = false;
  12860. Server svr;
  12861. svr.Post("/test", [&](const Request &req, Response &res) {
  12862. ASSERT_EQ(2u, req.form.files.size());
  12863. ASSERT_EQ(1u, req.form.fields.size());
  12864. // Test files
  12865. const auto &file1 = req.form.get_file("file1");
  12866. ASSERT_EQ("file1", file1.name);
  12867. ASSERT_EQ("A.txt", file1.filename);
  12868. ASSERT_EQ("text/plain", file1.content_type);
  12869. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12870. const auto &file2 = req.form.get_file("file2");
  12871. ASSERT_EQ("file2", file2.name);
  12872. ASSERT_EQ("a.html", file2.filename);
  12873. ASSERT_EQ("text/html", file2.content_type);
  12874. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12875. file2.content);
  12876. // Test text field
  12877. const auto &text = req.form.get_field("text");
  12878. ASSERT_EQ("text default", text);
  12879. res.set_content("ok", "text/plain");
  12880. handled = true;
  12881. });
  12882. thread t = thread([&] { svr.listen(HOST, PORT); });
  12883. auto se = detail::scope_exit([&] {
  12884. svr.stop();
  12885. t.join();
  12886. ASSERT_FALSE(svr.is_running());
  12887. ASSERT_TRUE(handled);
  12888. });
  12889. svr.wait_until_ready();
  12890. auto req = "POST /test HTTP/1.1\r\n"
  12891. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12892. "Content-Length: 399\r\n"
  12893. "\r\n"
  12894. "----------\r\n"
  12895. "Content-Disposition: form-data; name=\"text\"\r\n"
  12896. "\r\n"
  12897. "text default\r\n"
  12898. "----------\r\n"
  12899. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12900. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12901. "Content-Type: text/plain\r\n"
  12902. "\r\n"
  12903. "Content of a.txt.\r\n"
  12904. "\r\n"
  12905. "----------\r\n"
  12906. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12907. "\"a.html\"\r\n"
  12908. "Content-Type: text/html\r\n"
  12909. "\r\n"
  12910. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12911. "\r\n"
  12912. "------------\r\n";
  12913. ASSERT_TRUE(send_request(1, req));
  12914. }
  12915. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12916. auto handled = false;
  12917. Server svr;
  12918. svr.Post("/test", [&](const Request &req, Response &res) {
  12919. // Case-insensitive "utf-8''" prefix with a long value
  12920. const auto &file = req.form.get_file("file1");
  12921. ASSERT_EQ("file1", file.name);
  12922. // 8000 chars exercises both the Content-Disposition parser and the
  12923. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12924. // Prior to the fix, std::regex_match on this header would cause O(N)
  12925. // stack recursion in libstdc++, leading to SIGSEGV.
  12926. std::string expected_filename(8000, 'A');
  12927. ASSERT_EQ(expected_filename, file.filename);
  12928. res.set_content("ok", "text/plain");
  12929. handled = true;
  12930. });
  12931. thread t = thread([&] { svr.listen(HOST, PORT); });
  12932. auto se = detail::scope_exit([&] {
  12933. svr.stop();
  12934. t.join();
  12935. ASSERT_FALSE(svr.is_running());
  12936. ASSERT_TRUE(handled);
  12937. });
  12938. svr.wait_until_ready();
  12939. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12940. // Regression test for GHSA-qq6v-r583-3h69
  12941. std::string long_filename(8000, 'A');
  12942. std::string body = "----------\r\n"
  12943. "Content-Disposition: form-data; name=\"file1\"; "
  12944. "filename*=\"Utf-8''" +
  12945. long_filename +
  12946. "\"\r\n"
  12947. "\r\n"
  12948. "hello\r\n"
  12949. "------------\r\n";
  12950. auto req = "POST /test HTTP/1.1\r\n"
  12951. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12952. "Content-Length: " +
  12953. std::to_string(body.size()) + "\r\n\r\n" + body;
  12954. ASSERT_TRUE(send_request(1, req));
  12955. }
  12956. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12957. auto handled = false;
  12958. Server svr;
  12959. svr.Post("/test", [&](const Request &req, Response &) {
  12960. ASSERT_EQ(2u, req.form.fields.size());
  12961. const auto &text1 = req.form.get_field("text1");
  12962. ASSERT_EQ("text1", text1);
  12963. const auto &text2 = req.form.get_field("text2");
  12964. ASSERT_EQ("text2", text2);
  12965. handled = true;
  12966. });
  12967. thread t = thread([&] { svr.listen(HOST, PORT); });
  12968. auto se = detail::scope_exit([&] {
  12969. svr.stop();
  12970. t.join();
  12971. ASSERT_FALSE(svr.is_running());
  12972. ASSERT_TRUE(handled);
  12973. });
  12974. svr.wait_until_ready();
  12975. auto req = "POST /test HTTP/1.1\r\n"
  12976. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12977. "Content-Length: 146\r\n"
  12978. "\r\n----------\r\n"
  12979. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12980. "\r\n"
  12981. "text1"
  12982. "\r\n----------\r\n"
  12983. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12984. "\r\n"
  12985. "text2"
  12986. "\r\n------------";
  12987. std::string response;
  12988. ASSERT_TRUE(send_request(1, req, &response));
  12989. ASSERT_EQ("200", response.substr(9, 3));
  12990. }
  12991. TEST(MultipartFormDataTest, ContentLength) {
  12992. auto handled = false;
  12993. Server svr;
  12994. svr.Post("/test", [&](const Request &req, Response &) {
  12995. ASSERT_EQ(2u, req.form.fields.size());
  12996. const auto &text1 = req.form.get_field("text1");
  12997. ASSERT_EQ("text1", text1);
  12998. const auto &text2 = req.form.get_field("text2");
  12999. ASSERT_EQ("text2", text2);
  13000. handled = true;
  13001. });
  13002. thread t = thread([&] { svr.listen(HOST, PORT); });
  13003. auto se = detail::scope_exit([&] {
  13004. svr.stop();
  13005. t.join();
  13006. ASSERT_FALSE(svr.is_running());
  13007. ASSERT_TRUE(handled);
  13008. });
  13009. svr.wait_until_ready();
  13010. auto req = "POST /test HTTP/1.1\r\n"
  13011. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13012. "Content-Length: 167\r\n"
  13013. "\r\n----------\r\n"
  13014. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13015. "Content-Length: 5\r\n"
  13016. "\r\n"
  13017. "text1"
  13018. "\r\n----------\r\n"
  13019. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13020. "\r\n"
  13021. "text2"
  13022. "\r\n------------\r\n";
  13023. std::string response;
  13024. ASSERT_TRUE(send_request(1, req, &response));
  13025. ASSERT_EQ("200", response.substr(9, 3));
  13026. }
  13027. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13028. auto handled = false;
  13029. Server svr;
  13030. svr.Post("/test", [&](const Request &req, Response &) {
  13031. ASSERT_EQ(2u, req.form.fields.size());
  13032. const auto &text1 = req.form.get_field("text1");
  13033. ASSERT_EQ("text1", text1);
  13034. // TODO: Add header access for text fields if needed
  13035. const auto &text2 = req.form.get_field("text2");
  13036. ASSERT_EQ("text2", text2);
  13037. // TODO: Header access for text fields needs to be implemented
  13038. // auto &headers = it->second.headers;
  13039. // ASSERT_EQ(3U, headers.size());
  13040. // auto custom_header = headers.find("x-whatever");
  13041. // ASSERT_TRUE(custom_header != headers.end());
  13042. // ASSERT_NE("customvalue", custom_header->second);
  13043. // ASSERT_EQ("CustomValue", custom_header->second);
  13044. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13045. handled = true;
  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. ASSERT_TRUE(handled);
  13053. });
  13054. svr.wait_until_ready();
  13055. auto req = "POST /test HTTP/1.1\r\n"
  13056. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13057. "Content-Length: 232\r\n"
  13058. "\r\n----------\r\n"
  13059. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13060. "Content-Length: 5\r\n"
  13061. "X-Test: 1\r\n"
  13062. "\r\n"
  13063. "text1"
  13064. "\r\n----------\r\n"
  13065. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13066. "Content-Type: text/plain\r\n"
  13067. "X-Whatever: CustomValue\r\n"
  13068. "\r\n"
  13069. "text2"
  13070. "\r\n------------\r\n"
  13071. "That should be disregarded. Not even read";
  13072. std::string response;
  13073. ASSERT_TRUE(send_request(1, req, &response));
  13074. ASSERT_EQ("200", response.substr(9, 3));
  13075. }
  13076. TEST(MultipartFormDataTest, LargeHeader) {
  13077. auto handled = false;
  13078. Server svr;
  13079. svr.Post("/test", [&](const Request &req, Response &) {
  13080. ASSERT_EQ(1u, req.form.fields.size());
  13081. const auto &text = req.form.get_field("name1");
  13082. ASSERT_EQ("text1", text);
  13083. handled = true;
  13084. });
  13085. thread t = thread([&] { svr.listen(HOST, PORT); });
  13086. auto se = detail::scope_exit([&] {
  13087. svr.stop();
  13088. t.join();
  13089. ASSERT_FALSE(svr.is_running());
  13090. ASSERT_TRUE(handled);
  13091. });
  13092. svr.wait_until_ready();
  13093. auto boundary = std::string("cpp-httplib-multipart-data");
  13094. std::string content = "--" + boundary +
  13095. "\r\n"
  13096. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13097. "\r\n"
  13098. "text1\r\n"
  13099. "--" +
  13100. boundary + "--\r\n";
  13101. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13102. "Content-Type: multipart/form-data;boundary=" +
  13103. boundary +
  13104. "\r\n"
  13105. "Content-Length: " +
  13106. std::to_string(content.size()) +
  13107. "\r\n"
  13108. "Dummy-Header: ";
  13109. std::string header_suffix = "\r\n"
  13110. "\r\n";
  13111. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13112. size_t header_dummy_size =
  13113. read_buff_size -
  13114. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13115. auto header_dummy = std::string(header_dummy_size, '@');
  13116. auto req = header_prefix + header_dummy + header_suffix + content;
  13117. std::string response;
  13118. ASSERT_TRUE(send_request(1, req, &response));
  13119. ASSERT_EQ("200", response.substr(9, 3));
  13120. }
  13121. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13122. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13123. // (not chunked Transfer-Encoding) after the streaming refactor.
  13124. auto handled = false;
  13125. Server svr;
  13126. svr.Post("/upload", [&](const Request &req, Response &res) {
  13127. auto cl_it = req.headers.find("Content-Length");
  13128. EXPECT_TRUE(cl_it != req.headers.end());
  13129. auto te_it = req.headers.find("Transfer-Encoding");
  13130. EXPECT_TRUE(te_it == req.headers.end());
  13131. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13132. res.set_content("ok", "text/plain");
  13133. handled = true;
  13134. });
  13135. auto port = svr.bind_to_any_port(HOST);
  13136. auto t = thread([&] { svr.listen_after_bind(); });
  13137. auto se = detail::scope_exit([&] {
  13138. svr.stop();
  13139. t.join();
  13140. ASSERT_FALSE(svr.is_running());
  13141. ASSERT_TRUE(handled);
  13142. });
  13143. svr.wait_until_ready();
  13144. UploadFormDataItems items = {
  13145. {"field1", "hello", "", "text/plain"},
  13146. {"file1", "world", "test.txt", "application/octet-stream"},
  13147. };
  13148. Client cli(HOST, port);
  13149. auto res = cli.Post("/upload", {}, items);
  13150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13151. EXPECT_EQ(StatusCode::OK_200, res->status);
  13152. }
  13153. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13154. // Verify that make_multipart_content_provider coalesces many small segments
  13155. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13156. constexpr size_t kItemCount = 1000;
  13157. UploadFormDataItems items;
  13158. items.reserve(kItemCount);
  13159. for (size_t i = 0; i < kItemCount; i++) {
  13160. items.push_back(
  13161. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13162. }
  13163. const std::string boundary = "----test-boundary";
  13164. auto content_length = detail::get_multipart_content_length(items, boundary);
  13165. auto provider = detail::make_multipart_content_provider(items, boundary);
  13166. // Drive the provider the same way write_content_with_progress does
  13167. size_t write_count = 0;
  13168. size_t total_bytes = 0;
  13169. DataSink sink;
  13170. size_t offset = 0;
  13171. sink.write = [&](const char *d, size_t l) -> bool {
  13172. (void)d;
  13173. write_count++;
  13174. total_bytes += l;
  13175. offset += l;
  13176. return true;
  13177. };
  13178. sink.is_writable = []() -> bool { return true; };
  13179. while (offset < content_length) {
  13180. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13181. }
  13182. EXPECT_EQ(content_length, total_bytes);
  13183. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13184. // With buffering into 64KB blocks, write_count should be much smaller.
  13185. auto segment_count = 3 * kItemCount + 1;
  13186. EXPECT_LT(write_count, segment_count / 10);
  13187. }
  13188. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13189. // Integration test: send many UploadFormDataItems and verify the server
  13190. // receives all of them correctly (#2410).
  13191. constexpr size_t kItemCount = 500;
  13192. auto handled = false;
  13193. Server svr;
  13194. svr.Post("/upload", [&](const Request &req, Response &res) {
  13195. EXPECT_EQ(kItemCount, req.form.fields.size());
  13196. for (size_t i = 0; i < kItemCount; i++) {
  13197. auto key = "field" + std::to_string(i);
  13198. auto val = "value" + std::to_string(i);
  13199. auto it = req.form.fields.find(key);
  13200. if (it != req.form.fields.end()) {
  13201. EXPECT_EQ(val, it->second.content);
  13202. } else {
  13203. ADD_FAILURE() << "Missing field: " << key;
  13204. }
  13205. }
  13206. res.set_content("ok", "text/plain");
  13207. handled = true;
  13208. });
  13209. auto port = svr.bind_to_any_port(HOST);
  13210. auto t = thread([&] { svr.listen_after_bind(); });
  13211. auto se = detail::scope_exit([&] {
  13212. svr.stop();
  13213. t.join();
  13214. ASSERT_FALSE(svr.is_running());
  13215. ASSERT_TRUE(handled);
  13216. });
  13217. svr.wait_until_ready();
  13218. UploadFormDataItems items;
  13219. items.reserve(kItemCount);
  13220. for (size_t i = 0; i < kItemCount; i++) {
  13221. items.push_back(
  13222. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13223. }
  13224. Client cli(HOST, port);
  13225. auto res = cli.Post("/upload", items);
  13226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13227. EXPECT_EQ(StatusCode::OK_200, res->status);
  13228. }
  13229. TEST(MultipartFormDataTest, MakeFileProvider) {
  13230. // Verify make_file_provider sends a file's contents correctly.
  13231. const std::string file_content(4096, 'Z');
  13232. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13233. {
  13234. std::ofstream ofs(tmp_path, std::ios::binary);
  13235. ofs.write(file_content.data(),
  13236. static_cast<std::streamsize>(file_content.size()));
  13237. }
  13238. auto handled = false;
  13239. Server svr;
  13240. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13241. const ContentReader &content_reader) {
  13242. ASSERT_TRUE(req.is_multipart_form_data());
  13243. std::vector<FormData> items;
  13244. content_reader(
  13245. [&](const FormData &file) {
  13246. items.push_back(file);
  13247. return true;
  13248. },
  13249. [&](const char *data, size_t data_length) {
  13250. items.back().content.append(data, data_length);
  13251. return true;
  13252. });
  13253. ASSERT_EQ(1u, items.size());
  13254. EXPECT_EQ("myfile", items[0].name);
  13255. EXPECT_EQ("data.bin", items[0].filename);
  13256. EXPECT_EQ("application/octet-stream", items[0].content_type);
  13257. EXPECT_EQ(file_content, items[0].content);
  13258. handled = true;
  13259. });
  13260. auto port = svr.bind_to_any_port(HOST);
  13261. auto t = thread([&] { svr.listen_after_bind(); });
  13262. auto se = detail::scope_exit([&] {
  13263. svr.stop();
  13264. t.join();
  13265. ASSERT_FALSE(svr.is_running());
  13266. ASSERT_TRUE(handled);
  13267. std::remove(tmp_path.c_str());
  13268. });
  13269. svr.wait_until_ready();
  13270. FormDataProviderItems providers;
  13271. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  13272. "application/octet-stream"));
  13273. Client cli(HOST, port);
  13274. auto res = cli.Post("/upload", {}, {}, providers);
  13275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13276. EXPECT_EQ(StatusCode::OK_200, res->status);
  13277. }
  13278. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  13279. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  13280. // (100) headers is rejected with a 400 Bad Request response.
  13281. Server svr;
  13282. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13283. res.set_content("ok", "text/plain");
  13284. });
  13285. thread t = thread([&] { svr.listen(HOST, PORT); });
  13286. auto se = detail::scope_exit([&] {
  13287. svr.stop();
  13288. t.join();
  13289. ASSERT_FALSE(svr.is_running());
  13290. });
  13291. svr.wait_until_ready();
  13292. // Build a multipart part with 101 custom headers (exceeding
  13293. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  13294. std::stringstream body;
  13295. body << "--simpleboundary\r\n"
  13296. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  13297. for (int i = 0; i < 101; i++) {
  13298. body << "X-Custom-Header-" << i << ": value\r\n";
  13299. }
  13300. body << "\r\n"
  13301. << "value1\r\n"
  13302. << "--simpleboundary--\r\n";
  13303. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  13304. Client cli(HOST, PORT);
  13305. auto res = cli.Post("/post", body.str(), content_type.c_str());
  13306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13307. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13308. }
  13309. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  13310. // A body that never contains the declared boundary must not be accumulated
  13311. // while the parser waits for it. Buffering it would also make every read
  13312. // rescan everything seen so far, which is quadratic in the body size.
  13313. Server svr;
  13314. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13315. res.set_content("ok", "text/plain");
  13316. });
  13317. auto port = svr.bind_to_any_port(HOST);
  13318. thread t = thread([&] { svr.listen_after_bind(); });
  13319. auto se = detail::scope_exit([&] {
  13320. svr.stop();
  13321. t.join();
  13322. ASSERT_FALSE(svr.is_running());
  13323. });
  13324. svr.wait_until_ready();
  13325. Client cli(HOST, port);
  13326. cli.set_read_timeout(60, 0);
  13327. cli.set_write_timeout(60, 0);
  13328. // '-' is the worst case: it matches the first character of the boundary, so
  13329. // every position has to be checked against it.
  13330. auto post_dashes = [&](size_t size) {
  13331. const std::string body(size, '-');
  13332. auto start = std::chrono::steady_clock::now();
  13333. auto res =
  13334. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  13335. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  13336. std::chrono::steady_clock::now() - start)
  13337. .count();
  13338. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  13339. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  13340. return ms;
  13341. };
  13342. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  13343. // Windows.
  13344. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  13345. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  13346. // Comparing the two sizes rather than checking an absolute duration keeps
  13347. // this meaningful across build types and CI load, both of which move the
  13348. // absolute numbers by more than an order of magnitude. Four times the bytes
  13349. // costs about four times the time when parsing is linear, and about sixteen
  13350. // times when the body is buffered and rescanned.
  13351. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  13352. EXPECT_LT(ms_16mb, ms_4mb * 10)
  13353. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  13354. << "ms, which suggests the body is being buffered and rescanned";
  13355. }
  13356. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  13357. // A boundary can only be followed by CRLF or by "--", so anything else is
  13358. // malformed no matter what comes next. The parser must say so right away
  13359. // instead of buffering the rest of the declared body.
  13360. Server svr;
  13361. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13362. res.set_content("ok", "text/plain");
  13363. });
  13364. auto port = svr.bind_to_any_port(HOST);
  13365. thread t = thread([&] { svr.listen_after_bind(); });
  13366. auto se = detail::scope_exit([&] {
  13367. svr.stop();
  13368. t.join();
  13369. ASSERT_FALSE(svr.is_running());
  13370. });
  13371. svr.wait_until_ready();
  13372. // Announce a 1 MB body but send only the malformed prefix. A parser that
  13373. // buffers instead of failing would still be waiting for the remaining bytes.
  13374. const std::string body = "--zzzz\r\n"
  13375. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13376. "\r\n"
  13377. "text1"
  13378. "\r\n--zzzzXX";
  13379. const std::string req = "POST /post HTTP/1.1\r\n"
  13380. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13381. "Content-Length: 1048576\r\n"
  13382. "\r\n" +
  13383. body;
  13384. std::string response;
  13385. ASSERT_TRUE(send_request(3, req, &response, port));
  13386. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  13387. EXPECT_EQ("400", response.substr(9, 3));
  13388. }
  13389. // Posts a multipart body split into two writes, so that the server sees the
  13390. // split at whatever offset the caller chose, and expects the single "text1"
  13391. // field to come through.
  13392. static void expect_split_multipart_ok(const std::string &body1,
  13393. const std::string &body2) {
  13394. auto handled = false;
  13395. Server svr;
  13396. svr.Post("/post", [&](const Request &req, Response &) {
  13397. EXPECT_EQ(1u, req.form.fields.size());
  13398. EXPECT_EQ("text1", req.form.get_field("text1"));
  13399. handled = true;
  13400. });
  13401. auto port = svr.bind_to_any_port(HOST);
  13402. thread t = thread([&] { svr.listen_after_bind(); });
  13403. auto se = detail::scope_exit([&] {
  13404. svr.stop();
  13405. t.join();
  13406. ASSERT_FALSE(svr.is_running());
  13407. ASSERT_TRUE(handled);
  13408. });
  13409. svr.wait_until_ready();
  13410. // "Connection: close" makes the server close once it has answered, so the
  13411. // response drain ends immediately instead of idling until the read timeout.
  13412. const std::string head =
  13413. "POST /post HTTP/1.1\r\n"
  13414. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13415. "Connection: close\r\n"
  13416. "Content-Length: " +
  13417. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  13418. std::string response;
  13419. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  13420. ASSERT_GE(response.size(), 12u) << "no response";
  13421. EXPECT_EQ("200", response.substr(9, 3));
  13422. }
  13423. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  13424. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  13425. // ignored, including when it does not arrive in the same read as the
  13426. // close-delimiter itself.
  13427. expect_split_multipart_ok("--zzzz\r\n"
  13428. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13429. "\r\n"
  13430. "text1"
  13431. "\r\n--zzzz--",
  13432. "\r\nthis epilogue must be ignored\r\n");
  13433. }
  13434. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  13435. // The initial boundary may be preceded by a preamble of any length and may
  13436. // straddle a read boundary. Discarding data while waiting for it must not
  13437. // throw away a partial boundary sitting at the end of the buffer.
  13438. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  13439. "zz\r\n"
  13440. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13441. "\r\n"
  13442. "text1"
  13443. "\r\n--zzzz--\r\n");
  13444. }
  13445. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  13446. // The received boundary was only checked for being non-empty, so it could be
  13447. // as long as a header is allowed to be. The parser scans the body for
  13448. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  13449. // costs a nearly full comparison at nearly every position, making the
  13450. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  13451. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  13452. Server svr;
  13453. svr.Post("/post", [](const Request &req, Response &res) {
  13454. EXPECT_EQ(1u, req.form.fields.size());
  13455. EXPECT_EQ("text1", req.form.get_field("text1"));
  13456. res.set_content("ok", "text/plain");
  13457. });
  13458. auto port = svr.bind_to_any_port(HOST);
  13459. thread t = thread([&] { svr.listen_after_bind(); });
  13460. auto se = detail::scope_exit([&] {
  13461. svr.stop();
  13462. t.join();
  13463. ASSERT_FALSE(svr.is_running());
  13464. });
  13465. svr.wait_until_ready();
  13466. Client cli(HOST, port);
  13467. auto post_with_boundary_of_length = [&](size_t len) {
  13468. const std::string boundary(len, 'a');
  13469. const std::string body =
  13470. "--" + boundary +
  13471. "\r\n"
  13472. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13473. "\r\n"
  13474. "text1"
  13475. "\r\n--" +
  13476. boundary + "--\r\n";
  13477. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  13478. };
  13479. auto res = post_with_boundary_of_length(70);
  13480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13481. EXPECT_EQ(StatusCode::OK_200, res->status);
  13482. res = post_with_boundary_of_length(71);
  13483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13484. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13485. }
  13486. TEST(MakeFileBodyTest, Basic) {
  13487. const std::string file_content(4096, 'Z');
  13488. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  13489. {
  13490. std::ofstream ofs(tmp_path, std::ios::binary);
  13491. ofs.write(file_content.data(),
  13492. static_cast<std::streamsize>(file_content.size()));
  13493. }
  13494. auto handled = false;
  13495. Server svr;
  13496. svr.Post("/upload", [&](const Request &req, Response &res) {
  13497. EXPECT_EQ(file_content, req.body);
  13498. handled = true;
  13499. res.status = StatusCode::OK_200;
  13500. });
  13501. auto port = svr.bind_to_any_port(HOST);
  13502. auto t = thread([&] { svr.listen_after_bind(); });
  13503. auto se = detail::scope_exit([&] {
  13504. svr.stop();
  13505. t.join();
  13506. ASSERT_FALSE(svr.is_running());
  13507. ASSERT_TRUE(handled);
  13508. std::remove(tmp_path.c_str());
  13509. });
  13510. svr.wait_until_ready();
  13511. auto fb = make_file_body(tmp_path);
  13512. ASSERT_GT(fb.first, 0u);
  13513. Client cli(HOST, port);
  13514. auto res =
  13515. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  13516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13517. EXPECT_EQ(StatusCode::OK_200, res->status);
  13518. }
  13519. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  13520. static constexpr unsigned int number_of_tasks{1000000};
  13521. std::atomic_uint count{0};
  13522. std::unique_ptr<TaskQueue> task_queue{
  13523. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  13524. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13525. auto queued = task_queue->enqueue(
  13526. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  13527. EXPECT_TRUE(queued);
  13528. }
  13529. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13530. task_queue->shutdown();
  13531. #else
  13532. EXPECT_NO_THROW(task_queue->shutdown());
  13533. #endif
  13534. EXPECT_EQ(number_of_tasks, count.load());
  13535. }
  13536. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  13537. static constexpr unsigned int number_of_tasks{1000000};
  13538. static constexpr unsigned int qlimit{2};
  13539. unsigned int queued_count{0};
  13540. std::atomic_uint count{0};
  13541. std::unique_ptr<TaskQueue> task_queue{
  13542. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  13543. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  13544. if (task_queue->enqueue(
  13545. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  13546. queued_count++;
  13547. }
  13548. }
  13549. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13550. task_queue->shutdown();
  13551. #else
  13552. EXPECT_NO_THROW(task_queue->shutdown());
  13553. #endif
  13554. EXPECT_EQ(queued_count, count.load());
  13555. EXPECT_TRUE(queued_count <= number_of_tasks);
  13556. EXPECT_TRUE(queued_count >= qlimit);
  13557. }
  13558. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  13559. // Use a short idle timeout so a dynamic thread spawns, times out and
  13560. // exits during the test, and the pool keeps working afterwards.
  13561. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  13562. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  13563. /*idle_timeout_sec=*/1}};
  13564. std::atomic_uint count{0};
  13565. std::condition_variable cv;
  13566. std::mutex mtx;
  13567. bool release = false;
  13568. // Block the base thread so the second task spawns a dynamic thread.
  13569. EXPECT_TRUE(task_queue->enqueue([&] {
  13570. std::unique_lock<std::mutex> lock(mtx);
  13571. while (!release) {
  13572. cv.wait(lock);
  13573. }
  13574. count++;
  13575. }));
  13576. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13577. // Let the dynamic thread finish its task and exceed the idle timeout.
  13578. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  13579. {
  13580. std::unique_lock<std::mutex> lock(mtx);
  13581. release = true;
  13582. }
  13583. cv.notify_all();
  13584. // The pool must still accept and run tasks after the dynamic thread exited.
  13585. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  13586. task_queue->shutdown();
  13587. EXPECT_EQ(3u, count.load());
  13588. }
  13589. TEST(TaskQueueTest, MaxQueuedRequests) {
  13590. static constexpr unsigned int qlimit{3};
  13591. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  13592. std::condition_variable sem_cv;
  13593. std::mutex sem_mtx;
  13594. int credits = 0;
  13595. bool queued;
  13596. /* Fill up the queue with tasks that will block until we give them credits to
  13597. * complete. */
  13598. for (unsigned int n = 0; n <= qlimit;) {
  13599. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  13600. std::unique_lock<std::mutex> lock(sem_mtx);
  13601. while (credits <= 0) {
  13602. sem_cv.wait(lock);
  13603. }
  13604. /* Consume the credit and signal the test code if they are all gone. */
  13605. if (--credits == 0) { sem_cv.notify_one(); }
  13606. });
  13607. if (n < qlimit) {
  13608. /* The first qlimit enqueues must succeed. */
  13609. EXPECT_TRUE(queued);
  13610. } else {
  13611. /* The last one will succeed only when the worker thread
  13612. * starts and dequeues the first blocking task. Although
  13613. * not necessary for the correctness of this test, we sleep for
  13614. * a short while to avoid busy waiting. */
  13615. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13616. }
  13617. if (queued) { n++; }
  13618. }
  13619. /* Further enqueues must fail since the queue is full. */
  13620. for (auto i = 0; i < 4; i++) {
  13621. queued = task_queue->enqueue([] {});
  13622. EXPECT_FALSE(queued);
  13623. }
  13624. /* Give the credits to allow the previous tasks to complete. */
  13625. {
  13626. std::unique_lock<std::mutex> lock(sem_mtx);
  13627. credits += qlimit + 1;
  13628. }
  13629. sem_cv.notify_all();
  13630. /* Wait for all the credits to be consumed. */
  13631. {
  13632. std::unique_lock<std::mutex> lock(sem_mtx);
  13633. while (credits > 0) {
  13634. sem_cv.wait(lock);
  13635. }
  13636. }
  13637. /* Check that we are able again to enqueue at least qlimit tasks. */
  13638. for (unsigned int i = 0; i < qlimit; i++) {
  13639. queued = task_queue->enqueue([] {});
  13640. EXPECT_TRUE(queued);
  13641. }
  13642. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13643. task_queue->shutdown();
  13644. #else
  13645. EXPECT_NO_THROW(task_queue->shutdown());
  13646. #endif
  13647. }
  13648. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  13649. Server svr;
  13650. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13651. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  13652. });
  13653. svr.Get("/hello", [](const Request &req, Response &res) {
  13654. res.set_content(req.get_param_value("key"), "text/plain");
  13655. });
  13656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13657. auto se = detail::scope_exit([&] {
  13658. svr.stop();
  13659. thread.join();
  13660. ASSERT_FALSE(svr.is_running());
  13661. });
  13662. svr.wait_until_ready();
  13663. {
  13664. Client cli(HOST, PORT);
  13665. cli.set_follow_location(true);
  13666. auto res = cli.Get("/");
  13667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13668. EXPECT_EQ(StatusCode::OK_200, res->status);
  13669. EXPECT_EQ("val&key2=val2", res->body);
  13670. }
  13671. }
  13672. #endif
  13673. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  13674. Server svr;
  13675. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13676. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  13677. });
  13678. svr.Get("/hello", [](const Request &req, Response &res) {
  13679. res.set_content(req.get_param_value("key"), "text/plain");
  13680. });
  13681. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13682. auto se = detail::scope_exit([&] {
  13683. svr.stop();
  13684. thread.join();
  13685. ASSERT_FALSE(svr.is_running());
  13686. });
  13687. svr.wait_until_ready();
  13688. {
  13689. Client cli(HOST, PORT);
  13690. cli.set_follow_location(true);
  13691. auto res = cli.Get("/");
  13692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13693. EXPECT_EQ(StatusCode::OK_200, res->status);
  13694. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  13695. }
  13696. }
  13697. TEST(RedirectTest, RedirectWithPlusInPath) {
  13698. Server svr;
  13699. svr.Get("/", [](const Request & /*req*/, Response &res) {
  13700. res.set_redirect("/a+b");
  13701. });
  13702. // Route pattern uses regex; escape + as \\+
  13703. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  13704. res.set_content(req.path, "text/plain");
  13705. });
  13706. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13707. auto se = detail::scope_exit([&] {
  13708. svr.stop();
  13709. thread.join();
  13710. ASSERT_FALSE(svr.is_running());
  13711. });
  13712. svr.wait_until_ready();
  13713. {
  13714. Client cli(HOST, PORT);
  13715. cli.set_follow_location(true);
  13716. auto res = cli.Get("/");
  13717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13718. EXPECT_EQ(StatusCode::OK_200, res->status);
  13719. EXPECT_EQ("/a+b", res->body);
  13720. }
  13721. }
  13722. #ifdef CPPHTTPLIB_SSL_ENABLED
  13723. TEST(RedirectTest, Issue2185_Online) {
  13724. SSLClient client("github.com");
  13725. client.set_follow_location(true);
  13726. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  13727. "Coollab-Windows.zip");
  13728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13729. EXPECT_EQ(StatusCode::OK_200, res->status);
  13730. EXPECT_EQ(9920427U, res->body.size());
  13731. }
  13732. #endif
  13733. TEST(VulnerabilityTest, CRLFInjection) {
  13734. Server svr;
  13735. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  13736. res.set_content("Hello 1", "text/plain");
  13737. });
  13738. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  13739. res.set_content("Hello 2", "text/plain");
  13740. });
  13741. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  13742. res.set_content("Hello 3", "text/plain");
  13743. });
  13744. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  13745. res.set_content("Hello 4", "text/plain");
  13746. });
  13747. svr.set_logger([](const Request &req, const Response & /*res*/) {
  13748. for (const auto &x : req.headers) {
  13749. auto key = x.first;
  13750. EXPECT_STRNE("evil", key.c_str());
  13751. }
  13752. });
  13753. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13754. auto se = detail::scope_exit([&] {
  13755. svr.stop();
  13756. thread.join();
  13757. ASSERT_FALSE(svr.is_running());
  13758. });
  13759. svr.wait_until_ready();
  13760. {
  13761. Client cli(HOST, PORT);
  13762. cli.Post("/test1", "A=B",
  13763. "application/x-www-form-urlencoded\r\nevil: hello1");
  13764. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  13765. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  13766. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  13767. }
  13768. }
  13769. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  13770. auto server_thread = std::thread([] {
  13771. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13772. default_socket_options(srv);
  13773. sockaddr_in addr{};
  13774. addr.sin_family = AF_INET;
  13775. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  13776. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13777. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13778. ::listen(srv, 1);
  13779. sockaddr_in cli_addr{};
  13780. socklen_t cli_len = sizeof(cli_addr);
  13781. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13782. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  13783. std::string buf_all;
  13784. char buf[2048];
  13785. ssize_t n;
  13786. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  13787. buf_all.append(buf, static_cast<size_t>(n));
  13788. size_t pos;
  13789. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  13790. auto request_block = buf_all.substr(0, pos + 4); // include separator
  13791. auto e = request_block.find("\r\n");
  13792. if (e != std::string::npos) {
  13793. auto request_line = request_block.substr(0, e);
  13794. std::string msg =
  13795. "CRLF injection detected in request line: '" + request_line + "'";
  13796. EXPECT_FALSE(true) << msg;
  13797. }
  13798. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  13799. ::send(cli,
  13800. #ifdef _WIN32
  13801. static_cast<const char *>(resp.c_str()),
  13802. static_cast<int>(resp.size()),
  13803. #else
  13804. resp.c_str(), resp.size(),
  13805. #endif
  13806. 0);
  13807. buf_all.erase(0, pos + 4);
  13808. }
  13809. }
  13810. detail::close_socket(cli);
  13811. detail::close_socket(srv);
  13812. });
  13813. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13814. auto cli = Client("127.0.0.1", PORT + 1);
  13815. auto headers = Headers{
  13816. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  13817. {"Connection", "keep-alive"}};
  13818. auto res = cli.Get("/hi", headers);
  13819. EXPECT_FALSE(res);
  13820. EXPECT_EQ(Error::InvalidHeaders, res.error());
  13821. server_thread.join();
  13822. }
  13823. TEST(PathParamsTest, StaticMatch) {
  13824. const auto pattern = "/users/all";
  13825. detail::PathParamsMatcher matcher(pattern);
  13826. Request request;
  13827. request.path = "/users/all";
  13828. ASSERT_TRUE(matcher.match(request));
  13829. std::unordered_map<std::string, std::string> expected_params = {};
  13830. EXPECT_EQ(request.path_params, expected_params);
  13831. }
  13832. TEST(PathParamsTest, StaticMismatch) {
  13833. const auto pattern = "/users/all";
  13834. detail::PathParamsMatcher matcher(pattern);
  13835. Request request;
  13836. request.path = "/users/1";
  13837. ASSERT_FALSE(matcher.match(request));
  13838. }
  13839. TEST(PathParamsTest, SingleParamInTheMiddle) {
  13840. const auto pattern = "/users/:id/subscriptions";
  13841. detail::PathParamsMatcher matcher(pattern);
  13842. Request request;
  13843. request.path = "/users/42/subscriptions";
  13844. ASSERT_TRUE(matcher.match(request));
  13845. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13846. EXPECT_EQ(request.path_params, expected_params);
  13847. }
  13848. TEST(PathParamsTest, SingleParamInTheEnd) {
  13849. const auto pattern = "/users/:id";
  13850. detail::PathParamsMatcher matcher(pattern);
  13851. Request request;
  13852. request.path = "/users/24";
  13853. ASSERT_TRUE(matcher.match(request));
  13854. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  13855. EXPECT_EQ(request.path_params, expected_params);
  13856. }
  13857. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  13858. const auto pattern = "/users/:id/";
  13859. detail::PathParamsMatcher matcher(pattern);
  13860. Request request;
  13861. request.path = "/users/42/";
  13862. ASSERT_TRUE(matcher.match(request));
  13863. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  13864. EXPECT_EQ(request.path_params, expected_params);
  13865. }
  13866. TEST(PathParamsTest, EmptyParam) {
  13867. const auto pattern = "/users/:id/";
  13868. detail::PathParamsMatcher matcher(pattern);
  13869. Request request;
  13870. request.path = "/users//";
  13871. ASSERT_TRUE(matcher.match(request));
  13872. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  13873. EXPECT_EQ(request.path_params, expected_params);
  13874. }
  13875. TEST(PathParamsTest, FragmentMismatch) {
  13876. const auto pattern = "/users/:id/";
  13877. detail::PathParamsMatcher matcher(pattern);
  13878. Request request;
  13879. request.path = "/admins/24/";
  13880. ASSERT_FALSE(matcher.match(request));
  13881. }
  13882. TEST(PathParamsTest, ExtraFragments) {
  13883. const auto pattern = "/users/:id";
  13884. detail::PathParamsMatcher matcher(pattern);
  13885. Request request;
  13886. request.path = "/users/42/subscriptions";
  13887. ASSERT_FALSE(matcher.match(request));
  13888. }
  13889. TEST(PathParamsTest, MissingTrailingParam) {
  13890. const auto pattern = "/users/:id";
  13891. detail::PathParamsMatcher matcher(pattern);
  13892. Request request;
  13893. request.path = "/users";
  13894. ASSERT_FALSE(matcher.match(request));
  13895. }
  13896. TEST(PathParamsTest, MissingParamInTheMiddle) {
  13897. const auto pattern = "/users/:id/subscriptions";
  13898. detail::PathParamsMatcher matcher(pattern);
  13899. Request request;
  13900. request.path = "/users/subscriptions";
  13901. ASSERT_FALSE(matcher.match(request));
  13902. }
  13903. TEST(PathParamsTest, MultipleParams) {
  13904. const auto pattern = "/users/:userid/subscriptions/:subid";
  13905. detail::PathParamsMatcher matcher(pattern);
  13906. Request request;
  13907. request.path = "/users/42/subscriptions/2";
  13908. ASSERT_TRUE(matcher.match(request));
  13909. std::unordered_map<std::string, std::string> expected_params = {
  13910. {"userid", "42"}, {"subid", "2"}};
  13911. EXPECT_EQ(request.path_params, expected_params);
  13912. }
  13913. TEST(PathParamsTest, SequenceOfParams) {
  13914. const auto pattern = "/values/:x/:y/:z";
  13915. detail::PathParamsMatcher matcher(pattern);
  13916. Request request;
  13917. request.path = "/values/1/2/3";
  13918. ASSERT_TRUE(matcher.match(request));
  13919. std::unordered_map<std::string, std::string> expected_params = {
  13920. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  13921. EXPECT_EQ(request.path_params, expected_params);
  13922. }
  13923. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  13924. const auto pattern = "/prefix:suffix";
  13925. detail::PathParamsMatcher matcher(pattern);
  13926. Request request;
  13927. request.path = "/prefix:suffix";
  13928. ASSERT_TRUE(matcher.match(request));
  13929. const std::unordered_map<std::string, std::string> expected_params = {};
  13930. EXPECT_EQ(request.path_params, expected_params);
  13931. }
  13932. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  13933. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  13934. // calling thread's stack on a long enough path for a quantified pattern;
  13935. // RegexMatcher must refuse to run regex matching on paths beyond
  13936. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  13937. detail::RegexMatcher matcher("/files/(.*)");
  13938. Request within_limit;
  13939. within_limit.path = "/files/" + std::string(10, 'A');
  13940. EXPECT_TRUE(matcher.match(within_limit));
  13941. Request over_limit;
  13942. over_limit.path =
  13943. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  13944. EXPECT_FALSE(matcher.match(over_limit));
  13945. }
  13946. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  13947. Server svr;
  13948. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  13949. res.set_content("ok", "text/plain");
  13950. });
  13951. auto port = svr.bind_to_any_port(HOST);
  13952. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13953. auto se = detail::scope_exit([&] {
  13954. svr.stop();
  13955. thread.join();
  13956. ASSERT_FALSE(svr.is_running());
  13957. });
  13958. svr.wait_until_ready();
  13959. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  13960. // request URI limit; this used to be able to crash the process.
  13961. std::string path =
  13962. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  13963. std::string req = "GET " + path +
  13964. " HTTP/1.1\r\n"
  13965. "Host: " +
  13966. std::string(HOST) + ":" + std::to_string(port) +
  13967. "\r\n"
  13968. "Connection: close\r\n"
  13969. "\r\n";
  13970. std::string response;
  13971. ASSERT_TRUE(send_request(5, req, &response, port));
  13972. EXPECT_NE(std::string::npos, response.find("404"));
  13973. }
  13974. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  13975. Server svr;
  13976. auto handler = [](const Request & /*req*/, Response &res) {
  13977. res.set_content("hit", "text/plain");
  13978. };
  13979. // No regex metacharacter, so this one is compared literally
  13980. svr.Get("/literal/route", handler);
  13981. // '.' is a regex metacharacter, so this one must keep regex semantics
  13982. svr.Get("/a.c", handler);
  13983. auto port = svr.bind_to_any_port(HOST);
  13984. std::thread t([&]() { svr.listen_after_bind(); });
  13985. auto se = detail::scope_exit([&] {
  13986. svr.stop();
  13987. t.join();
  13988. ASSERT_FALSE(svr.is_running());
  13989. });
  13990. svr.wait_until_ready();
  13991. Client cli(HOST, port);
  13992. struct {
  13993. const char *path;
  13994. int status;
  13995. } cases[] = {
  13996. {"/literal/route", StatusCode::OK_200},
  13997. {"/literal/routes", StatusCode::NotFound_404},
  13998. {"/literal/rout", StatusCode::NotFound_404},
  13999. {"/abc", StatusCode::OK_200},
  14000. {"/a.c", StatusCode::OK_200},
  14001. };
  14002. for (const auto &x : cases) {
  14003. auto res = cli.Get(x.path);
  14004. ASSERT_TRUE(res) << x.path;
  14005. EXPECT_EQ(x.status, res->status) << x.path;
  14006. }
  14007. }
  14008. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14009. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14010. // from exhausting the stack, so it must only constrain routes that actually
  14011. // run a regular expression. A literal route is matched by comparison and
  14012. // stays usable at any length.
  14013. Server svr;
  14014. const std::string pattern =
  14015. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14016. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14017. res.set_content("hit", "text/plain");
  14018. });
  14019. auto port = svr.bind_to_any_port(HOST);
  14020. std::thread t([&]() { svr.listen_after_bind(); });
  14021. auto se = detail::scope_exit([&] {
  14022. svr.stop();
  14023. t.join();
  14024. ASSERT_FALSE(svr.is_running());
  14025. });
  14026. svr.wait_until_ready();
  14027. Client cli(HOST, port);
  14028. auto res = cli.Get(pattern);
  14029. ASSERT_TRUE(res);
  14030. EXPECT_EQ(StatusCode::OK_200, res->status);
  14031. }
  14032. TEST(ParseUrlTest, VariousPatterns) {
  14033. {
  14034. detail::UrlComponents uc;
  14035. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14036. EXPECT_EQ("http", uc.scheme);
  14037. EXPECT_EQ("example.com", uc.host);
  14038. EXPECT_EQ("8080", uc.port);
  14039. EXPECT_EQ("/path", uc.path);
  14040. EXPECT_EQ("?q=1", uc.query);
  14041. }
  14042. {
  14043. detail::UrlComponents uc;
  14044. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  14045. EXPECT_EQ("https", uc.scheme);
  14046. EXPECT_EQ("example.com", uc.host);
  14047. EXPECT_TRUE(uc.port.empty());
  14048. EXPECT_EQ("/path", uc.path);
  14049. }
  14050. {
  14051. detail::UrlComponents uc;
  14052. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  14053. EXPECT_EQ("::1", uc.host);
  14054. EXPECT_EQ("8080", uc.port);
  14055. EXPECT_EQ("/path", uc.path);
  14056. }
  14057. {
  14058. detail::UrlComponents uc;
  14059. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  14060. }
  14061. {
  14062. // Bytes after the IPv6 literal must be a delimiter, not folded into
  14063. // the path while the connection still targets the bracketed host.
  14064. detail::UrlComponents uc;
  14065. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  14066. }
  14067. {
  14068. detail::UrlComponents uc;
  14069. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  14070. }
  14071. {
  14072. detail::UrlComponents uc;
  14073. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  14074. EXPECT_EQ("::1", uc.host);
  14075. EXPECT_TRUE(uc.port.empty());
  14076. EXPECT_EQ("/path", uc.path);
  14077. }
  14078. {
  14079. detail::UrlComponents uc;
  14080. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  14081. EXPECT_TRUE(uc.scheme.empty());
  14082. EXPECT_EQ("example.com", uc.host);
  14083. EXPECT_EQ("/path", uc.path);
  14084. EXPECT_EQ("?q=1", uc.query);
  14085. }
  14086. {
  14087. detail::UrlComponents uc;
  14088. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  14089. EXPECT_TRUE(uc.host.empty());
  14090. EXPECT_EQ("/path", uc.path);
  14091. EXPECT_EQ("?q=1", uc.query);
  14092. }
  14093. {
  14094. detail::UrlComponents uc;
  14095. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  14096. EXPECT_EQ("example.com", uc.host);
  14097. EXPECT_EQ("8080", uc.port);
  14098. }
  14099. {
  14100. // Unix socket path — must not be parsed as host
  14101. detail::UrlComponents uc;
  14102. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  14103. EXPECT_TRUE(uc.host.empty());
  14104. }
  14105. {
  14106. detail::UrlComponents uc;
  14107. ASSERT_TRUE(detail::parse_url("", uc));
  14108. EXPECT_TRUE(uc.host.empty());
  14109. EXPECT_TRUE(uc.path.empty());
  14110. }
  14111. {
  14112. detail::UrlComponents uc;
  14113. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  14114. }
  14115. {
  14116. detail::UrlComponents uc;
  14117. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  14118. }
  14119. {
  14120. // Accepted by parse_url; callers restrict to http/https
  14121. detail::UrlComponents uc;
  14122. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  14123. EXPECT_EQ("ftp", uc.scheme);
  14124. }
  14125. {
  14126. detail::UrlComponents uc;
  14127. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  14128. }
  14129. {
  14130. detail::UrlComponents uc;
  14131. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  14132. }
  14133. }
  14134. TEST(ParseUrlTest, FragmentHandling) {
  14135. {
  14136. detail::UrlComponents uc;
  14137. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  14138. EXPECT_EQ("/path", uc.path);
  14139. EXPECT_TRUE(uc.query.empty());
  14140. }
  14141. {
  14142. detail::UrlComponents uc;
  14143. ASSERT_TRUE(detail::parse_url("#frag", uc));
  14144. EXPECT_TRUE(uc.path.empty());
  14145. EXPECT_TRUE(uc.query.empty());
  14146. }
  14147. }
  14148. TEST(ParseUrlTest, UserinfoHandling) {
  14149. // Userinfo with @ but no colon — host includes @
  14150. detail::UrlComponents uc;
  14151. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  14152. EXPECT_EQ("user@host.com", uc.host);
  14153. EXPECT_EQ("/path", uc.path);
  14154. }
  14155. TEST(ParseUrlTest, IPv6EdgeCases) {
  14156. {
  14157. detail::UrlComponents uc;
  14158. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  14159. EXPECT_TRUE(uc.scheme.empty());
  14160. EXPECT_EQ("::1", uc.host);
  14161. EXPECT_EQ("8080", uc.port);
  14162. }
  14163. {
  14164. // Zone ID '%25' is not in [a-fA-F0-9:]
  14165. detail::UrlComponents uc;
  14166. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  14167. }
  14168. }
  14169. TEST(ParseUrlTest, SchemeEdgeCases) {
  14170. {
  14171. detail::UrlComponents uc;
  14172. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  14173. }
  14174. {
  14175. detail::UrlComponents uc;
  14176. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  14177. }
  14178. {
  14179. detail::UrlComponents uc;
  14180. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  14181. }
  14182. }
  14183. TEST(ParseUrlTest, PortEdgeCases) {
  14184. {
  14185. detail::UrlComponents uc;
  14186. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  14187. EXPECT_TRUE(uc.port.empty());
  14188. EXPECT_EQ("/path", uc.path);
  14189. }
  14190. {
  14191. // parse_url accepts any port string; validation is done by parse_port
  14192. detail::UrlComponents uc;
  14193. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  14194. EXPECT_EQ("abc", uc.port);
  14195. }
  14196. }
  14197. TEST(ParseUrlTest, WebSocketPatterns) {
  14198. {
  14199. detail::UrlComponents uc;
  14200. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  14201. EXPECT_EQ("ws", uc.scheme);
  14202. EXPECT_EQ("echo.example.com", uc.host);
  14203. EXPECT_EQ("8080", uc.port);
  14204. EXPECT_EQ("/ws", uc.path);
  14205. }
  14206. {
  14207. detail::UrlComponents uc;
  14208. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  14209. EXPECT_EQ("wss", uc.scheme);
  14210. EXPECT_EQ("echo.example.com", uc.host);
  14211. EXPECT_TRUE(uc.port.empty());
  14212. EXPECT_EQ("/ws", uc.path);
  14213. }
  14214. }
  14215. TEST(ParseUrlTest, QueryOnly) {
  14216. detail::UrlComponents uc;
  14217. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  14218. EXPECT_TRUE(uc.host.empty());
  14219. EXPECT_TRUE(uc.path.empty());
  14220. EXPECT_EQ("?q=1&r=2", uc.query);
  14221. }
  14222. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  14223. detail::UrlComponents uc;
  14224. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  14225. EXPECT_TRUE(uc.scheme.empty());
  14226. EXPECT_EQ("example.com", uc.host);
  14227. EXPECT_EQ("443", uc.port);
  14228. EXPECT_EQ("/path", uc.path);
  14229. }
  14230. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  14231. // If ipv6 regex working, regex match codepath is taken.
  14232. // else port will default to 80 in Client impl
  14233. int clientImplMagicPort = 80;
  14234. int port = 4321;
  14235. // above ports must be different to avoid false negative
  14236. EXPECT_NE(clientImplMagicPort, port);
  14237. std::string ipV6TestURL = "http://[ff06::c3]";
  14238. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  14239. CLIENT_PRIVATE_KEY_FILE);
  14240. EXPECT_EQ(cli.port(), port);
  14241. }
  14242. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  14243. auto file_path = "./www/dir/index.html";
  14244. auto dir_path = "./www/dir";
  14245. detail::FileStat stat_file(file_path);
  14246. EXPECT_TRUE(stat_file.is_file());
  14247. EXPECT_FALSE(stat_file.is_dir());
  14248. detail::FileStat stat_dir(dir_path);
  14249. EXPECT_FALSE(stat_dir.is_file());
  14250. EXPECT_TRUE(stat_dir.is_dir());
  14251. }
  14252. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  14253. // IPv4 with default HTTP port (80)
  14254. EXPECT_EQ("example.com",
  14255. detail::make_host_and_port_string("example.com", 80, false));
  14256. // IPv4 with default HTTPS port (443)
  14257. EXPECT_EQ("example.com",
  14258. detail::make_host_and_port_string("example.com", 443, true));
  14259. // IPv4 with non-default HTTP port
  14260. EXPECT_EQ("example.com:8080",
  14261. detail::make_host_and_port_string("example.com", 8080, false));
  14262. // IPv4 with non-default HTTPS port
  14263. EXPECT_EQ("example.com:8443",
  14264. detail::make_host_and_port_string("example.com", 8443, true));
  14265. // IPv6 with default HTTP port (80)
  14266. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  14267. // IPv6 with default HTTPS port (443)
  14268. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  14269. // IPv6 with non-default HTTP port
  14270. EXPECT_EQ("[::1]:8080",
  14271. detail::make_host_and_port_string("::1", 8080, false));
  14272. // IPv6 with non-default HTTPS port
  14273. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  14274. // IPv6 full address with default port
  14275. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  14276. detail::make_host_and_port_string(
  14277. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  14278. // IPv6 full address with non-default port
  14279. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  14280. detail::make_host_and_port_string(
  14281. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  14282. // IPv6 localhost with non-default port
  14283. EXPECT_EQ("[::1]:3000",
  14284. detail::make_host_and_port_string("::1", 3000, false));
  14285. // IPv6 with zone ID (link-local address) with default port
  14286. EXPECT_EQ("[fe80::1%eth0]",
  14287. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  14288. // IPv6 with zone ID (link-local address) with non-default port
  14289. EXPECT_EQ("[fe80::1%eth0]:8080",
  14290. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  14291. // Edge case: Port 443 with is_ssl=false (should add port)
  14292. EXPECT_EQ("example.com:443",
  14293. detail::make_host_and_port_string("example.com", 443, false));
  14294. // Edge case: Port 80 with is_ssl=true (should add port)
  14295. EXPECT_EQ("example.com:80",
  14296. detail::make_host_and_port_string("example.com", 80, true));
  14297. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  14298. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  14299. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  14300. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  14301. // Security fix: Already bracketed IPv6 should not get double brackets
  14302. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  14303. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  14304. EXPECT_EQ("[::1]:8080",
  14305. detail::make_host_and_port_string("[::1]", 8080, false));
  14306. EXPECT_EQ("[2001:db8::1]:8080",
  14307. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  14308. EXPECT_EQ("[fe80::1%eth0]",
  14309. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  14310. EXPECT_EQ("[fe80::1%eth0]:8080",
  14311. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  14312. // Edge case: Empty host (should return as-is)
  14313. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  14314. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  14315. // This is a known limitation but shouldn't crash
  14316. EXPECT_EQ("[host:name]",
  14317. detail::make_host_and_port_string("host:name", 80, false));
  14318. // Port number edge cases (no validation, but should not crash)
  14319. EXPECT_EQ("example.com:0",
  14320. detail::make_host_and_port_string("example.com", 0, false));
  14321. EXPECT_EQ("example.com:-1",
  14322. detail::make_host_and_port_string("example.com", -1, false));
  14323. EXPECT_EQ("example.com:65535",
  14324. detail::make_host_and_port_string("example.com", 65535, false));
  14325. EXPECT_EQ("example.com:65536",
  14326. detail::make_host_and_port_string("example.com", 65536, false));
  14327. }
  14328. #ifdef CPPHTTPLIB_SSL_ENABLED
  14329. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  14330. httplib::SSLClient cli("roblox.com", 443);
  14331. cli.set_follow_location(true);
  14332. auto res = cli.Get("/");
  14333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14334. EXPECT_EQ(StatusCode::OK_200, res->status);
  14335. }
  14336. #endif
  14337. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  14338. Server svr;
  14339. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14340. EXPECT_EQ(res.status, 400);
  14341. });
  14342. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14343. auto se = detail::scope_exit([&] {
  14344. svr.stop();
  14345. thread.join();
  14346. ASSERT_FALSE(svr.is_running());
  14347. });
  14348. svr.wait_until_ready();
  14349. Client cli(HOST, PORT);
  14350. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  14351. }
  14352. TEST(InvalidHeaderCharsTest, is_field_name) {
  14353. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  14354. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  14355. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  14356. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  14357. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  14358. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  14359. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  14360. EXPECT_FALSE(detail::fields::is_field_name(""));
  14361. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  14362. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  14363. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  14364. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  14365. }
  14366. TEST(InvalidHeaderCharsTest, is_field_value) {
  14367. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  14368. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  14369. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  14370. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  14371. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  14372. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  14373. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  14374. EXPECT_TRUE(detail::fields::is_field_value(""));
  14375. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  14376. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  14377. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  14378. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  14379. EXPECT_TRUE(detail::fields::is_field_value("0"));
  14380. }
  14381. TEST(InvalidHeaderCharsTest, OnServer) {
  14382. Server svr;
  14383. svr.Get("/test_name", [&](const Request &req, Response &res) {
  14384. std::string header = "Not Set";
  14385. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14386. res.set_header(header, "value");
  14387. res.set_content("Page Content Page Content", "text/plain");
  14388. });
  14389. svr.Get("/test_value", [&](const Request &req, Response &res) {
  14390. std::string header = "Not Set";
  14391. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14392. res.set_header("X-Test", header);
  14393. res.set_content("Page Content Page Content", "text/plain");
  14394. });
  14395. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14396. auto se = detail::scope_exit([&] {
  14397. svr.stop();
  14398. thread.join();
  14399. ASSERT_FALSE(svr.is_running());
  14400. });
  14401. svr.wait_until_ready();
  14402. Client cli(HOST, PORT);
  14403. {
  14404. auto res = cli.Get(
  14405. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14407. EXPECT_EQ("Page Content Page Content", res->body);
  14408. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14409. }
  14410. {
  14411. auto res = cli.Get(
  14412. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14414. EXPECT_EQ("Page Content Page Content", res->body);
  14415. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  14416. }
  14417. }
  14418. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  14419. auto handled = false;
  14420. Server svr;
  14421. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14422. thread t = thread([&] { svr.listen(HOST, PORT); });
  14423. auto se = detail::scope_exit([&] {
  14424. svr.stop();
  14425. t.join();
  14426. ASSERT_FALSE(svr.is_running());
  14427. ASSERT_FALSE(handled);
  14428. });
  14429. svr.wait_until_ready();
  14430. auto req = "POST /test HTTP/1.1\r\n"
  14431. "Content-Length: x\r\n"
  14432. "\r\n";
  14433. std::string response;
  14434. ASSERT_TRUE(send_request(1, req, &response));
  14435. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14436. response.substr(0, response.find("\r\n")));
  14437. }
  14438. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  14439. // case-insensitive, and a server that receives a 100-continue expectation in
  14440. // an HTTP/1.0 request MUST ignore it.
  14441. static void probe_expect(int port, const std::string &req, bool *got_100) {
  14442. std::string response;
  14443. ASSERT_TRUE(send_request(1, req, &response, port));
  14444. *got_100 = response.find("100 Continue") != std::string::npos;
  14445. }
  14446. class ExpectTokenTest : public ::testing::Test {
  14447. protected:
  14448. void SetUp() override {
  14449. svr_.Post("/p", [](const Request &, Response &res) {
  14450. res.set_content("ok", "text/plain");
  14451. });
  14452. port_ = svr_.bind_to_any_port(HOST);
  14453. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14454. svr_.wait_until_ready();
  14455. }
  14456. void TearDown() override {
  14457. svr_.stop();
  14458. if (thread_.joinable()) { thread_.join(); }
  14459. }
  14460. std::string request(const char *version, const char *expect_value) const {
  14461. return std::string("POST /p ") + version +
  14462. "\r\n"
  14463. "Host: localhost\r\n"
  14464. "Content-Length: 2\r\n"
  14465. "Connection: close\r\n"
  14466. "Expect: " +
  14467. expect_value +
  14468. "\r\n"
  14469. "\r\n"
  14470. "hi";
  14471. }
  14472. Server svr_;
  14473. int port_ = 0;
  14474. thread thread_;
  14475. };
  14476. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  14477. bool got_100 = false;
  14478. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  14479. EXPECT_TRUE(got_100);
  14480. }
  14481. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  14482. bool got_100 = true;
  14483. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  14484. EXPECT_FALSE(got_100);
  14485. }
  14486. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  14487. bool got_100 = false;
  14488. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  14489. EXPECT_TRUE(got_100);
  14490. }
  14491. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  14492. bool got_100 = false;
  14493. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  14494. EXPECT_TRUE(got_100);
  14495. }
  14496. #ifndef _WIN32
  14497. TEST(Expect100ContinueTest, ServerClosesConnection) {
  14498. static constexpr char reject[] = "Unauthorized";
  14499. static constexpr char accept[] = "Upload accepted";
  14500. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  14501. Server svr;
  14502. svr.set_expect_100_continue_handler(
  14503. [](const Request & /*req*/, Response &res) {
  14504. res.status = StatusCode::Unauthorized_401;
  14505. res.set_content(reject, "text/plain");
  14506. return res.status;
  14507. });
  14508. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  14509. res.set_content(accept, "text/plain");
  14510. });
  14511. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14512. auto se = detail::scope_exit([&] {
  14513. svr.stop();
  14514. thread.join();
  14515. ASSERT_FALSE(svr.is_running());
  14516. });
  14517. svr.wait_until_ready();
  14518. {
  14519. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  14520. curl_easy_init(), &curl_easy_cleanup};
  14521. ASSERT_NE(curl, nullptr);
  14522. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  14523. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  14524. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  14525. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  14526. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  14527. &curl_slist_free_all};
  14528. ASSERT_NE(list, nullptr);
  14529. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  14530. struct read_data {
  14531. size_t read_size;
  14532. size_t total_size;
  14533. } data = {0, total_size};
  14534. using read_callback_t =
  14535. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14536. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  14537. void *userdata) -> size_t {
  14538. read_data *d = (read_data *)userdata;
  14539. if (!userdata || d->read_size >= d->total_size) { return 0; }
  14540. std::fill_n(ptr, size * nmemb, 'A');
  14541. d->read_size += size * nmemb;
  14542. return size * nmemb;
  14543. };
  14544. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  14545. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  14546. std::vector<char> buffer;
  14547. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  14548. using write_callback_t =
  14549. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  14550. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  14551. void *userdata) -> size_t {
  14552. std::vector<char> *buf = (std::vector<char> *)userdata;
  14553. buf->reserve(buf->size() + size * nmemb + 1);
  14554. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  14555. return size * nmemb;
  14556. };
  14557. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  14558. {
  14559. const auto res = curl_easy_perform(curl.get());
  14560. ASSERT_EQ(res, CURLE_OK);
  14561. }
  14562. {
  14563. auto response_code = long{};
  14564. const auto res =
  14565. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  14566. ASSERT_EQ(res, CURLE_OK);
  14567. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  14568. }
  14569. {
  14570. auto dl = curl_off_t{};
  14571. const auto res =
  14572. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  14573. ASSERT_EQ(res, CURLE_OK);
  14574. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  14575. }
  14576. {
  14577. buffer.push_back('\0');
  14578. ASSERT_STRCASEEQ(buffer.data(), reject);
  14579. }
  14580. }
  14581. }
  14582. #endif
  14583. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  14584. // Regression test for #2458.
  14585. //
  14586. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  14587. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  14588. // ticket can make the client socket spuriously readable during the
  14589. // 100-continue wait. If the readiness is mistaken for an incoming response,
  14590. // the client withholds the body and then blocks reading a response that never
  14591. // comes, failing with `Failed to read connection`.
  14592. //
  14593. // A correct client (like curl) sends the body once no `100 Continue` arrives
  14594. // within the timeout. This raw OpenSSL server deliberately never sends
  14595. // `100 Continue`; the client must still deliver the body and receive 200.
  14596. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  14597. signal(SIGPIPE, SIG_IGN);
  14598. const auto port = PORT + 4;
  14599. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14600. ASSERT_NE(srv, INVALID_SOCKET);
  14601. int opt = 1;
  14602. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  14603. sockaddr_in addr{};
  14604. addr.sin_family = AF_INET;
  14605. addr.sin_port = htons(static_cast<uint16_t>(port));
  14606. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14607. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14608. ASSERT_EQ(0, ::listen(srv, 1));
  14609. std::atomic<size_t> server_body_bytes{0};
  14610. auto server_thread = std::thread([&] {
  14611. sockaddr_in cli_addr{};
  14612. socklen_t cli_len = sizeof(cli_addr);
  14613. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14614. if (cli == INVALID_SOCKET) { return; }
  14615. // Bound the lifetime of the server side so a buggy client (which never
  14616. // sends the body) cannot make this thread block forever on join.
  14617. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  14618. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14619. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  14620. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  14621. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  14622. SSL *ssl = SSL_new(ctx);
  14623. SSL_set_fd(ssl, static_cast<int>(cli));
  14624. if (SSL_accept(ssl) > 0) {
  14625. // Read the request headers. Reading here also flushes the TLS 1.3
  14626. // session tickets to the client. Deliberately do NOT send
  14627. // `100 Continue`.
  14628. std::string buf;
  14629. char tmp[1024];
  14630. while (buf.find("\r\n\r\n") == std::string::npos) {
  14631. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14632. if (n <= 0) { break; }
  14633. buf.append(tmp, static_cast<size_t>(n));
  14634. }
  14635. // A correct client sends the body now; count what arrives.
  14636. auto pos = buf.find("\r\n\r\n");
  14637. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  14638. while (body < 4096) {
  14639. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  14640. if (n <= 0) { break; }
  14641. body += static_cast<size_t>(n);
  14642. }
  14643. server_body_bytes = body;
  14644. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  14645. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  14646. SSL_shutdown(ssl);
  14647. }
  14648. SSL_free(ssl);
  14649. detail::close_socket(cli);
  14650. SSL_CTX_free(ctx);
  14651. });
  14652. auto se = detail::scope_exit([&] {
  14653. server_thread.join();
  14654. detail::close_socket(srv);
  14655. });
  14656. SSLClient cli("127.0.0.1", port);
  14657. cli.enable_server_certificate_verification(false);
  14658. cli.set_connection_timeout(5, 0);
  14659. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  14660. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  14661. std::string body(4096, 'A');
  14662. auto res = cli.Put("/api/test", body, "application/json");
  14663. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  14664. EXPECT_EQ(StatusCode::OK_200, res->status);
  14665. EXPECT_EQ(body.size(), server_body_bytes.load());
  14666. }
  14667. #endif
  14668. template <typename S, typename C>
  14669. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  14670. svr.Get("/stream", [&](const Request &, Response &res) {
  14671. auto data = new std::string("01234567890123456789");
  14672. res.set_content_provider(
  14673. data->size(), "text/plain",
  14674. [&, data](size_t offset, size_t length, DataSink &sink) {
  14675. const size_t DATA_CHUNK_SIZE = 4;
  14676. const auto &d = *data;
  14677. std::this_thread::sleep_for(std::chrono::seconds(1));
  14678. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  14679. return true;
  14680. },
  14681. [data](bool success) {
  14682. EXPECT_FALSE(success);
  14683. delete data;
  14684. });
  14685. });
  14686. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  14687. auto i = new size_t(0);
  14688. res.set_content_provider(
  14689. "text/plain",
  14690. [i](size_t, DataSink &sink) {
  14691. if (*i < 5) {
  14692. std::this_thread::sleep_for(std::chrono::seconds(1));
  14693. sink.write("abcd", 4);
  14694. (*i)++;
  14695. } else {
  14696. sink.done();
  14697. }
  14698. return true;
  14699. },
  14700. [i](bool success) {
  14701. EXPECT_FALSE(success);
  14702. delete i;
  14703. });
  14704. });
  14705. svr.Get("/chunked", [&](const Request &, Response &res) {
  14706. auto i = new size_t(0);
  14707. res.set_chunked_content_provider(
  14708. "text/plain",
  14709. [i](size_t, DataSink &sink) {
  14710. if (*i < 5) {
  14711. std::this_thread::sleep_for(std::chrono::seconds(1));
  14712. sink.os << "abcd";
  14713. (*i)++;
  14714. } else {
  14715. sink.done();
  14716. }
  14717. return true;
  14718. },
  14719. [i](bool success) {
  14720. EXPECT_FALSE(success);
  14721. delete i;
  14722. });
  14723. });
  14724. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14725. auto se = detail::scope_exit([&] {
  14726. svr.stop();
  14727. listen_thread.join();
  14728. ASSERT_FALSE(svr.is_running());
  14729. });
  14730. svr.wait_until_ready();
  14731. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  14732. {
  14733. auto start = std::chrono::steady_clock::now();
  14734. auto res = cli.Get("/stream");
  14735. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14736. std::chrono::steady_clock::now() - start)
  14737. .count();
  14738. ASSERT_FALSE(res);
  14739. EXPECT_EQ(Error::Read, res.error());
  14740. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14741. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14742. }
  14743. {
  14744. auto start = std::chrono::steady_clock::now();
  14745. auto res = cli.Get("/stream_without_length");
  14746. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14747. std::chrono::steady_clock::now() - start)
  14748. .count();
  14749. ASSERT_FALSE(res);
  14750. EXPECT_EQ(Error::Read, res.error());
  14751. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14752. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14753. }
  14754. {
  14755. auto start = std::chrono::steady_clock::now();
  14756. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  14757. EXPECT_EQ("abcd", string(data, data_length));
  14758. return true;
  14759. });
  14760. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  14761. std::chrono::steady_clock::now() - start)
  14762. .count();
  14763. ASSERT_FALSE(res);
  14764. EXPECT_EQ(Error::Read, res.error());
  14765. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  14766. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  14767. }
  14768. }
  14769. TEST(MaxTimeoutTest, ContentStream) {
  14770. time_t timeout = 2000;
  14771. time_t threshold = 200;
  14772. Server svr;
  14773. Client cli("localhost", PORT);
  14774. max_timeout_test(svr, cli, timeout, threshold);
  14775. }
  14776. #ifdef CPPHTTPLIB_SSL_ENABLED
  14777. TEST(MaxTimeoutTest, ContentStreamSSL) {
  14778. time_t timeout = 2000;
  14779. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  14780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14781. SSLClient cli("localhost", PORT);
  14782. cli.enable_server_certificate_verification(false);
  14783. max_timeout_test(svr, cli, timeout, threshold);
  14784. }
  14785. #endif
  14786. class EventDispatcher {
  14787. public:
  14788. EventDispatcher() {}
  14789. bool wait_event(DataSink *sink) {
  14790. unique_lock<mutex> lk(m_);
  14791. int id = id_;
  14792. // Wait with timeout to prevent hanging if client disconnects
  14793. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  14794. [&] { return cid_ == id; })) {
  14795. return false; // Timeout occurred
  14796. }
  14797. sink->write(message_.data(), message_.size());
  14798. return true;
  14799. }
  14800. void send_event(const string &message) {
  14801. lock_guard<mutex> lk(m_);
  14802. cid_ = id_++;
  14803. message_ = message;
  14804. cv_.notify_all();
  14805. }
  14806. private:
  14807. mutex m_;
  14808. condition_variable cv_;
  14809. atomic_int id_{0};
  14810. atomic_int cid_{-1};
  14811. string message_;
  14812. };
  14813. TEST(ClientInThreadTest, Issue2068) {
  14814. EventDispatcher ed;
  14815. Server svr;
  14816. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  14817. res.set_chunked_content_provider("text/event-stream",
  14818. [&](size_t /*offset*/, DataSink &sink) {
  14819. return ed.wait_event(&sink);
  14820. });
  14821. });
  14822. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  14823. svr.wait_until_ready();
  14824. thread event_thread([&] {
  14825. int id = 0;
  14826. while (svr.is_running()) {
  14827. this_thread::sleep_for(chrono::milliseconds(500));
  14828. std::stringstream ss;
  14829. ss << "data: " << id << "\n\n";
  14830. ed.send_event(ss.str());
  14831. id++;
  14832. }
  14833. });
  14834. auto se = detail::scope_exit([&] {
  14835. svr.stop();
  14836. listen_thread.join();
  14837. event_thread.join();
  14838. ASSERT_FALSE(svr.is_running());
  14839. });
  14840. {
  14841. auto client = detail::make_unique<Client>(HOST, PORT);
  14842. client->set_read_timeout(std::chrono::minutes(10));
  14843. std::atomic<bool> stop{false};
  14844. std::thread t([&] {
  14845. client->Get("/event1",
  14846. [&](const char *, size_t) -> bool { return !stop; });
  14847. });
  14848. std::this_thread::sleep_for(std::chrono::seconds(2));
  14849. stop = true;
  14850. client->stop();
  14851. t.join();
  14852. // Reset client after thread has finished
  14853. client.reset();
  14854. }
  14855. }
  14856. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  14857. auto handled = false;
  14858. Server svr;
  14859. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  14860. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14861. auto se = detail::scope_exit([&] {
  14862. svr.stop();
  14863. t.join();
  14864. ASSERT_FALSE(svr.is_running());
  14865. ASSERT_FALSE(handled);
  14866. });
  14867. svr.wait_until_ready();
  14868. // Two Content-Length headers with different values — must be rejected
  14869. auto req = "POST /test HTTP/1.1\r\n"
  14870. "Content-Length: 5\r\n"
  14871. "Content-Length: 10\r\n"
  14872. "\r\n"
  14873. "hello";
  14874. std::string response;
  14875. ASSERT_TRUE(send_request(1, req, &response));
  14876. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  14877. response.substr(0, response.find("\r\n")));
  14878. }
  14879. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  14880. auto handled = false;
  14881. Server svr;
  14882. svr.Post("/test", [&](const Request &, Response &res) {
  14883. handled = true;
  14884. res.set_content("ok", "text/plain");
  14885. });
  14886. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14887. auto se = detail::scope_exit([&] {
  14888. svr.stop();
  14889. t.join();
  14890. ASSERT_FALSE(svr.is_running());
  14891. ASSERT_TRUE(handled);
  14892. });
  14893. svr.wait_until_ready();
  14894. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  14895. auto req = "POST /test HTTP/1.1\r\n"
  14896. "Content-Length: 5\r\n"
  14897. "Content-Length: 5\r\n"
  14898. "\r\n"
  14899. "hello";
  14900. std::string response;
  14901. ASSERT_TRUE(send_request(1, req, &response));
  14902. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  14903. }
  14904. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  14905. Server svr;
  14906. svr.Get("/", [](const Request &req, Response &res) {
  14907. EXPECT_EQ(2U, req.trailers.size());
  14908. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  14909. // Denied
  14910. EXPECT_FALSE(req.has_trailer("Content-Length"));
  14911. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  14912. // Accepted
  14913. EXPECT_TRUE(req.has_trailer("X-Hello"));
  14914. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  14915. EXPECT_TRUE(req.has_trailer("X-World"));
  14916. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  14917. res.set_content("ok", "text/plain");
  14918. });
  14919. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14920. auto se = detail::scope_exit([&] {
  14921. svr.stop();
  14922. t.join();
  14923. ASSERT_FALSE(svr.is_running());
  14924. });
  14925. svr.wait_until_ready();
  14926. const std::string req = "GET / HTTP/1.1\r\n"
  14927. "Transfer-Encoding: chunked\r\n"
  14928. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  14929. "\r\n"
  14930. "0\r\n"
  14931. "Content-Length: 10\r\n"
  14932. "Host: internal.local\r\n"
  14933. "Content-Type: malicious/content\r\n"
  14934. "Cookie: any\r\n"
  14935. "Set-Cookie: any\r\n"
  14936. "X-Forwarded-For: attacker.com\r\n"
  14937. "X-Real-Ip: 1.1.1.1\r\n"
  14938. "X-Hello: hello\r\n"
  14939. "X-World: world\r\n"
  14940. "\r\n";
  14941. std::string res;
  14942. ASSERT_TRUE(send_request(1, req, &res));
  14943. }
  14944. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  14945. // several field lines, and the combined value is what has to be parsed. A
  14946. // Trailer field split across lines therefore declares every name it lists;
  14947. // reading only the first line silently drops the trailers the later lines
  14948. // declare. The prohibited-trailer filter still applies to every line.
  14949. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  14950. Server svr;
  14951. size_t observed_trailer_count = 0;
  14952. std::string observed_hello;
  14953. std::string observed_world;
  14954. bool observed_content_length = true;
  14955. svr.Get("/", [&](const Request &req, Response &res) {
  14956. observed_trailer_count = req.trailers.size();
  14957. observed_hello = req.get_trailer_value("X-Hello");
  14958. observed_world = req.get_trailer_value("X-World");
  14959. observed_content_length = req.has_trailer("Content-Length");
  14960. res.set_content("ok", "text/plain");
  14961. });
  14962. auto port = svr.bind_to_any_port(HOST);
  14963. thread t = thread([&]() { svr.listen_after_bind(); });
  14964. auto se = detail::scope_exit([&] {
  14965. svr.stop();
  14966. t.join();
  14967. ASSERT_FALSE(svr.is_running());
  14968. });
  14969. svr.wait_until_ready();
  14970. const std::string req = "GET / HTTP/1.1\r\n"
  14971. "Transfer-Encoding: chunked\r\n"
  14972. "Trailer: X-Hello\r\n"
  14973. "Trailer: X-World, Content-Length\r\n"
  14974. "\r\n"
  14975. "0\r\n"
  14976. "X-Hello: hello\r\n"
  14977. "X-World: world\r\n"
  14978. "Content-Length: 10\r\n"
  14979. "\r\n";
  14980. std::string res;
  14981. ASSERT_TRUE(send_request(1, req, &res, port));
  14982. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  14983. // Accepted: both field lines contribute to the declared set
  14984. EXPECT_EQ(2U, observed_trailer_count);
  14985. EXPECT_EQ(observed_hello, "hello");
  14986. EXPECT_EQ(observed_world, "world");
  14987. // Denied: a prohibited name stays prohibited on a later field line
  14988. EXPECT_FALSE(observed_content_length);
  14989. }
  14990. // A direct client that is not listed in trusted_proxies must not be able to
  14991. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  14992. // the peer address on the actual TCP connection determines whether the
  14993. // header is honored.
  14994. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  14995. Server svr;
  14996. // Deliberately does NOT include the loopback address the test client
  14997. // actually connects from, so the direct connection is not a trusted proxy.
  14998. svr.set_trusted_proxies({"203.0.113.66"});
  14999. std::string observed_remote_addr;
  15000. svr.Get("/ip", [&](const Request &req, Response &res) {
  15001. observed_remote_addr = req.remote_addr;
  15002. res.set_content("ok", "text/plain");
  15003. });
  15004. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15005. auto se = detail::scope_exit([&] {
  15006. svr.stop();
  15007. t.join();
  15008. ASSERT_FALSE(svr.is_running());
  15009. });
  15010. svr.wait_until_ready();
  15011. Client cli(HOST, PORT);
  15012. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  15013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15014. EXPECT_EQ(StatusCode::OK_200, res->status);
  15015. // The connecting peer is not a trusted proxy, so the spoofed header must be
  15016. // ignored entirely and the real connection-level address retained.
  15017. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15018. observed_remote_addr == "127.0.0.1");
  15019. }
  15020. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  15021. Server svr;
  15022. std::string observed_remote_addr;
  15023. std::string observed_xff;
  15024. svr.Get("/ip", [&](const Request &req, Response &res) {
  15025. observed_remote_addr = req.remote_addr;
  15026. observed_xff = req.get_header_value("X-Forwarded-For");
  15027. res.set_content("ok", "text/plain");
  15028. });
  15029. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15030. auto se = detail::scope_exit([&] {
  15031. svr.stop();
  15032. t.join();
  15033. ASSERT_FALSE(svr.is_running());
  15034. });
  15035. svr.wait_until_ready();
  15036. Client cli(HOST, PORT);
  15037. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  15038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15039. EXPECT_EQ(StatusCode::OK_200, res->status);
  15040. EXPECT_EQ(observed_xff, "203.0.113.66");
  15041. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15042. observed_remote_addr == "127.0.0.1");
  15043. }
  15044. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  15045. Server svr;
  15046. svr.set_trusted_proxies({"203.0.113.66"});
  15047. std::string observed_remote_addr;
  15048. std::string observed_xff;
  15049. svr.Get("/ip", [&](const Request &req, Response &res) {
  15050. observed_remote_addr = req.remote_addr;
  15051. observed_xff = req.get_header_value("X-Forwarded-For");
  15052. res.set_content("ok", "text/plain");
  15053. });
  15054. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15055. auto se = detail::scope_exit([&] {
  15056. svr.stop();
  15057. t.join();
  15058. ASSERT_FALSE(svr.is_running());
  15059. });
  15060. svr.wait_until_ready();
  15061. Client cli(HOST, PORT);
  15062. auto res = cli.Get("/ip");
  15063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15064. EXPECT_EQ(StatusCode::OK_200, res->status);
  15065. EXPECT_EQ(observed_xff, "");
  15066. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15067. observed_remote_addr == "127.0.0.1");
  15068. }
  15069. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  15070. Server svr;
  15071. // Include the loopback address the test client actually connects from, so
  15072. // the direct connection itself is recognized as the trusted proxy hop.
  15073. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  15074. std::string observed_remote_addr;
  15075. std::string observed_xff;
  15076. svr.Get("/ip", [&](const Request &req, Response &res) {
  15077. observed_remote_addr = req.remote_addr;
  15078. observed_xff = req.get_header_value("X-Forwarded-For");
  15079. res.set_content("ok", "text/plain");
  15080. });
  15081. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15082. auto se = detail::scope_exit([&] {
  15083. svr.stop();
  15084. t.join();
  15085. ASSERT_FALSE(svr.is_running());
  15086. });
  15087. svr.wait_until_ready();
  15088. Client cli(HOST, PORT);
  15089. auto res = cli.Get(
  15090. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  15091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15092. EXPECT_EQ(StatusCode::OK_200, res->status);
  15093. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  15094. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15095. }
  15096. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  15097. Server svr;
  15098. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  15099. std::string observed_remote_addr;
  15100. std::string observed_xff;
  15101. svr.Get("/ip", [&](const Request &req, Response &res) {
  15102. observed_remote_addr = req.remote_addr;
  15103. observed_xff = req.get_header_value("X-Forwarded-For");
  15104. res.set_content("ok", "text/plain");
  15105. });
  15106. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15107. auto se = detail::scope_exit([&] {
  15108. svr.stop();
  15109. t.join();
  15110. ASSERT_FALSE(svr.is_running());
  15111. });
  15112. svr.wait_until_ready();
  15113. Client cli(HOST, PORT);
  15114. auto res = cli.Get(
  15115. "/ip",
  15116. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15118. EXPECT_EQ(StatusCode::OK_200, res->status);
  15119. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15120. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15121. }
  15122. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  15123. Server svr;
  15124. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15125. std::string observed_remote_addr;
  15126. std::string observed_xff;
  15127. svr.Get("/ip", [&](const Request &req, Response &res) {
  15128. observed_remote_addr = req.remote_addr;
  15129. observed_xff = req.get_header_value("X-Forwarded-For");
  15130. res.set_content("ok", "text/plain");
  15131. });
  15132. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15133. auto se = detail::scope_exit([&] {
  15134. svr.stop();
  15135. t.join();
  15136. ASSERT_FALSE(svr.is_running());
  15137. });
  15138. svr.wait_until_ready();
  15139. Client cli(HOST, PORT);
  15140. auto res = cli.Get(
  15141. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  15142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15143. EXPECT_EQ(StatusCode::OK_200, res->status);
  15144. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  15145. // by the closest hop) is used. The leftmost entry is fully client-controlled
  15146. // and must not be selected.
  15147. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  15148. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  15149. }
  15150. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  15151. Server svr;
  15152. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  15153. std::string observed_remote_addr;
  15154. svr.Get("/ip", [&](const Request &req, Response &res) {
  15155. observed_remote_addr = req.remote_addr;
  15156. res.set_content("ok", "text/plain");
  15157. });
  15158. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15159. auto se = detail::scope_exit([&] {
  15160. svr.stop();
  15161. t.join();
  15162. ASSERT_FALSE(svr.is_running());
  15163. });
  15164. svr.wait_until_ready();
  15165. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  15166. // a forged address and the trusted proxy's own address; the forged value must
  15167. // not win over the address the trusted proxy actually recorded.
  15168. Client cli(HOST, PORT);
  15169. auto res = cli.Get(
  15170. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  15171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15172. EXPECT_EQ(StatusCode::OK_200, res->status);
  15173. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  15174. }
  15175. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  15176. Server svr;
  15177. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15178. std::string observed_remote_addr;
  15179. std::string observed_xff;
  15180. svr.Get("/ip", [&](const Request &req, Response &res) {
  15181. observed_remote_addr = req.remote_addr;
  15182. observed_xff = req.get_header_value("X-Forwarded-For");
  15183. res.set_content("ok", "text/plain");
  15184. });
  15185. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15186. auto se = detail::scope_exit([&] {
  15187. svr.stop();
  15188. t.join();
  15189. ASSERT_FALSE(svr.is_running());
  15190. });
  15191. svr.wait_until_ready();
  15192. Client cli(HOST, PORT);
  15193. auto res = cli.Get(
  15194. "/ip",
  15195. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15197. EXPECT_EQ(StatusCode::OK_200, res->status);
  15198. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15199. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15200. }
  15201. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  15202. Server svr;
  15203. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15204. std::string observed_remote_addr;
  15205. std::string observed_xff;
  15206. svr.Get("/ip", [&](const Request &req, Response &res) {
  15207. observed_remote_addr = req.remote_addr;
  15208. observed_xff = req.get_header_value("X-Forwarded-For");
  15209. res.set_content("ok", "text/plain");
  15210. });
  15211. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15212. auto se = detail::scope_exit([&] {
  15213. svr.stop();
  15214. t.join();
  15215. ASSERT_FALSE(svr.is_running());
  15216. });
  15217. svr.wait_until_ready();
  15218. std::string raw_req =
  15219. "GET /ip HTTP/1.1\r\n"
  15220. "Host: localhost\r\n"
  15221. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  15222. "Connection: close\r\n"
  15223. "\r\n";
  15224. std::string out;
  15225. ASSERT_TRUE(send_request(5, raw_req, &out));
  15226. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15227. // Header parser trims surrounding whitespace of the header value
  15228. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  15229. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15230. }
  15231. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  15232. // one comma-joined value, in the order received. Proxies such as HAProxy append
  15233. // their own X-Forwarded-For as a separate field line rather than extending the
  15234. // one the client sent, so every occurrence has to be taken into account.
  15235. // Reading only the first one hands back the address the client chose.
  15236. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  15237. Server svr;
  15238. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15239. std::string observed_remote_addr;
  15240. size_t observed_xff_count = 0;
  15241. svr.Get("/ip", [&](const Request &req, Response &res) {
  15242. observed_remote_addr = req.remote_addr;
  15243. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  15244. res.set_content("ok", "text/plain");
  15245. });
  15246. auto port = svr.bind_to_any_port(HOST);
  15247. thread t = thread([&]() { svr.listen_after_bind(); });
  15248. auto se = detail::scope_exit([&] {
  15249. svr.stop();
  15250. t.join();
  15251. ASSERT_FALSE(svr.is_running());
  15252. });
  15253. svr.wait_until_ready();
  15254. // The client supplies the first field line; the trusted proxy appends the
  15255. // address it observed as a second one.
  15256. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  15257. "Host: localhost\r\n"
  15258. "X-Forwarded-For: 1.2.3.4\r\n"
  15259. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  15260. "Connection: close\r\n"
  15261. "\r\n";
  15262. std::string out;
  15263. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15264. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15265. EXPECT_EQ(observed_xff_count, 2U);
  15266. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15267. // The same chain spread over one field line per hop derives the same client
  15268. // address, i.e. the split and the comma-joined representations agree.
  15269. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  15270. "Host: localhost\r\n"
  15271. "X-Forwarded-For: 1.2.3.4\r\n"
  15272. "X-Forwarded-For: 198.51.100.23\r\n"
  15273. "X-Forwarded-For: 192.0.2.45\r\n"
  15274. "Connection: close\r\n"
  15275. "\r\n";
  15276. out.clear();
  15277. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  15278. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15279. EXPECT_EQ(observed_xff_count, 3U);
  15280. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15281. }
  15282. // An X-Forwarded-For header whose value parses to zero IP segments must not
  15283. // crash the server (it used to call front() on an empty vector inside
  15284. // get_client_ip). The connection-level remote address must be retained instead.
  15285. static void run_malformed_xff_test(const std::string &xff_value) {
  15286. Server svr;
  15287. svr.set_trusted_proxies({"192.0.2.45"});
  15288. std::string observed_remote_addr;
  15289. svr.Get("/ip", [&](const Request &req, Response &res) {
  15290. observed_remote_addr = req.remote_addr;
  15291. res.set_content("ok", "text/plain");
  15292. });
  15293. int port = 0;
  15294. thread t = thread([&]() {
  15295. port = svr.bind_to_any_port(HOST);
  15296. svr.listen_after_bind();
  15297. });
  15298. auto se = detail::scope_exit([&] {
  15299. svr.stop();
  15300. t.join();
  15301. ASSERT_FALSE(svr.is_running());
  15302. });
  15303. svr.wait_until_ready();
  15304. Client cli(HOST, port);
  15305. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  15306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15307. EXPECT_EQ(StatusCode::OK_200, res->status);
  15308. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15309. observed_remote_addr == "127.0.0.1");
  15310. }
  15311. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  15312. run_malformed_xff_test("");
  15313. }
  15314. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  15315. run_malformed_xff_test(",");
  15316. }
  15317. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  15318. run_malformed_xff_test(", , ,");
  15319. }
  15320. // The same rule applies to Accept: a request whose acceptable types are spread
  15321. // over several field lines must be negotiated against all of them.
  15322. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  15323. // case-insensitive connection options. Comparing the whole field value against
  15324. // one option misses a client that sends several of them, and misses every
  15325. // casing but the one written in the comparison.
  15326. //
  15327. // Sends req, reads the response, then reuses the same socket for a second
  15328. // request to find out whether the server kept the connection.
  15329. static void probe_connection_reuse(int port, const std::string &req,
  15330. bool *announced_close, bool *reusable) {
  15331. auto error = Error::Success;
  15332. auto sock = detail::create_client_socket(
  15333. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15334. /*connection_timeout_sec=*/5, 0,
  15335. /*read_timeout_sec=*/1, 0,
  15336. /*write_timeout_sec=*/5, 0, std::string(), error);
  15337. ASSERT_NE(sock, INVALID_SOCKET);
  15338. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  15339. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  15340. "Host: localhost\r\n"
  15341. "Connection: close\r\n"
  15342. "\r\n";
  15343. std::string first_response;
  15344. std::string second_response;
  15345. detail::process_client_socket(
  15346. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  15347. [&](Stream &strm) {
  15348. if (strm.write(req.data(), req.size()) !=
  15349. static_cast<ssize_t>(req.size())) {
  15350. return false;
  15351. }
  15352. char buf[512];
  15353. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  15354. // Headers plus the two-byte body of the handler below
  15355. while (reader.getline()) {
  15356. first_response += reader.ptr();
  15357. if (first_response.find("ok") != std::string::npos) { break; }
  15358. }
  15359. if (strm.write(second.data(), second.size()) !=
  15360. static_cast<ssize_t>(second.size())) {
  15361. return true;
  15362. }
  15363. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  15364. while (reader2.getline()) {
  15365. second_response += reader2.ptr();
  15366. if (second_response.find("ok") != std::string::npos) { break; }
  15367. }
  15368. return true;
  15369. });
  15370. *announced_close =
  15371. first_response.find("Connection: close") != std::string::npos;
  15372. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  15373. }
  15374. class ConnectionTokenTest : public ::testing::Test {
  15375. protected:
  15376. void SetUp() override {
  15377. svr_.Get("/keepalive", [](const Request &, Response &res) {
  15378. res.set_content("ok", "text/plain");
  15379. });
  15380. port_ = svr_.bind_to_any_port(HOST);
  15381. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15382. svr_.wait_until_ready();
  15383. }
  15384. void TearDown() override {
  15385. svr_.stop();
  15386. if (thread_.joinable()) { thread_.join(); }
  15387. }
  15388. Server svr_;
  15389. int port_ = 0;
  15390. thread thread_;
  15391. };
  15392. // "close" alongside another option still closes the connection, and the
  15393. // response says so rather than leaving the peer to discover it.
  15394. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  15395. bool announced_close = false;
  15396. bool reusable = true;
  15397. probe_connection_reuse(port_,
  15398. "GET /keepalive HTTP/1.1\r\n"
  15399. "Host: localhost\r\n"
  15400. "Connection: keep-alive, close\r\n"
  15401. "\r\n",
  15402. &announced_close, &reusable);
  15403. EXPECT_TRUE(announced_close);
  15404. EXPECT_FALSE(reusable);
  15405. }
  15406. // "close" split over two field lines is the same list, so it is honored too.
  15407. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  15408. bool announced_close = false;
  15409. bool reusable = true;
  15410. probe_connection_reuse(port_,
  15411. "GET /keepalive HTTP/1.1\r\n"
  15412. "Host: localhost\r\n"
  15413. "Connection: keep-alive\r\n"
  15414. "Connection: close\r\n"
  15415. "\r\n",
  15416. &announced_close, &reusable);
  15417. EXPECT_TRUE(announced_close);
  15418. EXPECT_FALSE(reusable);
  15419. }
  15420. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  15421. // keep-alive in the spelling everyone actually sends keeps its connection.
  15422. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  15423. bool announced_close = false;
  15424. bool reusable = false;
  15425. probe_connection_reuse(port_,
  15426. "GET /keepalive HTTP/1.0\r\n"
  15427. "Host: localhost\r\n"
  15428. "Connection: keep-alive\r\n"
  15429. "\r\n",
  15430. &announced_close, &reusable);
  15431. EXPECT_FALSE(announced_close);
  15432. EXPECT_TRUE(reusable);
  15433. }
  15434. // A token the value merely contains is not the token itself.
  15435. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  15436. bool announced_close = false;
  15437. bool reusable = false;
  15438. probe_connection_reuse(port_,
  15439. "GET /keepalive HTTP/1.1\r\n"
  15440. "Host: localhost\r\n"
  15441. "Connection: notclose\r\n"
  15442. "\r\n",
  15443. &announced_close, &reusable);
  15444. EXPECT_FALSE(announced_close);
  15445. EXPECT_TRUE(reusable);
  15446. }
  15447. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  15448. Server svr;
  15449. std::vector<std::string> observed_types;
  15450. svr.Get("/", [&](const Request &req, Response &res) {
  15451. observed_types = req.accept_content_types;
  15452. res.set_content("ok", "text/plain");
  15453. });
  15454. auto port = svr.bind_to_any_port(HOST);
  15455. thread t = thread([&]() { svr.listen_after_bind(); });
  15456. auto se = detail::scope_exit([&] {
  15457. svr.stop();
  15458. t.join();
  15459. ASSERT_FALSE(svr.is_running());
  15460. });
  15461. svr.wait_until_ready();
  15462. Client cli(HOST, port);
  15463. Headers headers;
  15464. headers.emplace("Accept", "text/plain;q=0.5");
  15465. headers.emplace("Accept", "application/json");
  15466. auto res = cli.Get("/", headers);
  15467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15468. EXPECT_EQ(StatusCode::OK_200, res->status);
  15469. // Sorted by q-value, so the second field line's type comes first
  15470. ASSERT_EQ(2U, observed_types.size());
  15471. EXPECT_EQ("application/json", observed_types[0]);
  15472. EXPECT_EQ("text/plain", observed_types[1]);
  15473. }
  15474. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  15475. // empty field line must not contribute a bare comma to the combined value.
  15476. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  15477. Server svr;
  15478. std::vector<std::string> observed_types;
  15479. svr.Get("/", [&](const Request &req, Response &res) {
  15480. observed_types = req.accept_content_types;
  15481. res.set_content("ok", "text/plain");
  15482. });
  15483. auto port = svr.bind_to_any_port(HOST);
  15484. thread t = thread([&]() { svr.listen_after_bind(); });
  15485. auto se = detail::scope_exit([&] {
  15486. svr.stop();
  15487. t.join();
  15488. ASSERT_FALSE(svr.is_running());
  15489. });
  15490. svr.wait_until_ready();
  15491. // Empty first field line, then a real one
  15492. std::string raw_req = "GET / HTTP/1.1\r\n"
  15493. "Host: localhost\r\n"
  15494. "Accept:\r\n"
  15495. "Accept: application/json\r\n"
  15496. "Connection: close\r\n"
  15497. "\r\n";
  15498. std::string out;
  15499. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15500. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15501. ASSERT_EQ(1U, observed_types.size());
  15502. EXPECT_EQ("application/json", observed_types[0]);
  15503. }
  15504. // The skip in get_combined_header_value() is what keeps an empty field line
  15505. // from contributing a bare comma. Only a trailing empty field line exercises
  15506. // it: a leading one is already covered by the "combined is still empty" check,
  15507. // and parse_accept_header() now ignores the empty element either way, so the
  15508. // request-level test above can no longer tell the two apart.
  15509. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  15510. Headers headers;
  15511. headers.emplace("Accept", "text/html");
  15512. headers.emplace("Accept", "");
  15513. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  15514. headers.clear();
  15515. headers.emplace("Accept", "");
  15516. headers.emplace("Accept", "application/json");
  15517. EXPECT_EQ("application/json",
  15518. detail::get_combined_header_value(headers, "Accept"));
  15519. }
  15520. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15521. // An encoding offered on a later Accept-Encoding field line is still offered.
  15522. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  15523. Server svr;
  15524. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15525. res.set_content(std::string(1024, 'x'), "text/plain");
  15526. });
  15527. auto port = svr.bind_to_any_port(HOST);
  15528. thread t = thread([&]() { svr.listen_after_bind(); });
  15529. auto se = detail::scope_exit([&] {
  15530. svr.stop();
  15531. t.join();
  15532. ASSERT_FALSE(svr.is_running());
  15533. });
  15534. svr.wait_until_ready();
  15535. Client cli(HOST, port);
  15536. cli.set_decompress(false);
  15537. Headers headers;
  15538. headers.emplace("Accept-Encoding", "identity");
  15539. headers.emplace("Accept-Encoding", "gzip");
  15540. auto res = cli.Get("/", headers);
  15541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15542. EXPECT_EQ(StatusCode::OK_200, res->status);
  15543. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  15544. }
  15545. #endif
  15546. #ifndef _WIN32
  15547. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  15548. Server svr;
  15549. svr.Post("/post", [&](const Request &req, Response &res) {
  15550. res.set_content(req.body, "text/plain");
  15551. });
  15552. svr.Put("/put", [&](const Request &req, Response &res) {
  15553. res.set_content(req.body, "text/plain");
  15554. });
  15555. svr.Patch("/patch", [&](const Request &req, Response &res) {
  15556. res.set_content(req.body, "text/plain");
  15557. });
  15558. svr.Delete("/delete", [&](const Request &req, Response &res) {
  15559. res.set_content(req.body, "text/plain");
  15560. });
  15561. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15562. auto se = detail::scope_exit([&] {
  15563. svr.stop();
  15564. t.join();
  15565. ASSERT_FALSE(svr.is_running());
  15566. });
  15567. svr.wait_until_ready();
  15568. std::string resp;
  15569. // POST without Content-Length
  15570. ASSERT_TRUE(send_request(5,
  15571. "POST /post HTTP/1.1\r\n"
  15572. "Host: localhost\r\n"
  15573. "Connection: close\r\n"
  15574. "\r\n",
  15575. &resp));
  15576. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15577. // PUT without Content-Length
  15578. resp.clear();
  15579. ASSERT_TRUE(send_request(5,
  15580. "PUT /put HTTP/1.1\r\n"
  15581. "Host: localhost\r\n"
  15582. "Connection: close\r\n"
  15583. "\r\n",
  15584. &resp));
  15585. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15586. // PATCH without Content-Length
  15587. resp.clear();
  15588. ASSERT_TRUE(send_request(5,
  15589. "PATCH /patch HTTP/1.1\r\n"
  15590. "Host: localhost\r\n"
  15591. "Connection: close\r\n"
  15592. "\r\n",
  15593. &resp));
  15594. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15595. // DELETE without Content-Length
  15596. resp.clear();
  15597. ASSERT_TRUE(send_request(5,
  15598. "DELETE /delete HTTP/1.1\r\n"
  15599. "Host: localhost\r\n"
  15600. "Connection: close\r\n"
  15601. "\r\n",
  15602. &resp));
  15603. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  15604. }
  15605. #endif
  15606. //==============================================================================
  15607. // open_stream() Tests
  15608. //==============================================================================
  15609. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  15610. std::string result;
  15611. char buf[8192];
  15612. ssize_t n;
  15613. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15614. result.append(buf, static_cast<size_t>(n));
  15615. }
  15616. return result;
  15617. }
  15618. // Mock stream for unit tests
  15619. class MockStream : public Stream {
  15620. public:
  15621. std::string data;
  15622. size_t pos = 0;
  15623. ssize_t error_after = -1; // -1 = no error
  15624. explicit MockStream(const std::string &d, ssize_t err = -1)
  15625. : data(d), error_after(err) {}
  15626. bool is_readable() const override { return true; }
  15627. bool wait_readable() const override { return true; }
  15628. bool wait_writable() const override { return true; }
  15629. ssize_t read(char *ptr, size_t size) override {
  15630. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  15631. if (pos >= data.size()) return 0;
  15632. size_t limit =
  15633. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  15634. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  15635. std::memcpy(ptr, data.data() + pos, to_read);
  15636. pos += to_read;
  15637. return static_cast<ssize_t>(to_read);
  15638. }
  15639. ssize_t write(const char *, size_t) override { return -1; }
  15640. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  15641. ip = "127.0.0.1";
  15642. port = 0;
  15643. }
  15644. void get_local_ip_and_port(std::string &ip, int &port) const override {
  15645. ip = "127.0.0.1";
  15646. port = 0;
  15647. }
  15648. socket_t socket() const override { return INVALID_SOCKET; }
  15649. time_t duration() const override { return 0; }
  15650. };
  15651. TEST(StreamHandleTest, Basic) {
  15652. ClientImpl::StreamHandle handle;
  15653. EXPECT_FALSE(handle.is_valid());
  15654. handle.response = detail::make_unique<Response>();
  15655. handle.error = Error::Connection;
  15656. EXPECT_FALSE(handle.is_valid());
  15657. handle.error = Error::Success;
  15658. EXPECT_TRUE(handle.is_valid());
  15659. }
  15660. TEST(BodyReaderTest, Basic) {
  15661. MockStream stream("Hello, World!");
  15662. detail::BodyReader reader;
  15663. reader.stream = &stream;
  15664. reader.content_length = 13;
  15665. char buf[32];
  15666. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  15667. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  15668. EXPECT_TRUE(reader.eof);
  15669. }
  15670. TEST(BodyReaderTest, NoStream) {
  15671. detail::BodyReader reader;
  15672. char buf[32];
  15673. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15674. EXPECT_EQ(Error::Connection, reader.last_error);
  15675. }
  15676. TEST(BodyReaderTest, Error) {
  15677. MockStream stream("Hello, World!", 5);
  15678. detail::BodyReader reader;
  15679. reader.stream = &stream;
  15680. reader.content_length = 13;
  15681. char buf[32];
  15682. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  15683. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  15684. EXPECT_EQ(Error::Read, reader.last_error);
  15685. }
  15686. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  15687. // Mock-based StreamHandle tests relying on private internals are removed.
  15688. class OpenStreamTest : public ::testing::Test {
  15689. protected:
  15690. void SetUp() override {
  15691. svr_.Get("/hello", [](const Request &, Response &res) {
  15692. res.set_content("Hello World!", "text/plain");
  15693. });
  15694. svr_.Get("/large", [](const Request &, Response &res) {
  15695. res.set_content(std::string(10000, 'X'), "text/plain");
  15696. });
  15697. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  15698. res.set_content("Hello World!", "image/jpeg");
  15699. res.set_header("Content-Encoding", "UTF-8");
  15700. });
  15701. svr_.Get("/chunked", [](const Request &, Response &res) {
  15702. res.set_chunked_content_provider("text/plain",
  15703. [](size_t offset, DataSink &sink) {
  15704. if (offset < 15) {
  15705. sink.write("chunk", 5);
  15706. return true;
  15707. }
  15708. sink.done();
  15709. return true;
  15710. });
  15711. });
  15712. svr_.Get("/compressible", [](const Request &, Response &res) {
  15713. res.set_chunked_content_provider("text/plain", [](size_t offset,
  15714. DataSink &sink) {
  15715. if (offset < 100 * 1024) {
  15716. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  15717. sink.write(chunk.data(), chunk.size());
  15718. return true;
  15719. }
  15720. sink.done();
  15721. return true;
  15722. });
  15723. });
  15724. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  15725. [](const Request & /*req*/, Response &res) {
  15726. auto i = new int(0);
  15727. res.set_header("Trailer", "Content-Length, X-Allowed");
  15728. res.set_chunked_content_provider(
  15729. "text/plain",
  15730. [i](size_t /*offset*/, DataSink &sink) {
  15731. switch (*i) {
  15732. case 0: sink.os << "123"; break;
  15733. case 1: sink.os << "456"; break;
  15734. case 2: sink.os << "789"; break;
  15735. case 3: {
  15736. sink.done_with_trailer(
  15737. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  15738. } break;
  15739. }
  15740. (*i)++;
  15741. return true;
  15742. },
  15743. [i](bool success) {
  15744. EXPECT_TRUE(success);
  15745. delete i;
  15746. });
  15747. });
  15748. // Echo headers endpoint for header-related tests
  15749. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  15750. std::string body;
  15751. for (const auto &h : req.headers) {
  15752. body.append(h.first);
  15753. body.push_back(':');
  15754. body.append(h.second);
  15755. body.push_back('\n');
  15756. }
  15757. res.set_content(body, "text/plain");
  15758. });
  15759. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  15760. std::string body;
  15761. for (const auto &h : req.headers) {
  15762. body.append(h.first);
  15763. body.push_back(':');
  15764. body.append(h.second);
  15765. body.push_back('\n');
  15766. }
  15767. res.set_content(body, "text/plain");
  15768. });
  15769. port_ = svr_.bind_to_any_port("127.0.0.1");
  15770. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15771. svr_.wait_until_ready();
  15772. }
  15773. void TearDown() override {
  15774. svr_.stop();
  15775. if (thread_.joinable()) thread_.join();
  15776. }
  15777. Server svr_;
  15778. std::thread thread_;
  15779. int port_ = 0;
  15780. };
  15781. TEST_F(OpenStreamTest, Basic) {
  15782. Client cli("127.0.0.1", port_);
  15783. auto handle = cli.open_stream("GET", "/hello");
  15784. EXPECT_TRUE(handle.is_valid());
  15785. EXPECT_EQ("Hello World!", read_all(handle));
  15786. }
  15787. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  15788. Client cli("127.0.0.1", port_);
  15789. auto handle = cli.open_stream("GET", "/unknown-encoding");
  15790. ASSERT_TRUE(handle.is_valid());
  15791. EXPECT_EQ("Hello World!", read_all(handle));
  15792. }
  15793. TEST_F(OpenStreamTest, SmallBuffer) {
  15794. Client cli("127.0.0.1", port_);
  15795. auto handle = cli.open_stream("GET", "/hello");
  15796. std::string result;
  15797. char buf[4];
  15798. ssize_t n;
  15799. while ((n = handle.read(buf, sizeof(buf))) > 0)
  15800. result.append(buf, static_cast<size_t>(n));
  15801. EXPECT_EQ("Hello World!", result);
  15802. }
  15803. TEST_F(OpenStreamTest, DefaultHeaders) {
  15804. Client cli("127.0.0.1", port_);
  15805. // open_stream GET should include Host, User-Agent and Accept-Encoding
  15806. {
  15807. auto handle = cli.open_stream("GET", "/echo-headers");
  15808. ASSERT_TRUE(handle.is_valid());
  15809. auto body = read_all(handle);
  15810. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  15811. std::string::npos);
  15812. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  15813. std::string::npos);
  15814. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  15815. }
  15816. // open_stream POST with body and no explicit content_type should NOT add
  15817. // text/plain Content-Type (behavior differs from non-streaming path), but
  15818. // should include Content-Length
  15819. {
  15820. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  15821. ASSERT_TRUE(handle.is_valid());
  15822. auto body = read_all(handle);
  15823. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  15824. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  15825. }
  15826. // open_stream POST with explicit Content-Type should preserve it
  15827. {
  15828. auto handle = cli.open_stream("POST", "/echo-headers", {},
  15829. {{"Content-Type", "application/custom"}},
  15830. "{}", "application/custom");
  15831. ASSERT_TRUE(handle.is_valid());
  15832. auto body = read_all(handle);
  15833. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  15834. }
  15835. // User-specified User-Agent must not be overwritten for stream API
  15836. {
  15837. auto handle = cli.open_stream("GET", "/echo-headers", {},
  15838. {{"User-Agent", "MyAgent/1.2"}});
  15839. ASSERT_TRUE(handle.is_valid());
  15840. auto body = read_all(handle);
  15841. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  15842. }
  15843. }
  15844. TEST_F(OpenStreamTest, Large) {
  15845. Client cli("127.0.0.1", port_);
  15846. auto handle = cli.open_stream("GET", "/large");
  15847. EXPECT_EQ(10000u, read_all(handle).size());
  15848. }
  15849. TEST_F(OpenStreamTest, ConnectionError) {
  15850. Client cli("127.0.0.1", 9999);
  15851. auto handle = cli.open_stream("GET", "/hello");
  15852. EXPECT_FALSE(handle.is_valid());
  15853. }
  15854. TEST_F(OpenStreamTest, Chunked) {
  15855. Client cli("127.0.0.1", port_);
  15856. auto handle = cli.open_stream("GET", "/chunked");
  15857. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15858. "Transfer-Encoding") == "chunked");
  15859. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  15860. }
  15861. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  15862. Client cli("127.0.0.1", port_);
  15863. auto handle =
  15864. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  15865. ASSERT_TRUE(handle.is_valid());
  15866. // Consume body to allow trailers to be received/parsed
  15867. auto body = read_all(handle);
  15868. // Explicitly parse trailers (ensure trailers are available for assertion)
  15869. handle.parse_trailers_if_needed();
  15870. EXPECT_EQ(std::string("123456789"), body);
  15871. // The response should include a Trailer header declaring both names
  15872. ASSERT_TRUE(handle.response);
  15873. EXPECT_TRUE(handle.response->has_header("Trailer"));
  15874. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  15875. handle.response->get_header_value("Trailer"));
  15876. // Prohibited trailer must not be present
  15877. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  15878. // Allowed trailer should be present
  15879. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  15880. EXPECT_EQ(std::string("yes"),
  15881. handle.response->get_trailer_value("X-Allowed"));
  15882. // Verify trailers are NOT present as regular headers
  15883. EXPECT_EQ(std::string(""),
  15884. handle.response->get_header_value("Content-Length"));
  15885. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  15886. }
  15887. static std::thread serve_single_response(std::promise<int> &port_promise,
  15888. const std::string &response) {
  15889. return std::thread([&port_promise, response] {
  15890. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15891. default_socket_options(srv);
  15892. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  15893. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  15894. sockaddr_in addr{};
  15895. addr.sin_family = AF_INET;
  15896. addr.sin_port = htons(0); // Let OS assign a free port
  15897. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15898. int opt = 1;
  15899. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  15900. #ifdef _WIN32
  15901. reinterpret_cast<const char *>(&opt),
  15902. #else
  15903. &opt,
  15904. #endif
  15905. sizeof(opt));
  15906. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  15907. ::listen(srv, 1) != 0) {
  15908. port_promise.set_value(-1);
  15909. detail::close_socket(srv);
  15910. return;
  15911. }
  15912. socklen_t addr_len = sizeof(addr);
  15913. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  15914. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  15915. sockaddr_in cli_addr{};
  15916. socklen_t cli_len = sizeof(cli_addr);
  15917. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15918. if (cli != INVALID_SOCKET) {
  15919. // Read the complete HTTP request (until the blank line that terminates
  15920. // headers) before sending the response. If the server closes the socket
  15921. // while the client's request data is still unread in the kernel receive
  15922. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  15923. // connection on both sides: it discards the client's receive buffer
  15924. // (which already holds our response) and causes any in-progress write on
  15925. // the client to fail with ECONNRESET. Reading all request data first
  15926. // ensures close() emits a graceful FIN.
  15927. {
  15928. char rbuf[256];
  15929. std::string req;
  15930. while (req.find("\r\n\r\n") == std::string::npos) {
  15931. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  15932. if (n <= 0) { break; }
  15933. req.append(rbuf, static_cast<size_t>(n));
  15934. }
  15935. }
  15936. ::send(cli,
  15937. #ifdef _WIN32
  15938. static_cast<const char *>(response.c_str()),
  15939. static_cast<int>(response.size()),
  15940. #else
  15941. response.c_str(), response.size(),
  15942. #endif
  15943. 0);
  15944. detail::close_socket(cli);
  15945. }
  15946. detail::close_socket(srv);
  15947. });
  15948. }
  15949. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  15950. #ifndef _WIN32
  15951. signal(SIGPIPE, SIG_IGN);
  15952. #endif
  15953. std::promise<int> port_promise;
  15954. auto port_future = port_promise.get_future();
  15955. auto server_thread =
  15956. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  15957. "Content-Type: text/plain\r\n"
  15958. "Content-Length: not-a-number\r\n"
  15959. "Connection: close\r\n"
  15960. "\r\n"
  15961. "hello");
  15962. auto port = port_future.get();
  15963. ASSERT_GT(port, 0);
  15964. Client cli("127.0.0.1", port);
  15965. auto handle = cli.open_stream("GET", "/");
  15966. EXPECT_FALSE(handle.is_valid());
  15967. server_thread.join();
  15968. }
  15969. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  15970. #ifndef _WIN32
  15971. signal(SIGPIPE, SIG_IGN);
  15972. #endif
  15973. std::promise<int> port_promise;
  15974. auto port_future = port_promise.get_future();
  15975. auto server_thread = serve_single_response(
  15976. port_promise, "HTTP/1.1 200 OK\r\n"
  15977. "Content-Type: text/plain\r\n"
  15978. "Content-Length: 99999999999999999999999999\r\n"
  15979. "Connection: close\r\n"
  15980. "\r\n"
  15981. "hello");
  15982. auto port = port_future.get();
  15983. ASSERT_GT(port, 0);
  15984. // Historically std::stoull would throw std::out_of_range here and crash
  15985. // the process, then parsing silently clamped to a bogus framing length and
  15986. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  15987. // so the stream fails to open, matching the not-a-number case above. The
  15988. // process still must NOT terminate.
  15989. Client cli("127.0.0.1", port);
  15990. auto handle = cli.open_stream("GET", "/");
  15991. EXPECT_FALSE(handle.is_valid());
  15992. server_thread.join();
  15993. }
  15994. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15995. TEST_F(OpenStreamTest, Gzip) {
  15996. Client cli("127.0.0.1", port_);
  15997. auto handle = cli.open_stream("GET", "/compressible", {},
  15998. {{"Accept-Encoding", "gzip"}});
  15999. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  16000. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16001. }
  16002. #endif
  16003. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16004. TEST_F(OpenStreamTest, Brotli) {
  16005. Client cli("127.0.0.1", port_);
  16006. auto handle =
  16007. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  16008. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  16009. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16010. }
  16011. #endif
  16012. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16013. TEST_F(OpenStreamTest, Zstd) {
  16014. Client cli("127.0.0.1", port_);
  16015. auto handle = cli.open_stream("GET", "/compressible", {},
  16016. {{"Accept-Encoding", "zstd"}});
  16017. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  16018. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16019. }
  16020. #endif
  16021. #ifdef CPPHTTPLIB_SSL_ENABLED
  16022. class SSLOpenStreamTest : public ::testing::Test {
  16023. protected:
  16024. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  16025. void SetUp() override {
  16026. svr_.Get("/hello", [](const Request &, Response &res) {
  16027. res.set_content("Hello SSL World!", "text/plain");
  16028. });
  16029. svr_.Get("/chunked", [](const Request &, Response &res) {
  16030. res.set_chunked_content_provider("text/plain",
  16031. [](size_t offset, DataSink &sink) {
  16032. if (offset < 15) {
  16033. sink.write("chunk", 5);
  16034. return true;
  16035. }
  16036. sink.done();
  16037. return true;
  16038. });
  16039. });
  16040. svr_.Post("/echo", [](const Request &req, Response &res) {
  16041. res.set_content(req.body, req.get_header_value("Content-Type"));
  16042. });
  16043. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  16044. std::string body = req.body;
  16045. res.set_chunked_content_provider(
  16046. "text/plain", [body](size_t offset, DataSink &sink) {
  16047. if (offset < body.size()) {
  16048. sink.write(body.data() + offset, body.size() - offset);
  16049. }
  16050. sink.done();
  16051. return true;
  16052. });
  16053. });
  16054. port_ = svr_.bind_to_any_port("127.0.0.1");
  16055. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16056. svr_.wait_until_ready();
  16057. }
  16058. void TearDown() override {
  16059. svr_.stop();
  16060. if (thread_.joinable()) thread_.join();
  16061. }
  16062. SSLServer svr_;
  16063. std::thread thread_;
  16064. int port_ = 0;
  16065. };
  16066. TEST_F(SSLOpenStreamTest, Basic) {
  16067. SSLClient cli("127.0.0.1", port_);
  16068. cli.enable_server_certificate_verification(false);
  16069. auto handle = cli.open_stream("GET", "/hello");
  16070. ASSERT_TRUE(handle.is_valid());
  16071. EXPECT_EQ("Hello SSL World!", read_all(handle));
  16072. }
  16073. TEST_F(SSLOpenStreamTest, Chunked) {
  16074. SSLClient cli("127.0.0.1", port_);
  16075. cli.enable_server_certificate_verification(false);
  16076. auto handle = cli.open_stream("GET", "/chunked");
  16077. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16078. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16079. "Transfer-Encoding") == "chunked");
  16080. auto body = read_all(handle);
  16081. EXPECT_EQ("chunkchunkchunk", body);
  16082. }
  16083. TEST_F(SSLOpenStreamTest, Post) {
  16084. SSLClient cli("127.0.0.1", port_);
  16085. cli.enable_server_certificate_verification(false);
  16086. auto handle =
  16087. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  16088. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16089. EXPECT_EQ(200, handle.response->status);
  16090. auto body = read_all(handle);
  16091. EXPECT_EQ("Hello SSL POST", body);
  16092. }
  16093. TEST_F(SSLOpenStreamTest, PostChunked) {
  16094. SSLClient cli("127.0.0.1", port_);
  16095. cli.enable_server_certificate_verification(false);
  16096. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  16097. "Chunked SSL Data", "text/plain");
  16098. ASSERT_TRUE(handle.is_valid());
  16099. EXPECT_EQ(200, handle.response->status);
  16100. auto body = read_all(handle);
  16101. EXPECT_EQ("Chunked SSL Data", body);
  16102. }
  16103. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  16104. // Content-Length is terminated by the server closing the connection. When the
  16105. // SSL peer sends a close_notify after the body, the client must treat it as a
  16106. // clean EOF and return a successful response rather than an error.
  16107. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  16108. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16109. ASSERT_TRUE(svr.is_valid());
  16110. svr.set_keep_alive_max_count(1);
  16111. const std::string expected_body = "Hello from connection-close response!";
  16112. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  16113. res.set_content_provider("text/plain",
  16114. [&](size_t offset, DataSink &sink) -> bool {
  16115. if (offset < expected_body.size()) {
  16116. sink.write(expected_body.data() + offset,
  16117. expected_body.size() - offset);
  16118. }
  16119. sink.done();
  16120. return true;
  16121. });
  16122. });
  16123. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  16124. auto se = detail::scope_exit([&] {
  16125. svr.stop();
  16126. listen_thread.join();
  16127. ASSERT_FALSE(svr.is_running());
  16128. });
  16129. svr.wait_until_ready();
  16130. SSLClient cli(HOST, PORT);
  16131. cli.enable_server_certificate_verification(false);
  16132. auto res = cli.Get("/no-content-length");
  16133. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  16134. EXPECT_EQ(StatusCode::OK_200, res->status);
  16135. EXPECT_EQ(expected_body, res->body);
  16136. }
  16137. #endif // CPPHTTPLIB_SSL_ENABLED
  16138. //==============================================================================
  16139. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  16140. // results for various scenarios.
  16141. //==============================================================================
  16142. TEST(ParityTest, GetVsOpenStream) {
  16143. Server svr;
  16144. const std::string path = "/parity";
  16145. const std::string content = "Parity test content: hello world";
  16146. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16147. res.set_content(content, "text/plain");
  16148. });
  16149. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16150. auto se = detail::scope_exit([&] {
  16151. svr.stop();
  16152. t.join();
  16153. ASSERT_FALSE(svr.is_running());
  16154. });
  16155. svr.wait_until_ready();
  16156. Client cli(HOST, PORT);
  16157. // Non-stream path
  16158. auto r1 = cli.Get(path);
  16159. ASSERT_TRUE(r1);
  16160. EXPECT_EQ(StatusCode::OK_200, r1->status);
  16161. // Stream path
  16162. auto h = cli.open_stream("GET", path);
  16163. ASSERT_TRUE(h.is_valid());
  16164. EXPECT_EQ(r1->body, read_all(h));
  16165. }
  16166. // Helper to compress data with provided compressor type T
  16167. template <typename Compressor>
  16168. static std::string compress_payload_for_parity(const std::string &in) {
  16169. std::string out;
  16170. Compressor compressor;
  16171. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  16172. [&](const char *data, size_t n) {
  16173. out.append(data, n);
  16174. return true;
  16175. });
  16176. EXPECT_TRUE(ok);
  16177. return out;
  16178. }
  16179. // Helper function for compression parity tests
  16180. template <typename Compressor>
  16181. static void test_compression_parity(const std::string &original,
  16182. const std::string &path,
  16183. const std::string &encoding) {
  16184. const std::string compressed =
  16185. compress_payload_for_parity<Compressor>(original);
  16186. Server svr;
  16187. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16188. res.set_content(compressed, "application/octet-stream");
  16189. res.set_header("Content-Encoding", encoding);
  16190. });
  16191. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  16192. auto se = detail::scope_exit([&] {
  16193. svr.stop();
  16194. t.join();
  16195. ASSERT_FALSE(svr.is_running());
  16196. });
  16197. svr.wait_until_ready();
  16198. Client cli(HOST, PORT);
  16199. // Non-streaming
  16200. {
  16201. auto res = cli.Get(path);
  16202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16203. EXPECT_EQ(StatusCode::OK_200, res->status);
  16204. EXPECT_EQ(original, res->body);
  16205. }
  16206. // Streaming
  16207. {
  16208. auto h = cli.open_stream("GET", path);
  16209. ASSERT_TRUE(h.is_valid());
  16210. EXPECT_EQ(original, read_all(h));
  16211. }
  16212. }
  16213. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16214. TEST(ParityTest, Gzip) {
  16215. test_compression_parity<detail::gzip_compressor>(
  16216. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  16217. }
  16218. #endif
  16219. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16220. TEST(ParityTest, Brotli) {
  16221. test_compression_parity<detail::brotli_compressor>(
  16222. "Hello, brotli parity test payload", "/parity-br", "br");
  16223. }
  16224. #endif
  16225. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16226. TEST(ParityTest, Zstd) {
  16227. test_compression_parity<detail::zstd_compressor>(
  16228. "Zstandard parity test payload", "/parity-zstd", "zstd");
  16229. }
  16230. #endif
  16231. //==============================================================================
  16232. // New Stream API Tests
  16233. //==============================================================================
  16234. inline std::string read_body(httplib::stream::Result &result) {
  16235. std::string body;
  16236. while (result.next()) {
  16237. body.append(result.data(), result.size());
  16238. }
  16239. return body;
  16240. }
  16241. TEST(ClientConnectionTest, Basic) {
  16242. httplib::ClientConnection conn;
  16243. EXPECT_FALSE(conn.is_open());
  16244. conn.sock = 1;
  16245. EXPECT_TRUE(conn.is_open());
  16246. httplib::ClientConnection conn2(std::move(conn));
  16247. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  16248. conn2.sock = INVALID_SOCKET;
  16249. }
  16250. // Unified test server for all stream::* tests
  16251. class StreamApiTest : public ::testing::Test {
  16252. protected:
  16253. void SetUp() override {
  16254. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16255. res.set_content("Hello World!", "text/plain");
  16256. });
  16257. svr_.Get("/echo-params",
  16258. [](const httplib::Request &req, httplib::Response &res) {
  16259. std::string r;
  16260. for (const auto &p : req.params) {
  16261. if (!r.empty()) r += "&";
  16262. r += p.first + "=" + p.second;
  16263. }
  16264. res.set_content(r, "text/plain");
  16265. });
  16266. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16267. res.set_content(req.body, req.get_header_value("Content-Type"));
  16268. });
  16269. svr_.Post("/echo-headers",
  16270. [](const httplib::Request &req, httplib::Response &res) {
  16271. std::string r;
  16272. for (const auto &h : req.headers)
  16273. r += h.first + ": " + h.second + "\n";
  16274. res.set_content(r, "text/plain");
  16275. });
  16276. svr_.Post("/echo-params",
  16277. [](const httplib::Request &req, httplib::Response &res) {
  16278. std::string r = "params:";
  16279. for (const auto &p : req.params)
  16280. r += p.first + "=" + p.second + ";";
  16281. res.set_content(r + " body:" + req.body, "text/plain");
  16282. });
  16283. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  16284. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  16285. });
  16286. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16287. res.set_content("PUT:" + req.body, "text/plain");
  16288. });
  16289. svr_.Patch("/echo",
  16290. [](const httplib::Request &req, httplib::Response &res) {
  16291. res.set_content("PATCH:" + req.body, "text/plain");
  16292. });
  16293. svr_.Delete(
  16294. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  16295. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  16296. "text/plain");
  16297. });
  16298. svr_.Get("/head-test",
  16299. [](const httplib::Request &, httplib::Response &res) {
  16300. res.set_content("body for HEAD", "text/plain");
  16301. });
  16302. svr_.Options("/options",
  16303. [](const httplib::Request &, httplib::Response &res) {
  16304. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  16305. });
  16306. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  16307. svr_.wait_until_ready();
  16308. }
  16309. void TearDown() override {
  16310. svr_.stop();
  16311. if (thread_.joinable()) thread_.join();
  16312. }
  16313. httplib::Server svr_;
  16314. std::thread thread_;
  16315. };
  16316. // stream::Get tests
  16317. TEST_F(StreamApiTest, GetBasic) {
  16318. httplib::Client cli(HOST, PORT);
  16319. auto result = httplib::stream::Get(cli, "/hello");
  16320. ASSERT_TRUE(result.is_valid());
  16321. EXPECT_EQ(200, result.status());
  16322. EXPECT_EQ("Hello World!", read_body(result));
  16323. }
  16324. TEST_F(StreamApiTest, GetWithParams) {
  16325. httplib::Client cli(HOST, PORT);
  16326. httplib::Params params{{"foo", "bar"}};
  16327. auto result = httplib::stream::Get(cli, "/echo-params", params);
  16328. ASSERT_TRUE(result.is_valid());
  16329. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  16330. }
  16331. TEST_F(StreamApiTest, GetConnectionError) {
  16332. httplib::Client cli(HOST, 9999);
  16333. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  16334. }
  16335. TEST_F(StreamApiTest, Get404) {
  16336. httplib::Client cli(HOST, PORT);
  16337. auto result = httplib::stream::Get(cli, "/nonexistent");
  16338. EXPECT_TRUE(result.is_valid());
  16339. EXPECT_EQ(404, result.status());
  16340. }
  16341. // stream::Post tests
  16342. TEST_F(StreamApiTest, PostBasic) {
  16343. httplib::Client cli(HOST, PORT);
  16344. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  16345. "application/json");
  16346. ASSERT_TRUE(result.is_valid());
  16347. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  16348. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  16349. }
  16350. TEST_F(StreamApiTest, PostWithHeaders) {
  16351. httplib::Client cli(HOST, PORT);
  16352. httplib::Headers headers{{"X-Custom", "value"}};
  16353. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  16354. "text/plain");
  16355. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  16356. }
  16357. TEST_F(StreamApiTest, PostWithParams) {
  16358. httplib::Client cli(HOST, PORT);
  16359. httplib::Params params{{"k", "v"}};
  16360. auto result =
  16361. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  16362. auto body = read_body(result);
  16363. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  16364. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  16365. }
  16366. TEST_F(StreamApiTest, PostLarge) {
  16367. httplib::Client cli(HOST, PORT);
  16368. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  16369. size_t total = 0;
  16370. while (result.next()) {
  16371. total += result.size();
  16372. }
  16373. EXPECT_EQ(100u * 1024u, total);
  16374. }
  16375. // stream::Put/Patch tests
  16376. TEST_F(StreamApiTest, PutAndPatch) {
  16377. httplib::Client cli(HOST, PORT);
  16378. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  16379. EXPECT_EQ("PUT:test", read_body(put));
  16380. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  16381. EXPECT_EQ("PATCH:test", read_body(patch));
  16382. }
  16383. // stream::Delete tests
  16384. TEST_F(StreamApiTest, Delete) {
  16385. httplib::Client cli(HOST, PORT);
  16386. auto del1 = httplib::stream::Delete(cli, "/resource");
  16387. EXPECT_EQ("Deleted", read_body(del1));
  16388. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  16389. EXPECT_EQ("Deleted:data", read_body(del2));
  16390. }
  16391. // stream::Head/Options tests
  16392. TEST_F(StreamApiTest, HeadAndOptions) {
  16393. httplib::Client cli(HOST, PORT);
  16394. auto head = httplib::stream::Head(cli, "/head-test");
  16395. EXPECT_TRUE(head.is_valid());
  16396. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  16397. auto opts = httplib::stream::Options(cli, "/options");
  16398. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  16399. }
  16400. // SSL stream::* tests
  16401. #ifdef CPPHTTPLIB_SSL_ENABLED
  16402. class SSLStreamApiTest : public ::testing::Test {
  16403. protected:
  16404. void SetUp() override {
  16405. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16406. res.set_content("Hello SSL!", "text/plain");
  16407. });
  16408. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16409. res.set_content(req.body, "text/plain");
  16410. });
  16411. port_ = svr_.bind_to_any_port("127.0.0.1");
  16412. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16413. svr_.wait_until_ready();
  16414. }
  16415. void TearDown() override {
  16416. svr_.stop();
  16417. if (thread_.joinable()) thread_.join();
  16418. }
  16419. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  16420. std::thread thread_;
  16421. int port_ = 0;
  16422. };
  16423. TEST_F(SSLStreamApiTest, GetAndPost) {
  16424. httplib::SSLClient cli("127.0.0.1", port_);
  16425. cli.enable_server_certificate_verification(false);
  16426. auto get = httplib::stream::Get(cli, "/hello");
  16427. EXPECT_EQ("Hello SSL!", read_body(get));
  16428. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  16429. EXPECT_EQ("test", read_body(post));
  16430. }
  16431. #endif
  16432. // Tests for Error::Timeout and Error::ConnectionClosed error types
  16433. // These errors are set in SocketStream/SSLSocketStream and propagated through
  16434. // BodyReader
  16435. TEST(ErrorHandlingTest, StreamReadTimeout) {
  16436. // Test that read timeout during streaming is detected
  16437. // Use a large content-length response where server delays mid-stream
  16438. Server svr;
  16439. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16440. // Send a large response with delay in the middle
  16441. res.set_content_provider(
  16442. 1000, // content_length
  16443. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  16444. if (offset < 100) {
  16445. // Send first 100 bytes immediately
  16446. std::string data(100, 'A');
  16447. sink.write(data.c_str(), data.size());
  16448. return true;
  16449. }
  16450. // Then delay longer than client timeout
  16451. std::this_thread::sleep_for(std::chrono::seconds(3));
  16452. std::string data(900, 'B');
  16453. sink.write(data.c_str(), data.size());
  16454. return true;
  16455. });
  16456. });
  16457. auto port = 8091;
  16458. std::thread t([&]() { svr.listen("localhost", port); });
  16459. svr.wait_until_ready();
  16460. Client cli("localhost", port);
  16461. cli.set_read_timeout(1, 0); // 1 second timeout
  16462. auto handle = cli.open_stream("GET", "/slow-stream");
  16463. ASSERT_TRUE(handle.is_valid());
  16464. char buf[256];
  16465. ssize_t total = 0;
  16466. ssize_t n;
  16467. bool got_error = false;
  16468. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16469. total += n;
  16470. }
  16471. if (n < 0) {
  16472. got_error = true;
  16473. // Should be timeout or read error
  16474. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16475. handle.get_read_error() == Error::Read)
  16476. << "Actual error: " << to_string(handle.get_read_error());
  16477. }
  16478. // Either we got an error, or we got less data than expected
  16479. EXPECT_TRUE(got_error || total < 1000)
  16480. << "Expected timeout but got all " << total << " bytes";
  16481. svr.stop();
  16482. t.join();
  16483. }
  16484. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  16485. // Test connection closed detection via BodyReader
  16486. Server svr;
  16487. std::atomic<bool> close_now{false};
  16488. svr.Get("/will-close", [&](const Request &, Response &res) {
  16489. res.set_content_provider(
  16490. 10000, // Large content_length that we won't fully send
  16491. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16492. if (offset < 100) {
  16493. std::string data(100, 'X');
  16494. sink.write(data.c_str(), data.size());
  16495. return true;
  16496. }
  16497. // Wait for signal then abort
  16498. while (!close_now) {
  16499. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16500. }
  16501. return false; // Abort - server will close connection
  16502. });
  16503. });
  16504. auto port = 8092;
  16505. std::thread t([&]() { svr.listen("localhost", port); });
  16506. svr.wait_until_ready();
  16507. Client cli("localhost", port);
  16508. auto handle = cli.open_stream("GET", "/will-close");
  16509. ASSERT_TRUE(handle.is_valid());
  16510. char buf[256];
  16511. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16512. EXPECT_GT(n, 0) << "First read should succeed";
  16513. // Signal server to close
  16514. close_now = true;
  16515. // Keep reading until error or EOF
  16516. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16517. // Keep reading
  16518. }
  16519. // Should get an error since content_length wasn't satisfied
  16520. if (n < 0) {
  16521. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16522. handle.get_read_error() == Error::Read)
  16523. << "Actual error: " << to_string(handle.get_read_error());
  16524. }
  16525. svr.stop();
  16526. t.join();
  16527. }
  16528. #ifdef CPPHTTPLIB_SSL_ENABLED
  16529. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  16530. // Test that read timeout during SSL streaming is detected
  16531. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16532. svr.Get("/slow-stream", [](const Request &, Response &res) {
  16533. res.set_content_provider(
  16534. 1000, "text/plain",
  16535. [](size_t offset, size_t /*length*/, DataSink &sink) {
  16536. if (offset < 100) {
  16537. std::string data(100, 'A');
  16538. sink.write(data.c_str(), data.size());
  16539. return true;
  16540. }
  16541. std::this_thread::sleep_for(std::chrono::seconds(3));
  16542. std::string data(900, 'B');
  16543. sink.write(data.c_str(), data.size());
  16544. return true;
  16545. });
  16546. });
  16547. auto port = 8093;
  16548. std::thread t([&]() { svr.listen("localhost", port); });
  16549. svr.wait_until_ready();
  16550. SSLClient cli("localhost", port);
  16551. cli.enable_server_certificate_verification(false);
  16552. cli.set_read_timeout(1, 0); // 1 second timeout
  16553. auto handle = cli.open_stream("GET", "/slow-stream");
  16554. ASSERT_TRUE(handle.is_valid());
  16555. char buf[256];
  16556. ssize_t total = 0;
  16557. ssize_t n;
  16558. bool got_error = false;
  16559. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16560. total += n;
  16561. }
  16562. if (n < 0) {
  16563. got_error = true;
  16564. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  16565. handle.get_read_error() == Error::Read)
  16566. << "Actual error: " << to_string(handle.get_read_error());
  16567. }
  16568. EXPECT_TRUE(got_error || total < 1000)
  16569. << "Expected timeout but got all " << total << " bytes";
  16570. svr.stop();
  16571. t.join();
  16572. }
  16573. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  16574. // Test SSL connection closed detection
  16575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16576. std::atomic<bool> close_now{false};
  16577. svr.Get("/will-close", [&](const Request &, Response &res) {
  16578. res.set_content_provider(
  16579. 10000, "text/plain",
  16580. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  16581. if (offset < 100) {
  16582. std::string data(100, 'X');
  16583. sink.write(data.c_str(), data.size());
  16584. return true;
  16585. }
  16586. while (!close_now) {
  16587. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16588. }
  16589. return false;
  16590. });
  16591. });
  16592. auto port = 8094;
  16593. std::thread t([&]() { svr.listen("localhost", port); });
  16594. svr.wait_until_ready();
  16595. SSLClient cli("localhost", port);
  16596. cli.enable_server_certificate_verification(false);
  16597. auto handle = cli.open_stream("GET", "/will-close");
  16598. ASSERT_TRUE(handle.is_valid());
  16599. char buf[256];
  16600. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  16601. EXPECT_GT(n, 0);
  16602. // Signal server to close
  16603. close_now = true;
  16604. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16605. // Keep reading
  16606. }
  16607. if (n < 0) {
  16608. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  16609. handle.get_read_error() == Error::Read)
  16610. << "Actual error: " << to_string(handle.get_read_error());
  16611. }
  16612. svr.stop();
  16613. t.join();
  16614. }
  16615. #endif
  16616. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  16617. using namespace httplib;
  16618. // Create a test file
  16619. const char *fname = "etag_testfile.txt";
  16620. const char *content = "etag-content";
  16621. {
  16622. std::ofstream ofs(fname);
  16623. ofs << content;
  16624. ASSERT_TRUE(ofs.good());
  16625. }
  16626. Server svr;
  16627. svr.set_mount_point("/static", ".");
  16628. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16629. svr.wait_until_ready();
  16630. Client cli(HOST, PORT);
  16631. // First request: should get 200 with ETag header
  16632. auto res1 = cli.Get("/static/etag_testfile.txt");
  16633. ASSERT_TRUE(res1);
  16634. ASSERT_EQ(200, res1->status);
  16635. ASSERT_TRUE(res1->has_header("ETag"));
  16636. std::string etag = res1->get_header_value("ETag");
  16637. EXPECT_FALSE(etag.empty());
  16638. // Verify ETag format: W/"hex-hex"
  16639. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  16640. EXPECT_EQ('W', etag[0]);
  16641. EXPECT_EQ('/', etag[1]);
  16642. EXPECT_EQ('"', etag[2]);
  16643. EXPECT_EQ('"', etag.back());
  16644. // Exact match: expect 304 Not Modified
  16645. Headers h2 = {{"If-None-Match", etag}};
  16646. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  16647. ASSERT_TRUE(res2);
  16648. EXPECT_EQ(304, res2->status);
  16649. // Wildcard match: expect 304 Not Modified
  16650. Headers h3 = {{"If-None-Match", "*"}};
  16651. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  16652. ASSERT_TRUE(res3);
  16653. EXPECT_EQ(304, res3->status);
  16654. // Non-matching ETag: expect 200
  16655. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  16656. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  16657. ASSERT_TRUE(res4);
  16658. EXPECT_EQ(200, res4->status);
  16659. // Multiple ETags with one matching: expect 304
  16660. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  16661. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  16662. ASSERT_TRUE(res5);
  16663. EXPECT_EQ(304, res5->status);
  16664. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  16665. // that equivalent to the single comma-separated list above, so the match on
  16666. // the second line must still be found.
  16667. Headers h6;
  16668. h6.emplace("If-None-Match", "W/\"other\"");
  16669. h6.emplace("If-None-Match", etag);
  16670. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  16671. ASSERT_TRUE(res6);
  16672. EXPECT_EQ(304, res6->status);
  16673. svr.stop();
  16674. t.join();
  16675. std::remove(fname);
  16676. }
  16677. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  16678. using namespace httplib;
  16679. Server svr;
  16680. svr.set_mount_point("/static", ".");
  16681. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16682. svr.wait_until_ready();
  16683. Client cli(HOST, PORT);
  16684. // Send If-None-Match: * to a non-existent file
  16685. Headers h = {{"If-None-Match", "*"}};
  16686. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  16687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16688. EXPECT_EQ(404, res->status);
  16689. svr.stop();
  16690. t.join();
  16691. }
  16692. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  16693. using namespace httplib;
  16694. // Create a test file
  16695. const char *fname = "etag_boundary_testfile.txt";
  16696. const char *content = "boundary-test";
  16697. {
  16698. std::ofstream ofs(fname);
  16699. ofs << content;
  16700. ASSERT_TRUE(ofs.good());
  16701. }
  16702. Server svr;
  16703. svr.set_mount_point("/static", ".");
  16704. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  16705. svr.wait_until_ready();
  16706. Client cli(HOST, PORT);
  16707. // Get the actual ETag
  16708. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  16709. ASSERT_TRUE(res1);
  16710. ASSERT_EQ(200, res1->status);
  16711. ASSERT_TRUE(res1->has_header("ETag"));
  16712. std::string etag = res1->get_header_value("ETag");
  16713. // Test 1: Very long ETag value (longer than actual ETag)
  16714. // Should NOT match and return 200 (not trigger out-of-bounds read)
  16715. Headers h1 = {{"If-None-Match", "W/"
  16716. "\"very-long-etag-value-that-is-much-longer-"
  16717. "than-the-actual-etag-value\""}};
  16718. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  16719. ASSERT_TRUE(res2);
  16720. EXPECT_EQ(200, res2->status); // Should not match
  16721. // Test 2: Long string followed by wildcard
  16722. // Should match on "*" and return 304 (without out-of-bounds read on the long
  16723. // string)
  16724. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  16725. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  16726. ASSERT_TRUE(res3);
  16727. EXPECT_EQ(304, res3->status); // Should match on "*"
  16728. // Test 3: Wildcard followed by long string
  16729. // Should match on "*" immediately and return 304
  16730. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  16731. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  16732. ASSERT_TRUE(res4);
  16733. EXPECT_EQ(304, res4->status); // Should match on "*"
  16734. // Test 4: Multiple long non-matching values
  16735. // Should NOT match and return 200 (test that all comparisons are safe)
  16736. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  16737. "W/\"second-long-non-matching-value\", "
  16738. "W/\"third-long-non-matching-value\""}};
  16739. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  16740. ASSERT_TRUE(res5);
  16741. EXPECT_EQ(200, res5->status); // Should not match
  16742. // Test 5: Single character that is not "*" (edge case)
  16743. Headers h5 = {{"If-None-Match", "X"}};
  16744. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  16745. ASSERT_TRUE(res6);
  16746. EXPECT_EQ(200, res6->status); // Should not match
  16747. svr.stop();
  16748. t.join();
  16749. std::remove(fname);
  16750. }
  16751. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  16752. using namespace httplib;
  16753. // Create a test file
  16754. const char *fname = "ims_testfile.txt";
  16755. const char *content = "if-modified-since-test";
  16756. {
  16757. std::ofstream ofs(fname);
  16758. ofs << content;
  16759. ASSERT_TRUE(ofs.good());
  16760. }
  16761. Server svr;
  16762. svr.set_mount_point("/static", ".");
  16763. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16764. svr.wait_until_ready();
  16765. Client cli(HOST, PORT);
  16766. // First request: should get 200 with Last-Modified header
  16767. auto res1 = cli.Get("/static/ims_testfile.txt");
  16768. ASSERT_TRUE(res1);
  16769. ASSERT_EQ(200, res1->status);
  16770. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16771. std::string last_modified = res1->get_header_value("Last-Modified");
  16772. EXPECT_FALSE(last_modified.empty());
  16773. // If-Modified-Since with same time: expect 304
  16774. Headers h2 = {{"If-Modified-Since", last_modified}};
  16775. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  16776. ASSERT_TRUE(res2);
  16777. EXPECT_EQ(304, res2->status);
  16778. // If-Modified-Since with future time: expect 304
  16779. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16780. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  16781. ASSERT_TRUE(res3);
  16782. EXPECT_EQ(304, res3->status);
  16783. // If-Modified-Since with past time: expect 200
  16784. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16785. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  16786. ASSERT_TRUE(res4);
  16787. EXPECT_EQ(200, res4->status);
  16788. // If-None-Match takes precedence over If-Modified-Since
  16789. // (send matching ETag with old If-Modified-Since -> should still be 304)
  16790. ASSERT_TRUE(res1->has_header("ETag"));
  16791. std::string etag = res1->get_header_value("ETag");
  16792. Headers h5 = {{"If-None-Match", etag},
  16793. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16794. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  16795. ASSERT_TRUE(res5);
  16796. EXPECT_EQ(304, res5->status);
  16797. svr.stop();
  16798. t.join();
  16799. std::remove(fname);
  16800. }
  16801. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  16802. using namespace httplib;
  16803. Server svr;
  16804. // Endpoint that returns compressible content
  16805. svr.Get("/compressible", [](const Request &, Response &res) {
  16806. // Return a large enough body to trigger compression
  16807. std::string body(1000, 'a');
  16808. res.set_content(body, "text/plain");
  16809. });
  16810. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16811. svr.wait_until_ready();
  16812. Client cli(HOST, PORT);
  16813. // Request with gzip support: should get Vary header when compressed
  16814. cli.set_compress(true);
  16815. auto res1 = cli.Get("/compressible");
  16816. ASSERT_TRUE(res1);
  16817. EXPECT_EQ(200, res1->status);
  16818. // If Content-Encoding is set, Vary should also be set
  16819. if (res1->has_header("Content-Encoding")) {
  16820. EXPECT_TRUE(res1->has_header("Vary"));
  16821. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  16822. }
  16823. // Request without Accept-Encoding header: should not have compression
  16824. Headers h_no_compress;
  16825. auto res2 = cli.Get("/compressible", h_no_compress);
  16826. ASSERT_TRUE(res2);
  16827. EXPECT_EQ(200, res2->status);
  16828. // Verify Vary header is present when compression is applied
  16829. // (the exact behavior depends on server configuration)
  16830. svr.stop();
  16831. t.join();
  16832. }
  16833. TEST(ETagTest, IfRangeWithETag) {
  16834. using namespace httplib;
  16835. // Create a test file with known content
  16836. const char *fname = "if_range_testfile.txt";
  16837. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  16838. {
  16839. std::ofstream ofs(fname);
  16840. ofs << content;
  16841. ASSERT_TRUE(ofs.good());
  16842. }
  16843. Server svr;
  16844. svr.set_mount_point("/static", ".");
  16845. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16846. svr.wait_until_ready();
  16847. Client cli(HOST, PORT);
  16848. // First request: get ETag
  16849. auto res1 = cli.Get("/static/if_range_testfile.txt");
  16850. ASSERT_TRUE(res1);
  16851. ASSERT_EQ(200, res1->status);
  16852. ASSERT_TRUE(res1->has_header("ETag"));
  16853. std::string etag = res1->get_header_value("ETag");
  16854. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  16855. // Since our server generates weak ETags (W/"..."), If-Range with our
  16856. // ETag should NOT result in partial content - it should return full content.
  16857. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  16858. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  16859. ASSERT_TRUE(res2);
  16860. // Weak ETag in If-Range -> full content (200), not partial (206)
  16861. EXPECT_EQ(200, res2->status);
  16862. EXPECT_EQ(content, res2->body);
  16863. EXPECT_FALSE(res2->has_header("Content-Range"));
  16864. // Range request with non-matching If-Range (ETag): should get 200 (full
  16865. // content)
  16866. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  16867. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  16868. ASSERT_TRUE(res3);
  16869. EXPECT_EQ(200, res3->status);
  16870. EXPECT_EQ(content, res3->body);
  16871. EXPECT_FALSE(res3->has_header("Content-Range"));
  16872. // Range request with strong ETag (hypothetical - our server doesn't generate
  16873. // strong ETags, but if client sends a strong ETag that doesn't match, it
  16874. // should return full content)
  16875. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  16876. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  16877. ASSERT_TRUE(res4);
  16878. EXPECT_EQ(200, res4->status);
  16879. EXPECT_EQ(content, res4->body);
  16880. EXPECT_FALSE(res4->has_header("Content-Range"));
  16881. svr.stop();
  16882. t.join();
  16883. std::remove(fname);
  16884. }
  16885. TEST(ETagTest, IfRangeWithDate) {
  16886. using namespace httplib;
  16887. // Create a test file
  16888. const char *fname = "if_range_date_testfile.txt";
  16889. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  16890. {
  16891. std::ofstream ofs(fname);
  16892. ofs << content;
  16893. ASSERT_TRUE(ofs.good());
  16894. }
  16895. Server svr;
  16896. svr.set_mount_point("/static", ".");
  16897. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16898. svr.wait_until_ready();
  16899. Client cli(HOST, PORT);
  16900. // First request: get Last-Modified
  16901. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  16902. ASSERT_TRUE(res1);
  16903. ASSERT_EQ(200, res1->status);
  16904. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16905. std::string last_modified = res1->get_header_value("Last-Modified");
  16906. // Range request with matching If-Range (date): should get 206
  16907. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  16908. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  16909. ASSERT_TRUE(res2);
  16910. EXPECT_EQ(206, res2->status);
  16911. EXPECT_EQ("FGHIJ", res2->body);
  16912. // Range request with old If-Range date: should get 200 (full content)
  16913. Headers h3 = {{"Range", "bytes=5-9"},
  16914. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16915. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  16916. ASSERT_TRUE(res3);
  16917. EXPECT_EQ(200, res3->status);
  16918. EXPECT_EQ(content, res3->body);
  16919. // Range request with future If-Range date: should get 206
  16920. Headers h4 = {{"Range", "bytes=0-4"},
  16921. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16922. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  16923. ASSERT_TRUE(res4);
  16924. EXPECT_EQ(206, res4->status);
  16925. EXPECT_EQ("ABCDE", res4->body);
  16926. svr.stop();
  16927. t.join();
  16928. std::remove(fname);
  16929. }
  16930. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  16931. using namespace httplib;
  16932. const char *fname = "etag_malformed.txt";
  16933. const char *content = "malformed-etag";
  16934. {
  16935. std::ofstream ofs(fname);
  16936. ofs << content;
  16937. ASSERT_TRUE(ofs.good());
  16938. }
  16939. Server svr;
  16940. svr.set_mount_point("/static", ".");
  16941. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16942. svr.wait_until_ready();
  16943. Client cli(HOST, PORT);
  16944. // baseline: should get 200 and an ETag
  16945. auto res1 = cli.Get("/static/etag_malformed.txt");
  16946. ASSERT_TRUE(res1);
  16947. ASSERT_EQ(200, res1->status);
  16948. ASSERT_TRUE(res1->has_header("ETag"));
  16949. // Malformed ETag value (missing quotes) should be treated as non-matching
  16950. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  16951. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  16952. ASSERT_TRUE(res_bad);
  16953. EXPECT_EQ(200, res_bad->status);
  16954. // Whitespace-only header value should be considered invalid / non-matching
  16955. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  16956. "Host: localhost\r\n"
  16957. "If-None-Match: \r\n"
  16958. "Connection: close\r\n"
  16959. "\r\n";
  16960. std::string out;
  16961. ASSERT_TRUE(send_request(5, raw_req, &out));
  16962. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16963. svr.stop();
  16964. t.join();
  16965. std::remove(fname);
  16966. }
  16967. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  16968. using namespace httplib;
  16969. const char *fname = "ims_invalid_format.txt";
  16970. const char *content = "ims-bad-format";
  16971. {
  16972. std::ofstream ofs(fname);
  16973. ofs << content;
  16974. ASSERT_TRUE(ofs.good());
  16975. }
  16976. Server svr;
  16977. svr.set_mount_point("/static", ".");
  16978. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16979. svr.wait_until_ready();
  16980. Client cli(HOST, PORT);
  16981. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  16982. ASSERT_TRUE(res1);
  16983. ASSERT_EQ(200, res1->status);
  16984. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16985. // If-Modified-Since with invalid format should not result in 304
  16986. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  16987. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  16988. ASSERT_TRUE(res_bad);
  16989. EXPECT_EQ(200, res_bad->status);
  16990. // If-Range with invalid date format should be treated as mismatch -> full
  16991. // content (200)
  16992. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  16993. {"If-Range", "invalid-date"}};
  16994. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  16995. ASSERT_TRUE(res_ifrange);
  16996. EXPECT_EQ(200, res_ifrange->status);
  16997. svr.stop();
  16998. t.join();
  16999. std::remove(fname);
  17000. }
  17001. TEST(ETagTest, IfRangeWithMalformedETag) {
  17002. using namespace httplib;
  17003. const char *fname = "ifrange_malformed.txt";
  17004. const std::string content = "0123456789";
  17005. {
  17006. std::ofstream ofs(fname);
  17007. ofs << content;
  17008. ASSERT_TRUE(ofs.good());
  17009. }
  17010. Server svr;
  17011. svr.set_mount_point("/static", ".");
  17012. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17013. svr.wait_until_ready();
  17014. Client cli(HOST, PORT);
  17015. // First request: get ETag
  17016. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  17017. ASSERT_TRUE(res1);
  17018. ASSERT_EQ(200, res1->status);
  17019. ASSERT_TRUE(res1->has_header("ETag"));
  17020. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  17021. // full content (200)
  17022. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  17023. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  17024. ASSERT_TRUE(res2);
  17025. EXPECT_EQ(200, res2->status);
  17026. EXPECT_EQ(content, res2->body);
  17027. svr.stop();
  17028. t.join();
  17029. std::remove(fname);
  17030. }
  17031. TEST(ETagTest, ExtremeLargeDateValues) {
  17032. using namespace httplib;
  17033. const char *fname = "ims_extreme_date.txt";
  17034. const char *content = "ims-extreme-date";
  17035. {
  17036. std::ofstream ofs(fname);
  17037. ofs << content;
  17038. ASSERT_TRUE(ofs.good());
  17039. }
  17040. Server svr;
  17041. svr.set_mount_point("/static", ".");
  17042. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17043. svr.wait_until_ready();
  17044. Client cli(HOST, PORT);
  17045. auto res1 = cli.Get(std::string("/static/") + fname);
  17046. ASSERT_TRUE(res1);
  17047. ASSERT_EQ(200, res1->status);
  17048. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17049. // Extremely large year that may overflow date parsing routines.
  17050. Headers h_large_date = {
  17051. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17052. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  17053. ASSERT_TRUE(res_bad);
  17054. // Expect server to treat this as invalid/mismatch and return full content
  17055. EXPECT_EQ(200, res_bad->status);
  17056. // If-Range with extremely large date should be treated as mismatch -> full
  17057. // content (200)
  17058. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  17059. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17060. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  17061. ASSERT_TRUE(res_ifrange);
  17062. EXPECT_EQ(200, res_ifrange->status);
  17063. svr.stop();
  17064. t.join();
  17065. std::remove(fname);
  17066. }
  17067. TEST(ETagTest, NegativeFileModificationTime) {
  17068. using namespace httplib;
  17069. const char *fname = "ims_negative_mtime.txt";
  17070. const std::string content = "negative-mtime";
  17071. {
  17072. std::ofstream ofs(fname);
  17073. ofs << content;
  17074. ASSERT_TRUE(ofs.good());
  17075. }
  17076. // Try to set file mtime to a negative value. This may fail on some
  17077. // platforms/filesystems; if it fails, the test will still verify server
  17078. // behaves safely by performing a regular conditional request.
  17079. #if defined(__APPLE__) || defined(__linux__)
  17080. bool set_negative = false;
  17081. do {
  17082. struct timeval times[2];
  17083. // access time: now
  17084. times[0].tv_sec = time(nullptr);
  17085. times[0].tv_usec = 0;
  17086. // modification time: negative (e.g., -1)
  17087. times[1].tv_sec = -1;
  17088. times[1].tv_usec = 0;
  17089. if (utimes(fname, times) == 0) { set_negative = true; }
  17090. } while (0);
  17091. #else
  17092. bool set_negative = false;
  17093. #endif
  17094. Server svr;
  17095. svr.set_mount_point("/static", ".");
  17096. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17097. svr.wait_until_ready();
  17098. Client cli(HOST, PORT);
  17099. auto res1 = cli.Get(std::string("/static/") + fname);
  17100. ASSERT_TRUE(res1);
  17101. ASSERT_EQ(200, res1->status);
  17102. bool has_last_modified = res1->has_header("Last-Modified");
  17103. std::string last_modified;
  17104. if (has_last_modified) {
  17105. last_modified = res1->get_header_value("Last-Modified");
  17106. }
  17107. if (set_negative) {
  17108. // If we successfully set a negative mtime, ensure server returns a
  17109. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  17110. // with an old date and ensure server handles it without crash.
  17111. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  17112. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  17113. ASSERT_TRUE(res2);
  17114. // Behavior may vary; at minimum ensure server responds (200 or 304).
  17115. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  17116. } else {
  17117. // Could not set negative mtime on this platform; fall back to verifying
  17118. // that normal invalid/malformed dates are treated safely (non-304).
  17119. Headers h_bad_date = {
  17120. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17121. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  17122. ASSERT_TRUE(res_bad);
  17123. EXPECT_EQ(200, res_bad->status);
  17124. }
  17125. svr.stop();
  17126. t.join();
  17127. std::remove(fname);
  17128. }
  17129. //==============================================================================
  17130. // SSE Parsing Tests
  17131. //==============================================================================
  17132. class SSEParsingTest : public ::testing::Test {
  17133. protected:
  17134. // Test helper that mimics SSE parsing behavior
  17135. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  17136. int &retry_ms) {
  17137. // Blank line signals end of event
  17138. if (line.empty() || line == "\r") { return true; }
  17139. // Lines starting with ':' are comments (ignored)
  17140. if (!line.empty() && line[0] == ':') { return false; }
  17141. // Find the colon separator
  17142. auto colon_pos = line.find(':');
  17143. if (colon_pos == std::string::npos) {
  17144. // Line with no colon is treated as field name with empty value
  17145. return false;
  17146. }
  17147. std::string field = line.substr(0, colon_pos);
  17148. std::string value;
  17149. // Value starts after colon, skip optional single space
  17150. if (colon_pos + 1 < line.size()) {
  17151. size_t value_start = colon_pos + 1;
  17152. if (line[value_start] == ' ') { value_start++; }
  17153. value = line.substr(value_start);
  17154. // Remove trailing \r if present
  17155. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  17156. }
  17157. // Handle known fields
  17158. if (field == "event") {
  17159. msg.event = value;
  17160. } else if (field == "data") {
  17161. // Multiple data lines are concatenated with newlines
  17162. if (!msg.data.empty()) { msg.data += "\n"; }
  17163. msg.data += value;
  17164. } else if (field == "id") {
  17165. // Empty id is valid (clears the last event ID)
  17166. msg.id = value;
  17167. } else if (field == "retry") {
  17168. // Parse retry interval in milliseconds
  17169. {
  17170. int v = 0;
  17171. auto res =
  17172. detail::from_chars(value.data(), value.data() + value.size(), v);
  17173. if (res.ec == std::errc{}) { retry_ms = v; }
  17174. }
  17175. }
  17176. // Unknown fields are ignored per SSE spec
  17177. return false;
  17178. }
  17179. };
  17180. // Test: Single-line data
  17181. TEST_F(SSEParsingTest, SingleLineData) {
  17182. sse::SSEMessage msg;
  17183. int retry_ms = 3000;
  17184. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  17185. EXPECT_EQ(msg.data, "hello");
  17186. EXPECT_EQ(msg.event, "message");
  17187. // Blank line ends event
  17188. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17189. }
  17190. // Test: Multi-line data
  17191. TEST_F(SSEParsingTest, MultiLineData) {
  17192. sse::SSEMessage msg;
  17193. int retry_ms = 3000;
  17194. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  17195. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  17196. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  17197. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  17198. }
  17199. // Test: Custom event types
  17200. TEST_F(SSEParsingTest, CustomEventType) {
  17201. sse::SSEMessage msg;
  17202. int retry_ms = 3000;
  17203. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  17204. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  17205. EXPECT_EQ(msg.event, "update");
  17206. EXPECT_EQ(msg.data, "payload");
  17207. }
  17208. // Test: Event ID handling
  17209. TEST_F(SSEParsingTest, EventIdHandling) {
  17210. sse::SSEMessage msg;
  17211. int retry_ms = 3000;
  17212. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  17213. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  17214. EXPECT_EQ(msg.id, "12345");
  17215. }
  17216. // Test: Empty event ID (clears last event ID)
  17217. TEST_F(SSEParsingTest, EmptyEventId) {
  17218. sse::SSEMessage msg;
  17219. msg.id = "previous";
  17220. int retry_ms = 3000;
  17221. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  17222. EXPECT_EQ(msg.id, "");
  17223. }
  17224. // Test: Retry field parsing
  17225. TEST_F(SSEParsingTest, RetryFieldParsing) {
  17226. sse::SSEMessage msg;
  17227. int retry_ms = 3000;
  17228. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  17229. EXPECT_EQ(retry_ms, 5000);
  17230. }
  17231. // Test: Invalid retry value
  17232. TEST_F(SSEParsingTest, InvalidRetryValue) {
  17233. sse::SSEMessage msg;
  17234. int retry_ms = 3000;
  17235. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  17236. EXPECT_EQ(retry_ms, 3000); // Unchanged
  17237. }
  17238. // Test: Comments (lines starting with :)
  17239. TEST_F(SSEParsingTest, CommentsIgnored) {
  17240. sse::SSEMessage msg;
  17241. int retry_ms = 3000;
  17242. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  17243. EXPECT_EQ(msg.data, "");
  17244. EXPECT_EQ(msg.event, "message");
  17245. }
  17246. // Test: Colon in value
  17247. TEST_F(SSEParsingTest, ColonInValue) {
  17248. sse::SSEMessage msg;
  17249. int retry_ms = 3000;
  17250. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  17251. EXPECT_EQ(msg.data, "hello:world:test");
  17252. }
  17253. // Test: Line with no colon (field name only)
  17254. TEST_F(SSEParsingTest, FieldNameOnly) {
  17255. sse::SSEMessage msg;
  17256. int retry_ms = 3000;
  17257. // According to SSE spec, this is treated as field name with empty value
  17258. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  17259. // Since we don't recognize "data" without colon, data should be empty
  17260. EXPECT_EQ(msg.data, "");
  17261. }
  17262. // Test: Trailing \r handling
  17263. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  17264. sse::SSEMessage msg;
  17265. int retry_ms = 3000;
  17266. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  17267. EXPECT_EQ(msg.data, "hello");
  17268. }
  17269. // Test: Unknown fields ignored
  17270. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  17271. sse::SSEMessage msg;
  17272. int retry_ms = 3000;
  17273. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  17274. EXPECT_EQ(msg.data, "");
  17275. EXPECT_EQ(msg.event, "message");
  17276. }
  17277. // Test: Space after colon is optional
  17278. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  17279. sse::SSEMessage msg1, msg2;
  17280. int retry_ms = 3000;
  17281. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  17282. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  17283. EXPECT_EQ(msg1.data, "hello");
  17284. EXPECT_EQ(msg2.data, "hello");
  17285. }
  17286. // Test: SSEMessage clear
  17287. TEST_F(SSEParsingTest, MessageClear) {
  17288. sse::SSEMessage msg;
  17289. msg.event = "custom";
  17290. msg.data = "some data";
  17291. msg.id = "123";
  17292. msg.clear();
  17293. EXPECT_EQ(msg.event, "message");
  17294. EXPECT_EQ(msg.data, "");
  17295. EXPECT_EQ(msg.id, "");
  17296. }
  17297. // Test: Complete event parsing
  17298. TEST_F(SSEParsingTest, CompleteEventParsing) {
  17299. sse::SSEMessage msg;
  17300. int retry_ms = 3000;
  17301. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  17302. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  17303. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  17304. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  17305. // Blank line ends event
  17306. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17307. EXPECT_EQ(msg.event, "notification");
  17308. EXPECT_EQ(msg.id, "evt-42");
  17309. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  17310. EXPECT_EQ(retry_ms, 1000);
  17311. }
  17312. //==============================================================================
  17313. // Integration Tests with Server
  17314. //==============================================================================
  17315. class SSEIntegrationTest : public ::testing::Test {
  17316. protected:
  17317. void SetUp() override {
  17318. stop_server_.store(false);
  17319. events_.clear();
  17320. server_ = httplib::detail::make_unique<Server>();
  17321. setup_server();
  17322. start_server();
  17323. }
  17324. void TearDown() override {
  17325. stop_server_.store(true);
  17326. event_cv_.notify_all();
  17327. server_->stop();
  17328. if (server_thread_.joinable()) { server_thread_.join(); }
  17329. }
  17330. void setup_server() {
  17331. // Simple SSE endpoint
  17332. server_->Get("/events", [this](const Request &req, Response &res) {
  17333. auto last_id = req.get_header_value("Last-Event-ID");
  17334. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  17335. res.set_chunked_content_provider(
  17336. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  17337. std::unique_lock<std::mutex> lock(event_mutex_);
  17338. if (event_cv_.wait_for(
  17339. lock, std::chrono::milliseconds(200), [this] {
  17340. return !events_.empty() || stop_server_.load();
  17341. })) {
  17342. if (stop_server_.load()) { return false; }
  17343. if (!events_.empty()) {
  17344. std::string event = events_.front();
  17345. events_.erase(events_.begin());
  17346. sink.write(event.data(), event.size());
  17347. return true;
  17348. }
  17349. }
  17350. return !stop_server_.load();
  17351. });
  17352. });
  17353. // Endpoint that returns error
  17354. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  17355. res.status = 500;
  17356. res.set_content("Internal Server Error", "text/plain");
  17357. });
  17358. // Endpoint for custom event types
  17359. server_->Get("/custom-events", [](const Request &, Response &res) {
  17360. res.set_chunked_content_provider(
  17361. "text/event-stream", [](size_t offset, DataSink &sink) {
  17362. if (offset == 0) {
  17363. std::string event = "event: update\ndata: updated\n\n"
  17364. "event: delete\ndata: deleted\n\n";
  17365. sink.write(event.data(), event.size());
  17366. }
  17367. return false; // End stream after sending
  17368. });
  17369. });
  17370. }
  17371. void start_server() {
  17372. port_ = server_->bind_to_any_port(HOST);
  17373. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17374. // Wait for server to start
  17375. while (!server_->is_running()) {
  17376. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17377. }
  17378. }
  17379. int get_port() const { return port_; }
  17380. void send_event(const std::string &event) {
  17381. std::lock_guard<std::mutex> lock(event_mutex_);
  17382. events_.push_back(event);
  17383. event_cv_.notify_all();
  17384. }
  17385. std::unique_ptr<Server> server_;
  17386. std::thread server_thread_;
  17387. std::mutex event_mutex_;
  17388. std::condition_variable event_cv_;
  17389. std::vector<std::string> events_;
  17390. std::atomic<bool> stop_server_{false};
  17391. std::string last_received_event_id_;
  17392. int port_ = 0;
  17393. };
  17394. // Test: Successful connection and on_open callback
  17395. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  17396. // Add a simple endpoint that sends one event and closes
  17397. server_->Get("/simple-event", [](const Request &, Response &res) {
  17398. res.set_chunked_content_provider(
  17399. "text/event-stream", [](size_t offset, DataSink &sink) {
  17400. if (offset == 0) {
  17401. std::string event = "data: hello\n\n";
  17402. sink.write(event.data(), event.size());
  17403. }
  17404. return false; // Close stream after sending
  17405. });
  17406. });
  17407. Client client("localhost", get_port());
  17408. sse::SSEClient sse(client, "/simple-event");
  17409. std::atomic<bool> open_called{false};
  17410. std::atomic<bool> message_received{false};
  17411. sse.on_open([&open_called]() { open_called.store(true); });
  17412. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  17413. if (msg.data == "hello") { message_received.store(true); }
  17414. });
  17415. sse.set_reconnect_interval(100);
  17416. sse.set_max_reconnect_attempts(1);
  17417. // Start async
  17418. sse.start_async();
  17419. // Wait for message to be processed
  17420. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17421. sse.stop();
  17422. EXPECT_TRUE(open_called.load());
  17423. EXPECT_TRUE(message_received.load());
  17424. }
  17425. // Test: on_message callback
  17426. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  17427. // Endpoint that sends multiple events then closes
  17428. server_->Get("/multi-event", [](const Request &, Response &res) {
  17429. res.set_chunked_content_provider(
  17430. "text/event-stream", [](size_t offset, DataSink &sink) {
  17431. if (offset == 0) {
  17432. std::string events = "data: message1\n\ndata: message2\n\n";
  17433. sink.write(events.data(), events.size());
  17434. }
  17435. return false;
  17436. });
  17437. });
  17438. Client client("localhost", get_port());
  17439. sse::SSEClient sse(client, "/multi-event");
  17440. std::vector<std::string> received_messages;
  17441. std::mutex messages_mutex;
  17442. sse.on_message([&](const sse::SSEMessage &msg) {
  17443. std::lock_guard<std::mutex> lock(messages_mutex);
  17444. received_messages.push_back(msg.data);
  17445. });
  17446. sse.set_reconnect_interval(100);
  17447. sse.set_max_reconnect_attempts(1);
  17448. sse.start_async();
  17449. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17450. sse.stop();
  17451. std::lock_guard<std::mutex> lock(messages_mutex);
  17452. EXPECT_GE(received_messages.size(), 2u);
  17453. if (received_messages.size() >= 2) {
  17454. EXPECT_EQ(received_messages[0], "message1");
  17455. EXPECT_EQ(received_messages[1], "message2");
  17456. }
  17457. }
  17458. // Test: on_event for specific types
  17459. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  17460. Client client("localhost", get_port());
  17461. sse::SSEClient sse(client, "/custom-events");
  17462. std::atomic<bool> update_received{false};
  17463. std::atomic<bool> delete_received{false};
  17464. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  17465. if (msg.data == "updated") { update_received.store(true); }
  17466. });
  17467. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  17468. if (msg.data == "deleted") { delete_received.store(true); }
  17469. });
  17470. sse.set_max_reconnect_attempts(1);
  17471. sse.start_async();
  17472. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  17473. sse.stop();
  17474. EXPECT_TRUE(update_received.load());
  17475. EXPECT_TRUE(delete_received.load());
  17476. }
  17477. // Test: on_error callback on connection failure
  17478. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  17479. // Connect to a non-existent port
  17480. Client client("localhost", 59999);
  17481. sse::SSEClient sse(client, "/events");
  17482. std::atomic<bool> error_called{false};
  17483. Error received_error = Error::Success;
  17484. sse.on_error([&](Error err) {
  17485. error_called.store(true);
  17486. received_error = err;
  17487. });
  17488. sse.set_reconnect_interval(50);
  17489. sse.set_max_reconnect_attempts(1);
  17490. sse.start_async();
  17491. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17492. sse.stop();
  17493. EXPECT_TRUE(error_called.load());
  17494. EXPECT_NE(received_error, Error::Success);
  17495. }
  17496. // Test: Last-Event-ID header sent on reconnect
  17497. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  17498. // Endpoint that sends event with ID
  17499. server_->Get("/event-with-id", [](const Request &, Response &res) {
  17500. res.set_chunked_content_provider(
  17501. "text/event-stream", [](size_t offset, DataSink &sink) {
  17502. if (offset == 0) {
  17503. std::string event = "id: evt-123\ndata: test\n\n";
  17504. sink.write(event.data(), event.size());
  17505. }
  17506. return false;
  17507. });
  17508. });
  17509. Client client("localhost", get_port());
  17510. sse::SSEClient sse(client, "/event-with-id");
  17511. std::atomic<bool> id_received{false};
  17512. sse.on_message([&](const sse::SSEMessage &msg) {
  17513. if (!msg.id.empty()) { id_received.store(true); }
  17514. });
  17515. sse.set_reconnect_interval(100);
  17516. sse.set_max_reconnect_attempts(1);
  17517. sse.start_async();
  17518. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17519. sse.stop();
  17520. EXPECT_TRUE(id_received.load());
  17521. EXPECT_EQ(sse.last_event_id(), "evt-123");
  17522. }
  17523. // Test: Manual stop
  17524. TEST_F(SSEIntegrationTest, ManualStop) {
  17525. // Endpoint that sends one event and stays open briefly
  17526. std::atomic<bool> handler_running{true};
  17527. server_->Get("/stay-open", [&handler_running](const Request &,
  17528. Response &res) {
  17529. res.set_chunked_content_provider(
  17530. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  17531. if (offset == 0) {
  17532. std::string event = "data: connected\n\n";
  17533. sink.write(event.data(), event.size());
  17534. }
  17535. // Keep connection open while handler_running is true
  17536. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  17537. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17538. }
  17539. return false;
  17540. });
  17541. });
  17542. Client client("localhost", get_port());
  17543. sse::SSEClient sse(client, "/stay-open");
  17544. std::atomic<bool> connected{false};
  17545. sse.on_open([&connected]() { connected.store(true); });
  17546. sse.set_reconnect_interval(100);
  17547. sse.set_max_reconnect_attempts(1);
  17548. sse.start_async();
  17549. // Wait for connection to establish
  17550. for (int i = 0; i < 20 && !connected.load(); ++i) {
  17551. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  17552. }
  17553. EXPECT_TRUE(connected.load());
  17554. EXPECT_TRUE(sse.is_connected());
  17555. // Signal handler to stop
  17556. handler_running.store(false);
  17557. // Stop SSE client
  17558. sse.stop();
  17559. EXPECT_FALSE(sse.is_connected());
  17560. }
  17561. // Test: SSEClient with custom headers
  17562. TEST_F(SSEIntegrationTest, CustomHeaders) {
  17563. // Setup a server endpoint that checks for custom header
  17564. std::atomic<bool> header_received{false};
  17565. server_->Get("/header-check", [&](const Request &req, Response &res) {
  17566. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  17567. header_received.store(true);
  17568. }
  17569. res.set_chunked_content_provider("text/event-stream",
  17570. [](size_t, DataSink &) { return false; });
  17571. });
  17572. Client client("localhost", get_port());
  17573. Headers headers = {{"X-Custom-Header", "custom-value"}};
  17574. sse::SSEClient sse(client, "/header-check", headers);
  17575. sse.set_max_reconnect_attempts(1);
  17576. sse.start_async();
  17577. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17578. sse.stop();
  17579. EXPECT_TRUE(header_received.load());
  17580. }
  17581. // Test: Reconnect interval configuration
  17582. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  17583. Client client("localhost", get_port());
  17584. sse::SSEClient sse(client, "/events");
  17585. auto &result = sse.set_reconnect_interval(500);
  17586. // Builder pattern should return reference to self
  17587. EXPECT_EQ(&result, &sse);
  17588. }
  17589. // Test: Max reconnect attempts
  17590. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  17591. // Connect to non-existent port to force reconnects
  17592. Client client("localhost", 59998);
  17593. sse::SSEClient sse(client, "/events");
  17594. std::atomic<int> error_count{0};
  17595. sse.on_error([&](Error) { error_count.fetch_add(1); });
  17596. sse.set_reconnect_interval(50);
  17597. sse.set_max_reconnect_attempts(2);
  17598. auto start = std::chrono::steady_clock::now();
  17599. sse.start(); // Blocking call
  17600. auto end = std::chrono::steady_clock::now();
  17601. // Should have stopped after 2 failed attempts
  17602. EXPECT_GE(error_count.load(), 2);
  17603. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  17604. auto duration =
  17605. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  17606. #ifdef _WIN32
  17607. // Windows is much slower for socket connection failures
  17608. EXPECT_LT(duration.count(), 7000);
  17609. #else
  17610. EXPECT_LT(duration.count(), 1000);
  17611. #endif
  17612. }
  17613. // Test: Multi-line data in integration
  17614. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  17615. // Endpoint with multi-line data
  17616. server_->Get("/multiline-data", [](const Request &, Response &res) {
  17617. res.set_chunked_content_provider(
  17618. "text/event-stream", [](size_t offset, DataSink &sink) {
  17619. if (offset == 0) {
  17620. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  17621. sink.write(event.data(), event.size());
  17622. }
  17623. return false;
  17624. });
  17625. });
  17626. Client client("localhost", get_port());
  17627. sse::SSEClient sse(client, "/multiline-data");
  17628. std::string received_data;
  17629. std::mutex data_mutex;
  17630. sse.on_message([&](const sse::SSEMessage &msg) {
  17631. std::lock_guard<std::mutex> lock(data_mutex);
  17632. received_data = msg.data;
  17633. });
  17634. sse.set_reconnect_interval(100);
  17635. sse.set_max_reconnect_attempts(1);
  17636. sse.start_async();
  17637. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17638. sse.stop();
  17639. std::lock_guard<std::mutex> lock(data_mutex);
  17640. EXPECT_EQ(received_data, "line1\nline2\nline3");
  17641. }
  17642. // Test: Auto-reconnect after server disconnection
  17643. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  17644. std::atomic<int> connection_count{0};
  17645. std::atomic<int> message_count{0};
  17646. // Endpoint that sends one event and closes, forcing reconnect
  17647. server_->Get("/reconnect-test",
  17648. [&connection_count](const Request &, Response &res) {
  17649. connection_count.fetch_add(1);
  17650. res.set_chunked_content_provider(
  17651. "text/event-stream", [](size_t offset, DataSink &sink) {
  17652. if (offset == 0) {
  17653. std::string event = "data: hello\n\n";
  17654. sink.write(event.data(), event.size());
  17655. }
  17656. return false; // Close connection after sending
  17657. });
  17658. });
  17659. Client client("localhost", get_port());
  17660. sse::SSEClient sse(client, "/reconnect-test");
  17661. sse.on_message([&message_count](const sse::SSEMessage &) {
  17662. message_count.fetch_add(1);
  17663. });
  17664. sse.set_reconnect_interval(100);
  17665. sse.set_max_reconnect_attempts(3);
  17666. sse.start_async();
  17667. // Wait long enough for multiple reconnects
  17668. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17669. sse.stop();
  17670. // Should have connected multiple times (initial + reconnects)
  17671. EXPECT_GE(connection_count.load(), 2);
  17672. // Should have received messages from multiple connections
  17673. EXPECT_GE(message_count.load(), 2);
  17674. }
  17675. // Test: Last-Event-ID sent on reconnect
  17676. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  17677. std::atomic<int> connection_count{0};
  17678. std::vector<std::string> received_last_event_ids;
  17679. std::mutex id_mutex;
  17680. // Endpoint that checks Last-Event-ID header and sends event with ID
  17681. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  17682. int conn = connection_count.fetch_add(1);
  17683. // Capture the Last-Event-ID header from each connection
  17684. {
  17685. std::lock_guard<std::mutex> lock(id_mutex);
  17686. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  17687. }
  17688. res.set_chunked_content_provider(
  17689. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  17690. if (offset == 0) {
  17691. std::string event =
  17692. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  17693. sink.write(event.data(), event.size());
  17694. }
  17695. return false;
  17696. });
  17697. });
  17698. Client client("localhost", get_port());
  17699. sse::SSEClient sse(client, "/reconnect-with-id");
  17700. sse.set_reconnect_interval(100);
  17701. sse.set_max_reconnect_attempts(3);
  17702. sse.start_async();
  17703. // Wait for at least 2 connections
  17704. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  17705. sse.stop();
  17706. // Verify behavior
  17707. std::lock_guard<std::mutex> lock(id_mutex);
  17708. EXPECT_GE(received_last_event_ids.size(), 2u);
  17709. // First connection should have no Last-Event-ID
  17710. if (!received_last_event_ids.empty()) {
  17711. EXPECT_EQ(received_last_event_ids[0], "");
  17712. }
  17713. // Second connection should have Last-Event-ID from first connection
  17714. if (received_last_event_ids.size() >= 2) {
  17715. EXPECT_EQ(received_last_event_ids[1], "event-0");
  17716. }
  17717. }
  17718. // Test: set_headers updates headers used on reconnect
  17719. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  17720. std::vector<std::string> received_tokens;
  17721. std::mutex token_mutex;
  17722. // Endpoint that captures Authorization header
  17723. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  17724. {
  17725. std::lock_guard<std::mutex> lock(token_mutex);
  17726. received_tokens.push_back(req.get_header_value("Authorization"));
  17727. }
  17728. res.set_chunked_content_provider(
  17729. "text/event-stream", [](size_t offset, DataSink &sink) {
  17730. if (offset == 0) {
  17731. std::string event = "data: hello\n\n";
  17732. sink.write(event.data(), event.size());
  17733. }
  17734. return false; // Close connection to trigger reconnect
  17735. });
  17736. });
  17737. Client client("localhost", get_port());
  17738. Headers headers = {{"Authorization", "Bearer old-token"}};
  17739. sse::SSEClient sse(client, "/auth-check", headers);
  17740. // Update headers on each successful connection
  17741. sse.on_open(
  17742. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  17743. sse.set_reconnect_interval(100);
  17744. sse.set_max_reconnect_attempts(3);
  17745. sse.start_async();
  17746. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17747. sse.stop();
  17748. std::lock_guard<std::mutex> lock(token_mutex);
  17749. ASSERT_GE(received_tokens.size(), 2u);
  17750. // First connection uses original header
  17751. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  17752. // Second connection uses updated header from set_headers
  17753. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  17754. }
  17755. // Test: 401 allows reconnection (so on_error can refresh headers)
  17756. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  17757. std::atomic<int> connection_count{0};
  17758. // Endpoint: returns 401 on first attempt, 200 on second
  17759. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  17760. int conn = connection_count.fetch_add(1);
  17761. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  17762. res.status = StatusCode::Unauthorized_401;
  17763. res.set_content("Unauthorized", "text/plain");
  17764. return;
  17765. }
  17766. res.set_chunked_content_provider(
  17767. "text/event-stream", [](size_t offset, DataSink &sink) {
  17768. if (offset == 0) {
  17769. std::string event = "data: authenticated\n\n";
  17770. sink.write(event.data(), event.size());
  17771. }
  17772. return false;
  17773. });
  17774. });
  17775. Client client("localhost", get_port());
  17776. Headers headers = {{"Authorization", "Bearer expired"}};
  17777. sse::SSEClient sse(client, "/auth-retry", headers);
  17778. std::atomic<bool> message_received{false};
  17779. // Refresh token on error
  17780. sse.on_error(
  17781. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  17782. sse.on_message([&](const sse::SSEMessage &msg) {
  17783. if (msg.data == "authenticated") { message_received.store(true); }
  17784. });
  17785. sse.set_reconnect_interval(100);
  17786. sse.set_max_reconnect_attempts(3);
  17787. sse.start_async();
  17788. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  17789. sse.stop();
  17790. // Should have reconnected after 401 and succeeded with new token
  17791. EXPECT_GE(connection_count.load(), 2);
  17792. EXPECT_TRUE(message_received.load());
  17793. }
  17794. TEST(Issue2318Test, EmptyHostString) {
  17795. {
  17796. httplib::Client cli_empty("", PORT);
  17797. auto res = cli_empty.Get("/");
  17798. ASSERT_FALSE(res);
  17799. EXPECT_EQ(httplib::Error::Connection, res.error());
  17800. }
  17801. {
  17802. httplib::Client cli(" ", PORT);
  17803. auto res = cli.Get("/");
  17804. ASSERT_FALSE(res);
  17805. EXPECT_EQ(httplib::Error::Connection, res.error());
  17806. }
  17807. }
  17808. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17809. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  17810. Server svr;
  17811. // Set a small payload limit (1KB)
  17812. svr.set_payload_max_length(1024);
  17813. svr.Post("/test", [&](const Request &req, Response &res) {
  17814. res.set_content("Body size: " + std::to_string(req.body.size()),
  17815. "text/plain");
  17816. });
  17817. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17818. auto se = detail::scope_exit([&] {
  17819. svr.stop();
  17820. listen_thread.join();
  17821. });
  17822. svr.wait_until_ready();
  17823. // Create data that compresses well but exceeds limit when decompressed
  17824. // 8KB of repeated null bytes compresses to a very small size
  17825. std::string original_data(8 * 1024, '\0');
  17826. // Compress the data using gzip
  17827. std::string compressed_data;
  17828. detail::gzip_compressor compressor;
  17829. compressor.compress(original_data.data(), original_data.size(), true,
  17830. [&](const char *data, size_t size) {
  17831. compressed_data.append(data, size);
  17832. return true;
  17833. });
  17834. // Verify compression worked (compressed should be much smaller)
  17835. ASSERT_LT(compressed_data.size(), original_data.size());
  17836. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  17837. // Send compressed data with Content-Encoding: gzip
  17838. Client cli(HOST, PORT);
  17839. Headers headers = {{"Content-Encoding", "gzip"}};
  17840. auto res =
  17841. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  17842. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  17843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17844. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  17845. }
  17846. #endif
  17847. // ============================================================================
  17848. // OpenSSL-Specific Tests
  17849. // ============================================================================
  17850. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17851. X509 *readCertificate(const std::string &strFileName) {
  17852. std::ifstream inStream(strFileName);
  17853. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  17854. std::istreambuf_iterator<char>());
  17855. if (strCertPEM.empty()) return (nullptr);
  17856. BIO *pbCert = BIO_new(BIO_s_mem());
  17857. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  17858. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  17859. BIO_free(pbCert);
  17860. return (pCert);
  17861. }
  17862. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  17863. std::ifstream inStream(strFileName);
  17864. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  17865. std::istreambuf_iterator<char>());
  17866. if (strPrivateKeyPEM.empty()) return (nullptr);
  17867. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  17868. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  17869. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  17870. BIO_free(pbPrivKey);
  17871. return (pPrivateKey);
  17872. }
  17873. TEST(BindServerTest, UpdateCerts) {
  17874. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17875. int port = svr.bind_to_any_port("0.0.0.0");
  17876. ASSERT_TRUE(svr.is_valid());
  17877. ASSERT_TRUE(port > 0);
  17878. X509 *cert = readCertificate(SERVER_CERT_FILE);
  17879. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  17880. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  17881. ASSERT_TRUE(cert != nullptr);
  17882. ASSERT_TRUE(ca_cert != nullptr);
  17883. ASSERT_TRUE(key != nullptr);
  17884. X509_STORE *cert_store = X509_STORE_new();
  17885. X509_STORE_add_cert(cert_store, ca_cert);
  17886. // svr.update_certs(cert, key, cert_store); // deprecated
  17887. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  17888. CLIENT_CA_CERT_FILE);
  17889. ASSERT_TRUE(svr.is_valid());
  17890. svr.stop();
  17891. X509_STORE_free(cert_store);
  17892. X509_free(cert);
  17893. X509_free(ca_cert);
  17894. EVP_PKEY_free(key);
  17895. }
  17896. // Test that update_certs() updates client CA list correctly
  17897. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  17898. // Start with file-based constructor
  17899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17900. ASSERT_TRUE(svr.is_valid());
  17901. // Initially no client CA list should be set
  17902. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17903. ASSERT_TRUE(ssl_ctx != nullptr);
  17904. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  17905. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  17906. EXPECT_EQ(0, count_before);
  17907. // Now update with client CA (PEM string)
  17908. std::string cert_pem, key_pem, ca_pem;
  17909. read_file(SERVER_CERT_FILE, cert_pem);
  17910. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  17911. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  17912. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  17913. ASSERT_TRUE(svr.is_valid());
  17914. // Now client CA list should be set
  17915. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  17916. ASSERT_TRUE(ca_list_after != nullptr);
  17917. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  17918. }
  17919. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  17920. // Test that the file-path SSLServer constructor properly sets the client CA
  17921. // list that is sent to clients during the TLS handshake (CertificateRequest)
  17922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17923. ASSERT_TRUE(svr.is_valid());
  17924. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17925. ASSERT_TRUE(ssl_ctx != nullptr);
  17926. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  17927. ASSERT_TRUE(ca_list != nullptr);
  17928. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  17929. }
  17930. #endif
  17931. // ============================================================================
  17932. // MbedTLS-Specific Tests
  17933. // ============================================================================
  17934. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  17935. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  17936. using namespace httplib::tls;
  17937. // Track if callback was invoked
  17938. bool callback_invoked = false;
  17939. // The callback receives void* ctx which is actually MbedTlsContext*
  17940. // We can access the mbedtls_ssl_config via the context
  17941. auto setup_callback = [&callback_invoked](void *ctx) {
  17942. callback_invoked = true;
  17943. // Cast to MbedTlsContext* to access the ssl config
  17944. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  17945. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  17946. // Use static variables to hold certificate data (simplified for test)
  17947. static mbedtls_x509_crt own_cert;
  17948. static mbedtls_pk_context own_key;
  17949. static mbedtls_x509_crt ca_chain;
  17950. static bool initialized = false;
  17951. if (!initialized) {
  17952. mbedtls_x509_crt_init(&own_cert);
  17953. mbedtls_pk_init(&own_key);
  17954. mbedtls_x509_crt_init(&ca_chain);
  17955. // Load server certificate
  17956. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  17957. return false;
  17958. }
  17959. // Load server private key.
  17960. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  17961. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  17962. #if MBEDTLS_VERSION_MAJOR == 3
  17963. ,
  17964. mbedtls_ctr_drbg_random, nullptr
  17965. #endif
  17966. ) != 0) {
  17967. return false;
  17968. }
  17969. // Load CA chain for client verification
  17970. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  17971. return false;
  17972. }
  17973. initialized = true;
  17974. }
  17975. // Configure the SSL config
  17976. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  17977. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  17978. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17979. // Set minimum TLS version using mbedTLS native API
  17980. #if MBEDTLS_VERSION_MAJOR >= 3
  17981. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17982. #else
  17983. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17984. MBEDTLS_SSL_MINOR_VERSION_3);
  17985. #endif
  17986. return true;
  17987. };
  17988. SSLServer svr(setup_callback);
  17989. ASSERT_TRUE(svr.is_valid());
  17990. ASSERT_TRUE(callback_invoked);
  17991. svr.Get("/test", [&](const Request &req, Response &res) {
  17992. res.set_content("test", "text/plain");
  17993. auto cert = req.peer_cert();
  17994. ASSERT_TRUE(static_cast<bool>(cert));
  17995. auto common_name = cert.subject_cn();
  17996. EXPECT_EQ("Common Name", common_name);
  17997. });
  17998. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17999. auto se = detail::scope_exit([&] {
  18000. svr.stop();
  18001. t.join();
  18002. ASSERT_FALSE(svr.is_running());
  18003. });
  18004. svr.wait_until_ready();
  18005. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  18006. cli.enable_server_certificate_verification(false);
  18007. cli.set_connection_timeout(30);
  18008. auto res = cli.Get("/test");
  18009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18010. ASSERT_EQ(StatusCode::OK_200, res->status);
  18011. }
  18012. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  18013. // context (owning mbedtls_ssl_config) before shutting down a still-open
  18014. // keep-alive SSL session, which reads through that config in
  18015. // mbedtls_ssl_close_notify.
  18016. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  18017. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18018. ASSERT_TRUE(svr.is_valid());
  18019. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18020. res.set_content("test", "text/plain");
  18021. });
  18022. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18023. auto se = detail::scope_exit([&] {
  18024. svr.stop();
  18025. t.join();
  18026. ASSERT_FALSE(svr.is_running());
  18027. });
  18028. svr.wait_until_ready();
  18029. {
  18030. SSLClient cli(HOST, PORT);
  18031. cli.enable_server_certificate_verification(false);
  18032. cli.set_keep_alive(true);
  18033. auto res = cli.Get("/test");
  18034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18035. ASSERT_EQ(StatusCode::OK_200, res->status);
  18036. // cli is destructed here with the keep-alive SSL session still open.
  18037. }
  18038. }
  18039. #endif
  18040. // WebSocket Tests
  18041. TEST(WebSocketTest, RSVBitsMustBeZero) {
  18042. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  18043. // defining the meaning of these bits has been negotiated.
  18044. auto make_frame = [](uint8_t first_byte) {
  18045. std::string frame;
  18046. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  18047. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  18048. frame += "Hello";
  18049. return frame;
  18050. };
  18051. // RSV1 set (0x40)
  18052. {
  18053. detail::BufferStream strm;
  18054. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  18055. ws::Opcode opcode;
  18056. std::string payload;
  18057. bool fin;
  18058. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18059. false, 1024));
  18060. }
  18061. // RSV2 set (0x20)
  18062. {
  18063. detail::BufferStream strm;
  18064. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  18065. ws::Opcode opcode;
  18066. std::string payload;
  18067. bool fin;
  18068. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18069. false, 1024));
  18070. }
  18071. // RSV3 set (0x10)
  18072. {
  18073. detail::BufferStream strm;
  18074. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  18075. ws::Opcode opcode;
  18076. std::string payload;
  18077. bool fin;
  18078. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18079. false, 1024));
  18080. }
  18081. // No RSV bits set - should succeed
  18082. {
  18083. detail::BufferStream strm;
  18084. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  18085. ws::Opcode opcode;
  18086. std::string payload;
  18087. bool fin;
  18088. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18089. false, 1024));
  18090. EXPECT_EQ(ws::Opcode::Text, opcode);
  18091. EXPECT_EQ("Hello", payload);
  18092. EXPECT_TRUE(fin);
  18093. }
  18094. }
  18095. TEST(WebSocketTest, ControlFrameValidation) {
  18096. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  18097. // payload length <= 125.
  18098. // Ping with FIN=0 - must be rejected
  18099. {
  18100. detail::BufferStream strm;
  18101. std::string frame;
  18102. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  18103. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18104. strm.write(frame.data(), frame.size());
  18105. ws::Opcode opcode;
  18106. std::string payload;
  18107. bool fin;
  18108. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18109. false, 1024));
  18110. }
  18111. // Close with FIN=0 - must be rejected
  18112. {
  18113. detail::BufferStream strm;
  18114. std::string frame;
  18115. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  18116. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18117. strm.write(frame.data(), frame.size());
  18118. ws::Opcode opcode;
  18119. std::string payload;
  18120. bool fin;
  18121. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18122. false, 1024));
  18123. }
  18124. // Ping with payload_len=126 (extended length) - must be rejected
  18125. {
  18126. detail::BufferStream strm;
  18127. std::string frame;
  18128. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18129. frame += static_cast<char>(126); // payload_len=126 (>125)
  18130. frame += static_cast<char>(0x00); // extended length high byte
  18131. frame += static_cast<char>(126); // extended length low byte
  18132. frame += std::string(126, 'x');
  18133. strm.write(frame.data(), frame.size());
  18134. ws::Opcode opcode;
  18135. std::string payload;
  18136. bool fin;
  18137. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18138. false, 1024));
  18139. }
  18140. // Ping with FIN=1 and payload_len=125 - should succeed
  18141. {
  18142. detail::BufferStream strm;
  18143. std::string frame;
  18144. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18145. frame += static_cast<char>(125); // payload_len=125
  18146. frame += std::string(125, 'x');
  18147. strm.write(frame.data(), frame.size());
  18148. ws::Opcode opcode;
  18149. std::string payload;
  18150. bool fin;
  18151. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18152. false, 1024));
  18153. EXPECT_EQ(ws::Opcode::Ping, opcode);
  18154. EXPECT_EQ(125u, payload.size());
  18155. EXPECT_TRUE(fin);
  18156. }
  18157. }
  18158. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  18159. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  18160. // length MUST be 0.
  18161. // MSB set - must be rejected
  18162. {
  18163. detail::BufferStream strm;
  18164. std::string frame;
  18165. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18166. frame += static_cast<char>(127); // 64-bit extended length
  18167. frame += static_cast<char>(0x80); // MSB set (invalid)
  18168. frame += std::string(7, '\0'); // remaining 7 bytes of length
  18169. strm.write(frame.data(), frame.size());
  18170. ws::Opcode opcode;
  18171. std::string payload;
  18172. bool fin;
  18173. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18174. false, 1024));
  18175. }
  18176. // MSB clear - should pass length parsing (will be rejected by max_len,
  18177. // but that's a different check; use a small length to verify)
  18178. {
  18179. detail::BufferStream strm;
  18180. std::string frame;
  18181. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18182. frame += static_cast<char>(127); // 64-bit extended length
  18183. frame += std::string(7, '\0'); // high bytes = 0
  18184. frame += static_cast<char>(0x03); // length = 3
  18185. frame += "abc";
  18186. strm.write(frame.data(), frame.size());
  18187. ws::Opcode opcode;
  18188. std::string payload;
  18189. bool fin;
  18190. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  18191. false, 1024));
  18192. EXPECT_EQ(ws::Opcode::Text, opcode);
  18193. EXPECT_EQ("abc", payload);
  18194. }
  18195. }
  18196. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  18197. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  18198. // Valid UTF-8
  18199. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  18200. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  18201. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  18202. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  18203. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  18204. // Invalid UTF-8
  18205. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  18206. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  18207. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  18208. EXPECT_FALSE(
  18209. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  18210. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  18211. }
  18212. TEST(WebSocketTest, ConnectAndDisconnect) {
  18213. Server svr;
  18214. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18215. std::string msg;
  18216. while (ws.read(msg)) {}
  18217. });
  18218. auto port = svr.bind_to_any_port(HOST);
  18219. std::thread t([&]() { svr.listen_after_bind(); });
  18220. svr.wait_until_ready();
  18221. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18222. auto res = client.connect();
  18223. ASSERT_TRUE(res);
  18224. EXPECT_EQ(Error::Success, res.error());
  18225. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  18226. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  18227. EXPECT_TRUE(client.is_open());
  18228. client.close();
  18229. EXPECT_FALSE(client.is_open());
  18230. svr.stop();
  18231. t.join();
  18232. }
  18233. TEST(WebSocketTest, ValidURL) {
  18234. ws::WebSocketClient ws1("ws://localhost:8080/path");
  18235. EXPECT_TRUE(ws1.is_valid());
  18236. ws::WebSocketClient ws2("ws://example.com/path");
  18237. EXPECT_TRUE(ws2.is_valid());
  18238. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  18239. EXPECT_TRUE(ws3.is_valid());
  18240. #ifdef CPPHTTPLIB_SSL_ENABLED
  18241. ws::WebSocketClient wss1("wss://example.com/path");
  18242. EXPECT_TRUE(wss1.is_valid());
  18243. ws::WebSocketClient wss2("wss://example.com:443/path");
  18244. EXPECT_TRUE(wss2.is_valid());
  18245. #endif
  18246. }
  18247. TEST(WebSocketTest, InvalidURL) {
  18248. // No scheme
  18249. ws::WebSocketClient ws1("localhost:8080/path");
  18250. EXPECT_FALSE(ws1.is_valid());
  18251. // No path
  18252. ws::WebSocketClient ws2("ws://localhost:8080");
  18253. EXPECT_FALSE(ws2.is_valid());
  18254. // Empty string
  18255. ws::WebSocketClient ws3("");
  18256. EXPECT_FALSE(ws3.is_valid());
  18257. // Missing host
  18258. ws::WebSocketClient ws4("ws://:8080/path");
  18259. EXPECT_FALSE(ws4.is_valid());
  18260. // Port number overflow — should not crash
  18261. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  18262. EXPECT_FALSE(ws5.is_valid());
  18263. // Port out of range
  18264. ws::WebSocketClient ws6("ws://localhost:99999/path");
  18265. EXPECT_FALSE(ws6.is_valid());
  18266. }
  18267. TEST(WebSocketTest, UnsupportedScheme) {
  18268. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  18269. ws::WebSocketClient ws1("http://localhost:8080/path");
  18270. EXPECT_FALSE(ws1.is_valid());
  18271. ws::WebSocketClient ws2("https://localhost:8080/path");
  18272. EXPECT_FALSE(ws2.is_valid());
  18273. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  18274. EXPECT_FALSE(ws3.is_valid());
  18275. #else
  18276. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  18277. std::invalid_argument);
  18278. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  18279. std::invalid_argument);
  18280. #endif
  18281. }
  18282. TEST(WebSocketTest, ConnectWhenInvalid) {
  18283. ws::WebSocketClient ws("not a valid url");
  18284. EXPECT_FALSE(ws.is_valid());
  18285. auto res = ws.connect();
  18286. EXPECT_FALSE(res);
  18287. EXPECT_EQ(Error::Connection, res.error());
  18288. EXPECT_EQ(-1, res.status());
  18289. }
  18290. TEST(WebSocketTest, ConnectRefusedReportsError) {
  18291. // Grab a port that is free, then close it again so nothing listens there
  18292. Server svr;
  18293. auto port = svr.bind_to_any_port(HOST);
  18294. svr.stop();
  18295. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18296. auto res = client.connect();
  18297. ASSERT_FALSE(res);
  18298. EXPECT_EQ(Error::Connection, res.error());
  18299. EXPECT_EQ(-1, res.status());
  18300. }
  18301. TEST(WebSocketTest, DefaultPort) {
  18302. ws::WebSocketClient ws1("ws://example.com/path");
  18303. EXPECT_TRUE(ws1.is_valid());
  18304. // ws:// defaults to port 80 (verified by successful parse)
  18305. #ifdef CPPHTTPLIB_SSL_ENABLED
  18306. ws::WebSocketClient ws2("wss://example.com/path");
  18307. EXPECT_TRUE(ws2.is_valid());
  18308. // wss:// defaults to port 443 (verified by successful parse)
  18309. #endif
  18310. }
  18311. TEST(WebSocketTest, IPv6LiteralAddress) {
  18312. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  18313. EXPECT_TRUE(ws1.is_valid());
  18314. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  18315. EXPECT_TRUE(ws2.is_valid());
  18316. }
  18317. TEST(WebSocketTest, ComplexPath) {
  18318. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  18319. EXPECT_TRUE(ws1.is_valid());
  18320. ws::WebSocketClient ws2("ws://localhost:8080/");
  18321. EXPECT_TRUE(ws2.is_valid());
  18322. }
  18323. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  18324. Server svr;
  18325. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18326. std::string msg;
  18327. while (ws.read(msg)) {}
  18328. });
  18329. auto port = svr.bind_to_any_port(HOST);
  18330. std::thread t([&]() { svr.listen_after_bind(); });
  18331. svr.wait_until_ready();
  18332. auto another_host = "example.com";
  18333. auto wrong_ip = "192.0.2.1";
  18334. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18335. client.set_hostname_addr_map({{another_host, wrong_ip}});
  18336. ASSERT_TRUE(client.connect());
  18337. EXPECT_TRUE(client.is_open());
  18338. client.close();
  18339. svr.stop();
  18340. t.join();
  18341. }
  18342. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  18343. Server svr;
  18344. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18345. std::string msg;
  18346. while (ws.read(msg)) {}
  18347. });
  18348. auto port = svr.bind_to_any_port(HOST);
  18349. std::thread t([&]() { svr.listen_after_bind(); });
  18350. svr.wait_until_ready();
  18351. auto wrong_ip = "192.0.2.1";
  18352. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18353. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  18354. client.set_connection_timeout(1);
  18355. client.set_read_timeout(1);
  18356. client.set_write_timeout(1);
  18357. EXPECT_FALSE(client.connect());
  18358. EXPECT_FALSE(client.is_open());
  18359. svr.stop();
  18360. t.join();
  18361. }
  18362. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  18363. // A mapped value that is not an IP literal must be resolved. HOST resolves
  18364. // from the hosts file, so this test needs no external DNS. "target.invalid"
  18365. // (RFC 6761) is only a map key and the Host header value.
  18366. auto host = "target.invalid";
  18367. Server svr;
  18368. std::string received_host;
  18369. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18370. received_host = req.get_header_value("Host");
  18371. std::string msg;
  18372. while (ws.read(msg)) {}
  18373. });
  18374. auto port = svr.bind_to_any_port(HOST);
  18375. std::thread t([&]() { svr.listen_after_bind(); });
  18376. // ASSERT_* below returns from the test body, which would leave t joinable
  18377. // and make ~thread call std::terminate.
  18378. auto se = detail::scope_exit([&] {
  18379. svr.stop();
  18380. if (t.joinable()) { t.join(); }
  18381. });
  18382. svr.wait_until_ready();
  18383. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  18384. std::to_string(port) + "/ws");
  18385. client.set_hostname_addr_map({{host, HOST}});
  18386. ASSERT_TRUE(client.connect());
  18387. EXPECT_TRUE(client.is_open());
  18388. client.close();
  18389. svr.stop();
  18390. t.join();
  18391. // The mapping only redirects the connection; the identity stays host_.
  18392. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  18393. }
  18394. class WebSocketIntegrationTest : public ::testing::Test {
  18395. protected:
  18396. void SetUp() override {
  18397. server_ = httplib::detail::make_unique<Server>();
  18398. setup_server();
  18399. start_server();
  18400. }
  18401. void TearDown() override {
  18402. server_->stop();
  18403. if (server_thread_.joinable()) { server_thread_.join(); }
  18404. }
  18405. void setup_server() {
  18406. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18407. std::string msg;
  18408. ws::ReadResult ret;
  18409. while ((ret = ws.read(msg))) {
  18410. if (ret == ws::Binary) {
  18411. ws.send(msg.data(), msg.size());
  18412. } else {
  18413. ws.send(msg);
  18414. }
  18415. }
  18416. });
  18417. server_->WebSocket("/ws-echo-string",
  18418. [](const Request &, ws::WebSocket &ws) {
  18419. std::string msg;
  18420. while (ws.read(msg)) {
  18421. ws.send("echo: " + msg);
  18422. }
  18423. });
  18424. server_->WebSocket(
  18425. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  18426. // Echo back request metadata
  18427. ws.send("path:" + req.path);
  18428. ws.send("header:" + req.get_header_value("X-Test-Header"));
  18429. std::string msg;
  18430. while (ws.read(msg)) {}
  18431. });
  18432. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  18433. std::string msg;
  18434. ws.read(msg); // wait for a message
  18435. ws.close();
  18436. });
  18437. server_->WebSocket("/ws-close-status",
  18438. [](const Request &, ws::WebSocket &ws) {
  18439. std::string msg;
  18440. ws.read(msg); // wait for a message
  18441. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  18442. });
  18443. server_->WebSocket(
  18444. "/ws-subprotocol",
  18445. [](const Request &, ws::WebSocket &ws) {
  18446. std::string msg;
  18447. while (ws.read(msg)) {
  18448. ws.send(msg);
  18449. }
  18450. },
  18451. [](const std::vector<std::string> &protocols) -> std::string {
  18452. for (const auto &p : protocols) {
  18453. if (p == "graphql-ws") { return p; }
  18454. }
  18455. return "";
  18456. });
  18457. }
  18458. void start_server() {
  18459. port_ = server_->bind_to_any_port(HOST);
  18460. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18461. server_->wait_until_ready();
  18462. }
  18463. std::unique_ptr<Server> server_;
  18464. std::thread server_thread_;
  18465. int port_ = 0;
  18466. };
  18467. TEST_F(WebSocketIntegrationTest, TextEcho) {
  18468. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18469. "/ws-echo");
  18470. ASSERT_TRUE(client.connect());
  18471. ASSERT_TRUE(client.is_open());
  18472. ASSERT_TRUE(client.send("Hello WebSocket"));
  18473. std::string msg;
  18474. EXPECT_EQ(ws::Text, client.read(msg));
  18475. EXPECT_EQ("Hello WebSocket", msg);
  18476. client.close();
  18477. }
  18478. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  18479. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18480. "/ws-echo");
  18481. ASSERT_TRUE(client.connect());
  18482. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  18483. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  18484. std::string msg;
  18485. EXPECT_EQ(ws::Binary, client.read(msg));
  18486. EXPECT_EQ(binary_data, msg);
  18487. client.close();
  18488. }
  18489. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  18490. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18491. "/ws-echo");
  18492. ASSERT_TRUE(client.connect());
  18493. for (int i = 0; i < 10; i++) {
  18494. auto text = "message " + std::to_string(i);
  18495. ASSERT_TRUE(client.send(text));
  18496. std::string msg;
  18497. ASSERT_TRUE(client.read(msg));
  18498. EXPECT_EQ(text, msg);
  18499. }
  18500. client.close();
  18501. }
  18502. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  18503. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18504. "/ws-close");
  18505. ASSERT_TRUE(client.connect());
  18506. // Send a message to trigger the server to close
  18507. ASSERT_TRUE(client.send("trigger close"));
  18508. // The server will close, so read should return false
  18509. std::string msg;
  18510. EXPECT_FALSE(client.read(msg));
  18511. EXPECT_FALSE(client.is_open());
  18512. }
  18513. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  18514. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18515. "/ws-echo");
  18516. ASSERT_TRUE(client.connect());
  18517. // 128KB message
  18518. std::string large_data(128 * 1024, 'X');
  18519. ASSERT_TRUE(client.send(large_data));
  18520. std::string msg;
  18521. ASSERT_TRUE(client.read(msg));
  18522. EXPECT_EQ(large_data, msg);
  18523. client.close();
  18524. }
  18525. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  18526. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18527. "/ws-echo");
  18528. ASSERT_TRUE(client.connect());
  18529. const int num_threads = 4;
  18530. std::vector<std::thread> threads;
  18531. std::atomic<int> send_count{0};
  18532. for (int t = 0; t < num_threads; t++) {
  18533. threads.emplace_back([&client, &send_count, t]() {
  18534. for (int i = 0; i < 5; i++) {
  18535. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  18536. if (client.send(text)) { send_count++; }
  18537. }
  18538. });
  18539. }
  18540. for (auto &th : threads) {
  18541. th.join();
  18542. }
  18543. int received = 0;
  18544. std::string msg;
  18545. while (received < send_count.load()) {
  18546. if (!client.read(msg)) { break; }
  18547. received++;
  18548. }
  18549. EXPECT_EQ(send_count.load(), received);
  18550. client.close();
  18551. }
  18552. TEST_F(WebSocketIntegrationTest, ReadString) {
  18553. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18554. "/ws-echo-string");
  18555. ASSERT_TRUE(client.connect());
  18556. ASSERT_TRUE(client.send("hello"));
  18557. std::string msg;
  18558. ASSERT_TRUE(client.read(msg));
  18559. EXPECT_EQ("echo: hello", msg);
  18560. ASSERT_TRUE(client.send("world"));
  18561. ASSERT_TRUE(client.read(msg));
  18562. EXPECT_EQ("echo: world", msg);
  18563. client.close();
  18564. }
  18565. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  18566. Headers headers = {{"X-Test-Header", "test-value"}};
  18567. ws::WebSocketClient client(
  18568. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  18569. ASSERT_TRUE(client.connect());
  18570. std::string msg;
  18571. ASSERT_TRUE(client.read(msg));
  18572. EXPECT_EQ("path:/ws-request-info", msg);
  18573. ASSERT_TRUE(client.read(msg));
  18574. EXPECT_EQ("header:test-value", msg);
  18575. client.close();
  18576. }
  18577. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  18578. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18579. "/ws-echo");
  18580. client.set_read_timeout(1, 0); // 1 second
  18581. ASSERT_TRUE(client.connect());
  18582. // Don't send anything — server echo handler waits for a message,
  18583. // so read() should time out and return false.
  18584. std::string msg;
  18585. EXPECT_FALSE(client.read(msg));
  18586. }
  18587. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  18588. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18589. "/ws-echo");
  18590. client.set_read_timeout(5, 0);
  18591. ASSERT_TRUE(client.connect());
  18592. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18593. // The server should reject it and close the connection.
  18594. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  18595. client.send(oversized);
  18596. // The server's read() should have failed due to payload limit,
  18597. // so our read() should return false (connection closed).
  18598. std::string msg;
  18599. EXPECT_FALSE(client.read(msg));
  18600. }
  18601. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  18602. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18603. "/ws-echo");
  18604. client.set_read_timeout(10, 0);
  18605. ASSERT_TRUE(client.connect());
  18606. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  18607. // This should succeed.
  18608. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  18609. ASSERT_TRUE(client.send(at_limit));
  18610. std::string msg;
  18611. ASSERT_TRUE(client.read(msg));
  18612. EXPECT_EQ(at_limit.size(), msg.size());
  18613. client.close();
  18614. }
  18615. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  18616. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18617. "/nonexistent");
  18618. auto res = client.connect();
  18619. EXPECT_FALSE(res);
  18620. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18621. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  18622. EXPECT_FALSE(client.is_open());
  18623. }
  18624. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  18625. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18626. "/ws-echo");
  18627. ASSERT_TRUE(client.connect());
  18628. ASSERT_TRUE(client.send(""));
  18629. std::string msg;
  18630. EXPECT_EQ(ws::Text, client.read(msg));
  18631. EXPECT_EQ("", msg);
  18632. client.close();
  18633. }
  18634. TEST_F(WebSocketIntegrationTest, Reconnect) {
  18635. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18636. "/ws-echo");
  18637. // First connection
  18638. ASSERT_TRUE(client.connect());
  18639. ASSERT_TRUE(client.send("first"));
  18640. std::string msg;
  18641. ASSERT_TRUE(client.read(msg));
  18642. EXPECT_EQ("first", msg);
  18643. client.close();
  18644. EXPECT_FALSE(client.is_open());
  18645. // Reconnect using the same client object
  18646. ASSERT_TRUE(client.connect());
  18647. ASSERT_TRUE(client.is_open());
  18648. ASSERT_TRUE(client.send("second"));
  18649. ASSERT_TRUE(client.read(msg));
  18650. EXPECT_EQ("second", msg);
  18651. client.close();
  18652. }
  18653. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  18654. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18655. "/ws-close-status");
  18656. ASSERT_TRUE(client.connect());
  18657. // Trigger the server to close with GoingAway status
  18658. ASSERT_TRUE(client.send("trigger"));
  18659. // read() should return false after receiving the close frame
  18660. std::string msg;
  18661. EXPECT_FALSE(client.read(msg));
  18662. EXPECT_FALSE(client.is_open());
  18663. }
  18664. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  18665. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18666. "/ws-echo");
  18667. ASSERT_TRUE(client.connect());
  18668. client.close(ws::CloseStatus::GoingAway, "client leaving");
  18669. EXPECT_FALSE(client.is_open());
  18670. }
  18671. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  18672. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  18673. ws::WebSocketClient client(
  18674. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18675. ASSERT_TRUE(client.connect());
  18676. // Server should have selected graphql-ws
  18677. EXPECT_EQ("graphql-ws", client.subprotocol());
  18678. client.close();
  18679. }
  18680. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  18681. Headers headers;
  18682. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  18683. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  18684. ws::WebSocketClient client(
  18685. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18686. ASSERT_TRUE(client.connect());
  18687. // The offer on the second field line counts too, so graphql-ws is selected
  18688. EXPECT_EQ("graphql-ws", client.subprotocol());
  18689. client.close();
  18690. }
  18691. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  18692. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  18693. ws::WebSocketClient client(
  18694. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  18695. ASSERT_TRUE(client.connect());
  18696. // Server should not have selected any subprotocol
  18697. EXPECT_TRUE(client.subprotocol().empty());
  18698. client.close();
  18699. }
  18700. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  18701. // Connect without requesting any subprotocol
  18702. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18703. "/ws-subprotocol");
  18704. ASSERT_TRUE(client.connect());
  18705. EXPECT_TRUE(client.subprotocol().empty());
  18706. client.close();
  18707. }
  18708. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  18709. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18710. "/ws-echo");
  18711. client.set_tcp_nodelay(true);
  18712. client.set_connection_timeout(3, 0);
  18713. bool socket_options_called = false;
  18714. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  18715. ASSERT_TRUE(client.connect());
  18716. ASSERT_TRUE(client.is_open());
  18717. EXPECT_TRUE(socket_options_called);
  18718. ASSERT_TRUE(client.send("hello"));
  18719. std::string msg;
  18720. auto result = client.read(msg);
  18721. EXPECT_EQ(result, ws::ReadResult::Text);
  18722. EXPECT_EQ(msg, "hello");
  18723. client.close();
  18724. }
  18725. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  18726. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  18727. "/ws-echo");
  18728. client.set_connection_timeout(std::chrono::seconds(3));
  18729. client.set_write_timeout(std::chrono::seconds(3));
  18730. // A sub-second remainder exercises the seconds/microseconds split.
  18731. client.set_read_timeout(std::chrono::milliseconds(1500));
  18732. ASSERT_TRUE(client.connect());
  18733. auto start = std::chrono::steady_clock::now();
  18734. std::string msg;
  18735. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  18736. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18737. std::chrono::steady_clock::now() - start)
  18738. .count();
  18739. // Above 1s so that dropping the microseconds half of the split fails here,
  18740. // and well under the 300s default so that ignoring the setter fails too.
  18741. EXPECT_GE(elapsed, 1400);
  18742. EXPECT_LT(elapsed, 30000);
  18743. }
  18744. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  18745. Server svr;
  18746. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  18747. if (!req.has_header("Authorization")) {
  18748. res.status = StatusCode::Unauthorized_401;
  18749. res.set_content("Unauthorized", "text/plain");
  18750. return Server::HandlerResponse::Handled;
  18751. }
  18752. return Server::HandlerResponse::Unhandled;
  18753. });
  18754. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18755. std::string msg;
  18756. while (ws.read(msg)) {
  18757. ws.send(msg);
  18758. }
  18759. });
  18760. auto port = svr.bind_to_any_port("localhost");
  18761. std::thread t([&]() { svr.listen_after_bind(); });
  18762. svr.wait_until_ready();
  18763. // Without Authorization header - should be rejected before upgrade
  18764. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  18765. EXPECT_FALSE(client1.connect());
  18766. // With Authorization header - should succeed
  18767. Headers headers = {{"Authorization", "Bearer token123"}};
  18768. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  18769. headers);
  18770. ASSERT_TRUE(client2.connect());
  18771. ASSERT_TRUE(client2.send("hello"));
  18772. std::string msg;
  18773. ASSERT_TRUE(client2.read(msg));
  18774. EXPECT_EQ("hello", msg);
  18775. client2.close();
  18776. svr.stop();
  18777. t.join();
  18778. }
  18779. TEST(WebSocketTest, QueryStringInHandshake) {
  18780. Server svr;
  18781. std::mutex mtx;
  18782. std::string received_target;
  18783. std::string received_token;
  18784. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18785. {
  18786. std::lock_guard<std::mutex> lock(mtx);
  18787. received_target = req.target;
  18788. if (req.has_param("token")) {
  18789. received_token = req.get_param_value("token");
  18790. }
  18791. }
  18792. std::string msg;
  18793. while (ws.read(msg)) {
  18794. ws.send(msg);
  18795. }
  18796. });
  18797. auto port = svr.bind_to_any_port("localhost");
  18798. std::thread t([&]() { svr.listen_after_bind(); });
  18799. svr.wait_until_ready();
  18800. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  18801. "/ws?token=ABC&session=123");
  18802. ASSERT_TRUE(client.connect());
  18803. // Round-trip ensures the handler has run and captured the request.
  18804. ASSERT_TRUE(client.send("hello"));
  18805. std::string msg;
  18806. ASSERT_TRUE(client.read(msg));
  18807. EXPECT_EQ("hello", msg);
  18808. client.close();
  18809. {
  18810. std::lock_guard<std::mutex> lock(mtx);
  18811. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  18812. EXPECT_EQ("ABC", received_token);
  18813. }
  18814. svr.stop();
  18815. t.join();
  18816. }
  18817. // Run a handshake against a throwaway server and hand the request the server
  18818. // received back to the caller, so tests can assert on the headers the client
  18819. // actually put on the wire.
  18820. static void capture_websocket_handshake_request(
  18821. const Headers &client_headers,
  18822. std::function<void(const Request &, int port)> verify) {
  18823. Server svr;
  18824. std::mutex mtx;
  18825. Request received;
  18826. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18827. {
  18828. std::lock_guard<std::mutex> lock(mtx);
  18829. received = req;
  18830. }
  18831. std::string msg;
  18832. while (ws.read(msg)) {
  18833. ws.send(msg);
  18834. }
  18835. });
  18836. auto port = svr.bind_to_any_port("localhost");
  18837. std::thread t([&]() { svr.listen_after_bind(); });
  18838. auto se = detail::scope_exit([&] {
  18839. svr.stop();
  18840. t.join();
  18841. });
  18842. svr.wait_until_ready();
  18843. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  18844. client_headers);
  18845. ASSERT_TRUE(client.connect());
  18846. ASSERT_TRUE(client.send("hello"));
  18847. std::string msg;
  18848. ASSERT_TRUE(client.read(msg));
  18849. client.close();
  18850. {
  18851. std::lock_guard<std::mutex> lock(mtx);
  18852. verify(received, port);
  18853. }
  18854. }
  18855. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  18856. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  18857. // Non-default port must be present in the Host header. Default ports
  18858. // (80/443) are omitted; that logic is covered by
  18859. // MakeHostAndPortStringTest.
  18860. EXPECT_EQ("localhost:" + std::to_string(port),
  18861. req.get_header_value("Host"));
  18862. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  18863. req.get_header_value("User-Agent"));
  18864. EXPECT_FALSE(req.has_header("Accept"));
  18865. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  18866. EXPECT_FALSE(req.has_header("Content-Length"));
  18867. });
  18868. }
  18869. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  18870. capture_websocket_handshake_request(
  18871. {{"Host", "example.com"},
  18872. {"User-Agent", "custom-agent"},
  18873. {"X-Custom", "value"}},
  18874. [](const Request &req, int) {
  18875. EXPECT_EQ("example.com", req.get_header_value("Host"));
  18876. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  18877. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  18878. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  18879. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  18880. });
  18881. }
  18882. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  18883. capture_websocket_handshake_request(
  18884. {{"Upgrade", "bogus"},
  18885. {"Connection", "close"},
  18886. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  18887. {"Sec-WebSocket-Version", "8"}},
  18888. [](const Request &req, int) {
  18889. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  18890. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  18891. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  18892. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  18893. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  18894. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  18895. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  18896. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  18897. req.get_header_value("Sec-WebSocket-Key"));
  18898. });
  18899. }
  18900. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  18901. // A header the client refuses to send must abort the handshake before any
  18902. // part of it reaches the wire; a lone request line would otherwise sit in
  18903. // the peer's buffer as a truncated request.
  18904. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18905. ASSERT_NE(INVALID_SOCKET, srv);
  18906. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  18907. sockaddr_in addr{};
  18908. addr.sin_family = AF_INET;
  18909. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  18910. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18911. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18912. ASSERT_EQ(0, ::listen(srv, 1));
  18913. sockaddr_in bound{};
  18914. socklen_t bound_len = sizeof(bound);
  18915. ASSERT_EQ(
  18916. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  18917. auto port = ntohs(bound.sin_port);
  18918. ssize_t received = -1;
  18919. std::thread t([&] {
  18920. // Bound every blocking call so a regression fails the test with a bad
  18921. // value instead of hanging the suite.
  18922. fd_set rfds;
  18923. FD_ZERO(&rfds);
  18924. FD_SET(srv, &rfds);
  18925. timeval tv{5, 0};
  18926. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  18927. 0) {
  18928. return;
  18929. }
  18930. sockaddr_in cli_addr{};
  18931. socklen_t cli_len = sizeof(cli_addr);
  18932. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18933. if (cli == INVALID_SOCKET) { return; }
  18934. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  18935. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18936. char buf[4096];
  18937. received = ::recv(cli, buf, sizeof(buf), 0);
  18938. });
  18939. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  18940. // connect() has already shut the socket down by the time it returns false,
  18941. // so the peer sees EOF without waiting for the client to be destroyed.
  18942. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  18943. {{"X-Bad", "a\r\nInjected: 1"}});
  18944. EXPECT_FALSE(client.connect());
  18945. t.join();
  18946. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  18947. EXPECT_EQ(0, received);
  18948. }
  18949. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  18950. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  18951. // contains "upgrade" as a substring is a different token and must not
  18952. // start a WebSocket handshake.
  18953. auto make_request = [](const std::vector<std::string> &connection_values) {
  18954. Request req;
  18955. req.method = "GET";
  18956. req.headers.emplace("Upgrade", "websocket");
  18957. for (const auto &value : connection_values) {
  18958. req.headers.emplace("Connection", value);
  18959. }
  18960. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18961. req.headers.emplace("Sec-WebSocket-Version", "13");
  18962. return req;
  18963. };
  18964. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  18965. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  18966. EXPECT_TRUE(
  18967. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  18968. EXPECT_TRUE(
  18969. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  18970. EXPECT_TRUE(
  18971. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  18972. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  18973. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  18974. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  18975. EXPECT_FALSE(
  18976. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  18977. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  18978. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18979. }
  18980. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  18981. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  18982. // asks recipients to match each protocol-name case-insensitively, and RFC
  18983. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  18984. // client naming websocket alongside another protocol, or on a second field
  18985. // line, is offering websocket; a value that merely contains "websocket" as a
  18986. // substring is a different protocol name and is not.
  18987. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  18988. Request req;
  18989. req.method = "GET";
  18990. for (const auto &value : upgrade_values) {
  18991. req.headers.emplace("Upgrade", value);
  18992. }
  18993. req.headers.emplace("Connection", "Upgrade");
  18994. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18995. req.headers.emplace("Sec-WebSocket-Version", "13");
  18996. return req;
  18997. };
  18998. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  18999. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  19000. EXPECT_TRUE(
  19001. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  19002. EXPECT_TRUE(
  19003. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  19004. EXPECT_TRUE(
  19005. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  19006. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  19007. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  19008. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  19009. EXPECT_FALSE(
  19010. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  19011. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  19012. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  19013. }
  19014. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  19015. Server svr;
  19016. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  19017. auto port = svr.bind_to_any_port("localhost");
  19018. std::thread t([&]() { svr.listen_after_bind(); });
  19019. auto se = detail::scope_exit([&] {
  19020. svr.stop();
  19021. t.join();
  19022. });
  19023. svr.wait_until_ready();
  19024. Headers headers = {{"Upgrade", "websocket"},
  19025. {"Connection", "notupgrade"},
  19026. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  19027. {"Sec-WebSocket-Version", "13"}};
  19028. Client cli("localhost", port);
  19029. auto res = cli.Get("/ws", headers);
  19030. // The route exists only as a WebSocket route, so a request that fails the
  19031. // handshake check falls through to ordinary routing.
  19032. ASSERT_TRUE(res);
  19033. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  19034. }
  19035. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  19036. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  19037. // Connection value is the only thing left for the client to reject.
  19038. Server svr;
  19039. svr.Get("/ws", [](const Request &req, Response &res) {
  19040. res.status = StatusCode::SwitchingProtocol_101;
  19041. res.set_header("Upgrade", "websocket");
  19042. res.set_header("Connection", "notupgrade");
  19043. res.set_header("Sec-WebSocket-Accept",
  19044. detail::websocket_accept_key(
  19045. req.get_header_value("Sec-WebSocket-Key")));
  19046. });
  19047. auto port = svr.bind_to_any_port("localhost");
  19048. std::thread t([&]() { svr.listen_after_bind(); });
  19049. auto se = detail::scope_exit([&] {
  19050. svr.stop();
  19051. t.join();
  19052. });
  19053. svr.wait_until_ready();
  19054. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19055. auto res = client.connect();
  19056. EXPECT_FALSE(res);
  19057. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19058. EXPECT_FALSE(client.is_open());
  19059. }
  19060. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  19061. // The socket path doubles as the URL host, so it must not contain '/'.
  19062. const char *shard = getenv("GTEST_SHARD_INDEX");
  19063. const std::string sock_path =
  19064. shard ? std::string("httplib-ws-") + shard + ".sock"
  19065. : std::string("httplib-ws.sock");
  19066. std::remove(sock_path.c_str());
  19067. Server svr;
  19068. std::mutex mtx;
  19069. std::string received_host;
  19070. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19071. {
  19072. std::lock_guard<std::mutex> lock(mtx);
  19073. received_host = req.get_header_value("Host");
  19074. }
  19075. std::string msg;
  19076. while (ws.read(msg)) {
  19077. ws.send(msg);
  19078. }
  19079. });
  19080. svr.set_address_family(AF_UNIX);
  19081. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  19082. auto se = detail::scope_exit([&] {
  19083. svr.stop();
  19084. t.join();
  19085. std::remove(sock_path.c_str());
  19086. });
  19087. svr.wait_until_ready();
  19088. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  19089. client.set_address_family(AF_UNIX);
  19090. ASSERT_TRUE(client.connect());
  19091. ASSERT_TRUE(client.send("hello"));
  19092. std::string msg;
  19093. ASSERT_TRUE(client.read(msg));
  19094. client.close();
  19095. {
  19096. std::lock_guard<std::mutex> lock(mtx);
  19097. // There is no host:port for a Unix socket, so the same "localhost"
  19098. // placeholder the HTTP client uses is expected.
  19099. EXPECT_EQ("localhost", received_host);
  19100. }
  19101. }
  19102. // Two threads must never parse WebSocket frames from the same stream.
  19103. // close() used to read the peer's Close reply with its own frame read, so it
  19104. // raced a reader thread that was in the middle of a payload: the payload loop
  19105. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  19106. // so bytes taken by close() were replaced with bytes from further along the
  19107. // stream. The message kept its length and silently changed content.
  19108. //
  19109. // The raw peer below sends a frame header plus part of the payload, waits for
  19110. // the handler to call close(), and only then sends the rest. Whichever thread
  19111. // would win the race for those bytes, the message must arrive intact, because
  19112. // close() must not touch the stream while read() owns it.
  19113. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  19114. #ifndef _WIN32
  19115. signal(SIGPIPE, SIG_IGN);
  19116. #endif
  19117. const size_t payload_len = 120; // fits the 7-bit length field
  19118. const size_t prefix_len = 8;
  19119. const int attempts = 8;
  19120. std::string expected(payload_len, '\0');
  19121. for (size_t i = 0; i < payload_len; i++) {
  19122. expected[i] = static_cast<char>('a' + i % 26);
  19123. }
  19124. std::atomic<bool> peer_stalled{false};
  19125. std::atomic<bool> handler_done{false};
  19126. std::mutex received_mutex;
  19127. std::vector<std::string> received;
  19128. // Bound every wait, so a regression fails the test instead of hanging the
  19129. // suite.
  19130. auto wait_for = [](const std::atomic<bool> &flag) {
  19131. for (int i = 0; i < 500 && !flag; i++) {
  19132. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19133. }
  19134. };
  19135. Server svr;
  19136. svr.set_websocket_ping_interval(0);
  19137. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  19138. std::thread reader([&]() {
  19139. std::string msg;
  19140. while (ws.read(msg)) {
  19141. std::lock_guard<std::mutex> guard(received_mutex);
  19142. received.push_back(msg);
  19143. }
  19144. });
  19145. // Wait until the peer stalls mid-payload, so the reader thread is parked
  19146. // inside read_websocket_frame() when close() runs.
  19147. wait_for(peer_stalled);
  19148. ws.close();
  19149. reader.join();
  19150. handler_done = true;
  19151. });
  19152. auto port = svr.bind_to_any_port("127.0.0.1");
  19153. std::thread t([&]() { svr.listen_after_bind(); });
  19154. auto se = detail::scope_exit([&] {
  19155. svr.stop();
  19156. t.join();
  19157. });
  19158. svr.wait_until_ready();
  19159. auto send_bytes = [](socket_t s, const std::string &data) {
  19160. #ifdef _WIN32
  19161. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  19162. #else
  19163. auto n = ::send(s, data.data(), data.size(), 0);
  19164. #endif
  19165. return n == static_cast<decltype(n)>(data.size());
  19166. };
  19167. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  19168. // Every length used here fits the 7-bit length field.
  19169. auto masked_header = [](uint8_t first_byte, size_t len) {
  19170. std::string h;
  19171. h += static_cast<char>(first_byte);
  19172. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  19173. h.append(4, '\0'); // mask key
  19174. return h;
  19175. };
  19176. for (int attempt = 0; attempt < attempts; attempt++) {
  19177. peer_stalled = false;
  19178. handler_done = false;
  19179. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  19180. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  19181. auto se_sock = detail::scope_exit([&] {
  19182. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  19183. });
  19184. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19185. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19186. sockaddr_in addr{};
  19187. addr.sin_family = AF_INET;
  19188. addr.sin_port = htons(static_cast<uint16_t>(port));
  19189. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19190. ASSERT_EQ(
  19191. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  19192. << "attempt " << attempt;
  19193. ASSERT_TRUE(send_bytes(sock,
  19194. "GET /ws HTTP/1.1\r\n"
  19195. "Host: 127.0.0.1\r\n"
  19196. "Upgrade: websocket\r\n"
  19197. "Connection: Upgrade\r\n"
  19198. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  19199. "Sec-WebSocket-Version: 13\r\n"
  19200. "\r\n"))
  19201. << "attempt " << attempt;
  19202. std::string response;
  19203. while (response.find("\r\n\r\n") == std::string::npos) {
  19204. char buf[512];
  19205. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  19206. if (n <= 0) { break; }
  19207. response.append(buf, static_cast<size_t>(n));
  19208. }
  19209. ASSERT_NE(std::string::npos, response.find(" 101 "))
  19210. << "attempt " << attempt;
  19211. // Send the header of a Binary message but only the first prefix_len bytes
  19212. // of its payload, leaving the reader thread stalled inside the payload.
  19213. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  19214. expected.substr(0, prefix_len)))
  19215. << "attempt " << attempt;
  19216. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19217. peer_stalled = true;
  19218. // Let close() send its Close frame and park in its own read before the
  19219. // rest of the payload arrives, so both threads are waiting for it.
  19220. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19221. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  19222. close_frame += static_cast<char>(0x03); // status 1000
  19223. close_frame += static_cast<char>(0xE8);
  19224. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  19225. << "attempt " << attempt;
  19226. // Closing the peer releases the reader thread even on the buggy path,
  19227. // where it waits for bytes another thread already consumed.
  19228. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19229. detail::close_socket(sock);
  19230. sock = INVALID_SOCKET;
  19231. wait_for(handler_done);
  19232. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  19233. }
  19234. std::lock_guard<std::mutex> guard(received_mutex);
  19235. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  19236. << "a message in flight when close() ran was dropped";
  19237. for (size_t i = 0; i < received.size(); i++) {
  19238. EXPECT_EQ(expected, received[i]) << "message " << i;
  19239. }
  19240. }
  19241. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19242. class WebSocketSSLIntegrationTest : public ::testing::Test {
  19243. protected:
  19244. void SetUp() override {
  19245. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  19246. SERVER_PRIVATE_KEY_FILE);
  19247. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19248. std::string msg;
  19249. ws::ReadResult ret;
  19250. while ((ret = ws.read(msg))) {
  19251. if (ret == ws::Binary) {
  19252. ws.send(msg.data(), msg.size());
  19253. } else {
  19254. ws.send(msg);
  19255. }
  19256. }
  19257. });
  19258. port_ = server_->bind_to_any_port(HOST);
  19259. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19260. server_->wait_until_ready();
  19261. }
  19262. void TearDown() override {
  19263. server_->stop();
  19264. if (server_thread_.joinable()) { server_thread_.join(); }
  19265. }
  19266. std::unique_ptr<SSLServer> server_;
  19267. std::thread server_thread_;
  19268. int port_ = 0;
  19269. };
  19270. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  19271. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19272. "/ws-echo");
  19273. client.enable_server_certificate_verification(false);
  19274. ASSERT_TRUE(client.connect());
  19275. ASSERT_TRUE(client.is_open());
  19276. ASSERT_TRUE(client.send("Hello WSS"));
  19277. std::string msg;
  19278. EXPECT_EQ(ws::Text, client.read(msg));
  19279. EXPECT_EQ("Hello WSS", msg);
  19280. client.close();
  19281. }
  19282. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  19283. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  19284. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  19285. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  19286. // client (without calling close() first) is the only path that runs
  19287. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  19288. // bug exactly.
  19289. //
  19290. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  19291. // when linked against an instrumented libssl; run under Valgrind to catch it
  19292. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  19293. // suite (the freed session otherwise stalls on the close handshake) — this test
  19294. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  19295. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  19296. {
  19297. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19298. "/ws-echo");
  19299. client.enable_server_certificate_verification(false);
  19300. client.set_read_timeout(2, 0);
  19301. client.set_write_timeout(2, 0);
  19302. ASSERT_TRUE(client.connect());
  19303. ASSERT_TRUE(client.is_open());
  19304. ASSERT_TRUE(client.send("still open"));
  19305. // Intentionally do NOT call client.close(): leaving scope runs
  19306. // shutdown_and_close() with the WebSocket still open, which must send the
  19307. // close frame while the TLS session is still alive.
  19308. }
  19309. }
  19310. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  19311. // shutdown_and_close() at the start of connect(), reproducing the same
  19312. // use-after-free within the test body rather than at scope exit. The second
  19313. // connect must succeed and echo, proving the close handshake ran over a live
  19314. // session. See the note above about memory-tool requirements.
  19315. TEST_F(WebSocketSSLIntegrationTest,
  19316. ReconnectWhileOpenSendsCloseOverLiveSession) {
  19317. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19318. "/ws-echo");
  19319. client.enable_server_certificate_verification(false);
  19320. client.set_read_timeout(2, 0);
  19321. client.set_write_timeout(2, 0);
  19322. ASSERT_TRUE(client.connect());
  19323. ASSERT_TRUE(client.is_open());
  19324. ASSERT_TRUE(client.send("still open"));
  19325. // Reconnect without closing first: connect() calls shutdown_and_close() on
  19326. // the still-open connection, which must not touch a freed TLS session.
  19327. ASSERT_TRUE(client.connect());
  19328. ASSERT_TRUE(client.is_open());
  19329. ASSERT_TRUE(client.send("after reconnect"));
  19330. std::string msg;
  19331. EXPECT_EQ(ws::Text, client.read(msg));
  19332. EXPECT_EQ("after reconnect", msg);
  19333. client.close();
  19334. }
  19335. #endif
  19336. #ifdef CPPHTTPLIB_SSL_ENABLED
  19337. class WebSocketSSLCATest : public ::testing::Test {
  19338. protected:
  19339. void SetUp() override {
  19340. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  19341. SERVER_PRIVATE_KEY_FILE);
  19342. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19343. std::string msg;
  19344. while (ws.read(msg)) {
  19345. ws.send(msg);
  19346. }
  19347. });
  19348. port_ = server_->bind_to_any_port("127.0.0.1");
  19349. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19350. server_->wait_until_ready();
  19351. }
  19352. void TearDown() override {
  19353. server_->stop();
  19354. if (server_thread_.joinable()) { server_thread_.join(); }
  19355. }
  19356. std::string url() const {
  19357. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  19358. }
  19359. std::unique_ptr<SSLServer> server_;
  19360. std::thread server_thread_;
  19361. int port_ = 0;
  19362. };
  19363. // A custom CA loaded as PEM verifies the server with full certificate
  19364. // verification enabled
  19365. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  19366. ws::WebSocketClient client(url());
  19367. std::string cert;
  19368. read_file(SERVER_CERT2_FILE, cert);
  19369. client.load_ca_cert_store(cert.c_str(), cert.size());
  19370. ASSERT_TRUE(client.connect());
  19371. ASSERT_TRUE(client.send("hello"));
  19372. std::string msg;
  19373. EXPECT_EQ(ws::Text, client.read(msg));
  19374. EXPECT_EQ("hello", msg);
  19375. client.close();
  19376. }
  19377. // A custom CA that does not cover the server must fail verification (the
  19378. // custom CA is exclusive; system certs are not loaded alongside it)
  19379. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  19380. ws::WebSocketClient client(url());
  19381. std::string cert;
  19382. read_file(CLIENT_CA_CERT_FILE, cert);
  19383. client.load_ca_cert_store(cert.c_str(), cert.size());
  19384. auto res = client.connect();
  19385. ASSERT_FALSE(res);
  19386. EXPECT_EQ(Error::SSLServerVerification, res.error());
  19387. EXPECT_EQ(-1, res.status());
  19388. EXPECT_NE(0u, res.ssl_backend_error());
  19389. }
  19390. // The same CA as a file path rather than PEM in memory
  19391. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  19392. ws::WebSocketClient client(url());
  19393. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19394. ASSERT_TRUE(client.connect());
  19395. ASSERT_TRUE(client.send("hello"));
  19396. std::string msg;
  19397. EXPECT_EQ(ws::Text, client.read(msg));
  19398. EXPECT_EQ("hello", msg);
  19399. client.close();
  19400. }
  19401. // ...and a CA file that does not cover the server still fails, so it is the
  19402. // path above that decides the outcome
  19403. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  19404. ws::WebSocketClient client(url());
  19405. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19406. ASSERT_FALSE(client.connect());
  19407. }
  19408. // Regression test: reconnecting with a native custom CA store used to reuse
  19409. // a store handle the previous TLS context had already freed (use-after-free
  19410. // under the OpenSSL backend). The context now lives as long as the client.
  19411. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  19412. ws::WebSocketClient client(url());
  19413. std::string cert;
  19414. read_file(SERVER_CERT2_FILE, cert);
  19415. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  19416. ASSERT_TRUE(client.connect());
  19417. client.close();
  19418. ASSERT_TRUE(client.connect());
  19419. ASSERT_TRUE(client.send("again"));
  19420. std::string msg;
  19421. EXPECT_EQ(ws::Text, client.read(msg));
  19422. EXPECT_EQ("again", msg);
  19423. client.close();
  19424. }
  19425. // Regression test: a certificate with a trusted chain but no identity match
  19426. // for the server IP must be rejected. The Mbed TLS backend used to skip
  19427. // verification entirely for IP hosts, so this connection succeeded there.
  19428. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  19429. // chain verification while the identity check must still fail.
  19430. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  19431. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19432. ASSERT_TRUE(svr.is_valid());
  19433. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19434. std::string msg;
  19435. while (ws.read(msg)) {
  19436. ws.send(msg);
  19437. }
  19438. });
  19439. auto port = svr.bind_to_any_port("127.0.0.1");
  19440. auto t = std::thread([&]() { svr.listen_after_bind(); });
  19441. auto se = detail::scope_exit([&] {
  19442. svr.stop();
  19443. t.join();
  19444. });
  19445. svr.wait_until_ready();
  19446. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  19447. "/echo");
  19448. std::string cert;
  19449. read_file(SERVER_CERT_FILE, cert);
  19450. client.load_ca_cert_store(cert.c_str(), cert.size());
  19451. ASSERT_FALSE(client.connect());
  19452. }
  19453. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  19454. // SNI, so nothing binds the host name to the TLS session. These bind the
  19455. // server to "localhost" instead, the only shape that exercises the SNI and
  19456. // hostname-verification path with certificate verification left enabled.
  19457. class WebSocketSSLDnsHostTest : public ::testing::Test {
  19458. protected:
  19459. void Start(const char *cert_file) {
  19460. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  19461. SERVER_PRIVATE_KEY_FILE);
  19462. ASSERT_TRUE(server_->is_valid());
  19463. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  19464. std::string msg;
  19465. while (ws.read(msg)) {
  19466. ws.send(msg);
  19467. }
  19468. });
  19469. port_ = server_->bind_to_any_port("localhost");
  19470. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19471. server_->wait_until_ready();
  19472. }
  19473. void TearDown() override {
  19474. if (server_) { server_->stop(); }
  19475. if (server_thread_.joinable()) { server_thread_.join(); }
  19476. }
  19477. std::string url() const {
  19478. return "wss://localhost:" + std::to_string(port_) + "/echo";
  19479. }
  19480. std::unique_ptr<SSLServer> server_;
  19481. std::thread server_thread_;
  19482. int port_ = 0;
  19483. };
  19484. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  19485. // out and the connection is usable
  19486. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  19487. Start(SERVER_CERT2_FILE);
  19488. ws::WebSocketClient client(url());
  19489. client.set_ca_cert_path(SERVER_CERT2_FILE);
  19490. ASSERT_TRUE(client.connect());
  19491. ASSERT_TRUE(client.send("hello"));
  19492. std::string msg;
  19493. EXPECT_EQ(ws::Text, client.read(msg));
  19494. EXPECT_EQ("hello", msg);
  19495. client.close();
  19496. }
  19497. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  19498. // while the identity check must still reject "localhost"
  19499. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  19500. Start(SERVER_CERT_FILE);
  19501. ws::WebSocketClient client(url());
  19502. client.set_ca_cert_path(SERVER_CERT_FILE);
  19503. auto res = client.connect();
  19504. ASSERT_FALSE(res);
  19505. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  19506. EXPECT_EQ(-1, res.status());
  19507. }
  19508. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  19509. // disabled: the chain is still checked, only the identity check is skipped
  19510. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  19511. Start(SERVER_CERT_FILE);
  19512. ws::WebSocketClient client(url());
  19513. client.set_ca_cert_path(SERVER_CERT_FILE);
  19514. client.enable_server_hostname_verification(false);
  19515. ASSERT_TRUE(client.connect());
  19516. ASSERT_TRUE(client.send("hello"));
  19517. std::string msg;
  19518. EXPECT_EQ(ws::Text, client.read(msg));
  19519. EXPECT_EQ("hello", msg);
  19520. client.close();
  19521. }
  19522. // A CA that did not sign the server certificate fails the chain, even though
  19523. // the name would match
  19524. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  19525. Start(SERVER_CERT2_FILE);
  19526. ws::WebSocketClient client(url());
  19527. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  19528. ASSERT_FALSE(client.connect());
  19529. }
  19530. // With verification disabled, neither the chain nor the name is checked
  19531. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  19532. Start(SERVER_CERT_FILE);
  19533. ws::WebSocketClient client(url());
  19534. client.enable_server_certificate_verification(false);
  19535. ASSERT_TRUE(client.connect());
  19536. ASSERT_TRUE(client.send("hello"));
  19537. std::string msg;
  19538. EXPECT_EQ(ws::Text, client.read(msg));
  19539. EXPECT_EQ("hello", msg);
  19540. client.close();
  19541. }
  19542. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  19543. protected:
  19544. void SetUp() override {
  19545. server_ = httplib::detail::make_unique<SSLServer>(
  19546. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19547. ASSERT_TRUE(server_->is_valid());
  19548. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19549. std::string msg;
  19550. while (ws.read(msg)) {
  19551. ws.send(msg);
  19552. }
  19553. });
  19554. port_ = server_->bind_to_any_port("localhost");
  19555. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19556. server_->wait_until_ready();
  19557. }
  19558. void TearDown() override {
  19559. server_->stop();
  19560. if (server_thread_.joinable()) { server_thread_.join(); }
  19561. }
  19562. std::string url() const {
  19563. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  19564. }
  19565. void ConnectWithClientCert(const std::string &client_cert_file,
  19566. const std::string &client_private_key_file,
  19567. const char *private_key_password) {
  19568. std::string cert_pem, key_pem;
  19569. read_file(client_cert_file, cert_pem);
  19570. read_file(client_private_key_file, key_pem);
  19571. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  19572. key_pem.c_str(), key_pem.size(),
  19573. private_key_password};
  19574. ws::WebSocketClient client(url(), pem);
  19575. ASSERT_TRUE(client.is_valid());
  19576. client.enable_server_certificate_verification(false);
  19577. ASSERT_TRUE(client.connect());
  19578. ASSERT_TRUE(client.send("hello"));
  19579. std::string msg;
  19580. EXPECT_EQ(ws::Text, client.read(msg));
  19581. EXPECT_EQ("hello", msg);
  19582. client.close();
  19583. }
  19584. std::unique_ptr<SSLServer> server_;
  19585. std::thread server_thread_;
  19586. int port_ = 0;
  19587. };
  19588. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  19589. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  19590. }
  19591. // Control for the tests above: the fixture's server really does require a
  19592. // client certificate, so it is the PEM the constructor installed that decides
  19593. // the outcome.
  19594. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  19595. ws::WebSocketClient client(url());
  19596. ASSERT_TRUE(client.is_valid());
  19597. client.enable_server_certificate_verification(false);
  19598. EXPECT_FALSE(client.connect());
  19599. }
  19600. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  19601. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  19602. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  19603. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  19604. }
  19605. #endif
  19606. #if !defined(_WIN32)
  19607. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  19608. auto secret_dir = std::string("./symlink_test_secret");
  19609. auto served_dir = std::string("./symlink_test_served");
  19610. auto secret_file = secret_dir + "/secret.txt";
  19611. auto symlink_path = served_dir + "/escape";
  19612. // Setup: create directories and files
  19613. mkdir(secret_dir.c_str(), 0755);
  19614. mkdir(served_dir.c_str(), 0755);
  19615. {
  19616. std::ofstream ofs(secret_file);
  19617. ofs << "SECRET_DATA";
  19618. }
  19619. // Create symlink using absolute path so it resolves correctly
  19620. #ifdef PATH_MAX
  19621. char abs_secret[PATH_MAX];
  19622. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  19623. #else
  19624. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  19625. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  19626. ASSERT_NE(nullptr, abs_secret);
  19627. #endif
  19628. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  19629. auto se = detail::scope_exit([&] {
  19630. unlink(symlink_path.c_str());
  19631. unlink(secret_file.c_str());
  19632. rmdir(served_dir.c_str());
  19633. rmdir(secret_dir.c_str());
  19634. });
  19635. Server svr;
  19636. svr.set_mount_point("/", served_dir);
  19637. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19638. auto se2 = detail::scope_exit([&] {
  19639. svr.stop();
  19640. listen_thread.join();
  19641. });
  19642. svr.wait_until_ready();
  19643. Client cli("localhost", PORT);
  19644. // Symlink pointing outside base dir should be blocked
  19645. auto res = cli.Get("/escape/secret.txt");
  19646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19647. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19648. }
  19649. #endif
  19650. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  19651. // A GET request with Content-Length to a static file handler must have its
  19652. // body drained before the keep-alive connection is reused. Otherwise the
  19653. // unread body bytes are interpreted as the next HTTP request.
  19654. //
  19655. // The body is sent AFTER receiving the first response (as in the original
  19656. // PoC) so that the stream_line_reader cannot buffer it together with the
  19657. // headers of the first request.
  19658. Server svr;
  19659. svr.set_mount_point("/", "./www");
  19660. std::atomic<int> smuggled_count(0);
  19661. svr.Get("/smuggled", [&](const Request &, Response &res) {
  19662. smuggled_count++;
  19663. res.set_content("oops", "text/plain");
  19664. });
  19665. auto port = svr.bind_to_any_port("localhost");
  19666. thread t = thread([&] { svr.listen_after_bind(); });
  19667. auto se = detail::scope_exit([&] {
  19668. svr.stop();
  19669. t.join();
  19670. });
  19671. svr.wait_until_ready();
  19672. auto error = Error::Success;
  19673. auto sock = detail::create_client_socket(
  19674. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  19675. /*connection_timeout_sec=*/2, 0,
  19676. /*read_timeout_sec=*/2, 0,
  19677. /*write_timeout_sec=*/2, 0, std::string(), error);
  19678. ASSERT_NE(INVALID_SOCKET, sock);
  19679. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19680. // The "smuggled" request will be sent as the body of the outer GET
  19681. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  19682. "Host: localhost\r\n"
  19683. "Connection: close\r\n"
  19684. "\r\n";
  19685. // Step 1: Send only the outer request headers (no body yet)
  19686. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  19687. "Host: localhost\r\n"
  19688. "Content-Length: " +
  19689. std::to_string(smuggled.size()) +
  19690. "\r\n"
  19691. "\r\n";
  19692. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  19693. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  19694. // Step 2: Read the first response (server serves file without reading body)
  19695. std::string first_response;
  19696. char buf[4096];
  19697. for (;;) {
  19698. auto n = recv(sock, buf, sizeof(buf), 0);
  19699. if (n <= 0) break;
  19700. first_response.append(buf, static_cast<size_t>(n));
  19701. // Stop once we have a complete response (headers + body)
  19702. auto hdr_end = first_response.find("\r\n\r\n");
  19703. if (hdr_end != std::string::npos) {
  19704. // Check for Content-Length to know when the body is complete
  19705. auto cl_pos = first_response.find("Content-Length:");
  19706. if (cl_pos != std::string::npos) {
  19707. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  19708. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  19709. auto cl = std::stoul(
  19710. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  19711. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  19712. } else {
  19713. break; // No Content-Length, assume headers-only response
  19714. }
  19715. }
  19716. }
  19717. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  19718. // Step 3: Now send the body, which looks like a new HTTP request.
  19719. // On a vulnerable server the keep-alive loop reads this as a second request.
  19720. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  19721. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  19722. // Step 4: Try to read a second response (should NOT exist after fix)
  19723. std::string second_response;
  19724. for (;;) {
  19725. auto n = recv(sock, buf, sizeof(buf), 0);
  19726. if (n <= 0) break;
  19727. second_response.append(buf, static_cast<size_t>(n));
  19728. }
  19729. // The smuggled request must NOT have been processed
  19730. EXPECT_EQ(0, smuggled_count.load());
  19731. }
  19732. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19733. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  19734. // must be rejected with 400 Bad Request.
  19735. Server svr;
  19736. svr.Post("/test", [&](const Request &, Response &res) {
  19737. res.set_content("ok", "text/plain");
  19738. });
  19739. thread t = thread([&] { svr.listen(HOST, PORT); });
  19740. auto se = detail::scope_exit([&] {
  19741. svr.stop();
  19742. t.join();
  19743. ASSERT_FALSE(svr.is_running());
  19744. });
  19745. svr.wait_until_ready();
  19746. // Exact "chunked"
  19747. {
  19748. auto req = "POST /test HTTP/1.1\r\n"
  19749. "Host: localhost\r\n"
  19750. "Content-Length: 5\r\n"
  19751. "Transfer-Encoding: chunked\r\n"
  19752. "Connection: close\r\n"
  19753. "\r\n"
  19754. "hello";
  19755. std::string response;
  19756. ASSERT_TRUE(send_request(1, req, &response));
  19757. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19758. response.substr(0, response.find("\r\n")));
  19759. }
  19760. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  19761. {
  19762. auto req = "POST /test HTTP/1.1\r\n"
  19763. "Host: localhost\r\n"
  19764. "Content-Length: 5\r\n"
  19765. "Transfer-Encoding: gzip, chunked\r\n"
  19766. "Connection: close\r\n"
  19767. "\r\n"
  19768. "hello";
  19769. std::string response;
  19770. ASSERT_TRUE(send_request(1, req, &response));
  19771. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19772. response.substr(0, response.find("\r\n")));
  19773. }
  19774. }
  19775. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  19776. Server svr;
  19777. svr.Post("/test", [&](const Request &, Response &res) {
  19778. res.set_content("ok", "text/plain");
  19779. });
  19780. thread t = thread([&] { svr.listen(HOST, PORT); });
  19781. auto se = detail::scope_exit([&] {
  19782. svr.stop();
  19783. t.join();
  19784. ASSERT_FALSE(svr.is_running());
  19785. });
  19786. svr.wait_until_ready();
  19787. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  19788. // length cannot be determined, so the server must answer 400 and close
  19789. // rather than treat the request as bodyless and leave the body in the
  19790. // socket for the next request to pick up.
  19791. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  19792. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  19793. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  19794. std::string response;
  19795. ASSERT_TRUE(send_request(1, req, &response));
  19796. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19797. response.substr(0, response.find("\r\n")))
  19798. << transfer_encoding;
  19799. }
  19800. // RFC 9110 5.3: the codings may also be split across several
  19801. // Transfer-Encoding lines, which combine in the order they were received.
  19802. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  19803. // just like the single-line "chunked, gzip" above.
  19804. {
  19805. auto req = "POST /test HTTP/1.1\r\n"
  19806. "Host: localhost\r\n"
  19807. "Transfer-Encoding: chunked\r\n"
  19808. "Transfer-Encoding: gzip\r\n"
  19809. "\r\n"
  19810. "0\r\n\r\n";
  19811. std::string response;
  19812. ASSERT_TRUE(send_request(1, req, &response));
  19813. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  19814. response.substr(0, response.find("\r\n")));
  19815. }
  19816. // A sequence ending in chunked stays valid.
  19817. auto req = "POST /test HTTP/1.1\r\n"
  19818. "Host: localhost\r\n"
  19819. "Transfer-Encoding: gzip, chunked\r\n"
  19820. "Connection: close\r\n"
  19821. "\r\n"
  19822. "0\r\n\r\n";
  19823. std::string response;
  19824. ASSERT_TRUE(send_request(1, req, &response));
  19825. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19826. // ...including when it is spread over several lines.
  19827. auto split_req = "POST /test HTTP/1.1\r\n"
  19828. "Host: localhost\r\n"
  19829. "Transfer-Encoding: gzip\r\n"
  19830. "Transfer-Encoding: chunked\r\n"
  19831. "Connection: close\r\n"
  19832. "\r\n"
  19833. "0\r\n\r\n";
  19834. std::string split_response;
  19835. ASSERT_TRUE(send_request(1, split_req, &split_response));
  19836. EXPECT_EQ("HTTP/1.1 200 OK",
  19837. split_response.substr(0, split_response.find("\r\n")));
  19838. }
  19839. // Regression for issue #2450: a DELETE without Content-Length on a
  19840. // keep-alive connection must not let the post-response drain consume the
  19841. // next request's bytes.
  19842. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  19843. Server svr;
  19844. std::atomic<int> delete_count(0);
  19845. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  19846. delete_count++;
  19847. res.status = StatusCode::NoContent_204;
  19848. });
  19849. auto port = svr.bind_to_any_port(HOST);
  19850. thread t = thread([&] { svr.listen_after_bind(); });
  19851. auto se = detail::scope_exit([&] {
  19852. svr.stop();
  19853. t.join();
  19854. });
  19855. svr.wait_until_ready();
  19856. auto error = Error::Success;
  19857. auto sock = detail::create_client_socket(
  19858. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19859. /*connection_timeout_sec=*/2, 0,
  19860. /*read_timeout_sec=*/2, 0,
  19861. /*write_timeout_sec=*/2, 0, std::string(), error);
  19862. ASSERT_NE(INVALID_SOCKET, sock);
  19863. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19864. auto send_request_and_read_response = [&](const std::string &req,
  19865. std::string &out) -> bool {
  19866. auto sent = send(sock, req.data(), req.size(), 0);
  19867. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  19868. char buf[4096];
  19869. for (;;) {
  19870. auto n = recv(sock, buf, sizeof(buf), 0);
  19871. if (n <= 0) { return !out.empty(); }
  19872. out.append(buf, static_cast<size_t>(n));
  19873. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  19874. }
  19875. };
  19876. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  19877. "Host: localhost\r\n"
  19878. "\r\n";
  19879. std::string resp1;
  19880. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  19881. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  19882. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  19883. "Host: localhost\r\n"
  19884. "Connection: close\r\n"
  19885. "\r\n";
  19886. std::string resp2;
  19887. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  19888. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  19889. EXPECT_EQ(2, delete_count.load());
  19890. }
  19891. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  19892. Server svr;
  19893. svr.Post("/ingest", [&](const Request &, Response &res,
  19894. const ContentReader &content_reader) {
  19895. auto consumed = content_reader([](const char *, size_t) { return false; });
  19896. EXPECT_FALSE(consumed);
  19897. res.status = StatusCode::Conflict_409;
  19898. res.set_header("Connection", "close");
  19899. });
  19900. auto port = svr.bind_to_any_port(HOST);
  19901. thread t = thread([&] { svr.listen_after_bind(); });
  19902. auto se = detail::scope_exit([&] {
  19903. svr.stop();
  19904. t.join();
  19905. });
  19906. svr.wait_until_ready();
  19907. auto error = Error::Success;
  19908. auto sock = detail::create_client_socket(
  19909. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19910. /*connection_timeout_sec=*/2, 0,
  19911. /*read_timeout_sec=*/1, 0,
  19912. /*write_timeout_sec=*/2, 0, std::string(), error);
  19913. ASSERT_NE(INVALID_SOCKET, sock);
  19914. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19915. std::string request = "POST /ingest HTTP/1.1\r\n"
  19916. "Host: localhost\r\n"
  19917. "Transfer-Encoding: chunked\r\n"
  19918. "\r\n"
  19919. "4\r\n"
  19920. "data\r\n";
  19921. auto sent = send(sock, request.data(), request.size(), 0);
  19922. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  19923. std::string response;
  19924. ssize_t received = 0;
  19925. do {
  19926. char buf[4096];
  19927. received = recv(sock, buf, sizeof(buf), 0);
  19928. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  19929. } while (received > 0);
  19930. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  19931. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  19932. EXPECT_EQ(0, received);
  19933. }
  19934. namespace no_proxy_test {
  19935. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  19936. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  19937. // calling listen().
  19938. class ScopedServer {
  19939. public:
  19940. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  19941. ~ScopedServer() {
  19942. svr_.stop();
  19943. if (th_.joinable()) { th_.join(); }
  19944. }
  19945. Server &svr() { return svr_; }
  19946. int port() const { return port_; }
  19947. void listen() {
  19948. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19949. svr_.wait_until_ready();
  19950. }
  19951. private:
  19952. Server svr_;
  19953. std::thread th_;
  19954. int port_ = 0;
  19955. };
  19956. class ProxyAndTargetServers {
  19957. public:
  19958. ProxyAndTargetServers() {
  19959. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  19960. proxy_hits_++;
  19961. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19962. res.set_content("via-proxy", "text/plain");
  19963. });
  19964. target_.Get(".*", [this](const Request &req, Response &res) {
  19965. target_hits_++;
  19966. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19967. res.set_content("direct", "text/plain");
  19968. });
  19969. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  19970. target_port_ = target_.bind_to_any_port("127.0.0.1");
  19971. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  19972. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  19973. proxy_mock_.wait_until_ready();
  19974. target_.wait_until_ready();
  19975. }
  19976. ~ProxyAndTargetServers() {
  19977. proxy_mock_.stop();
  19978. target_.stop();
  19979. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  19980. if (target_thread_.joinable()) { target_thread_.join(); }
  19981. }
  19982. Server &proxy_mock() { return proxy_mock_; }
  19983. Server &target() { return target_; }
  19984. int proxy_port() const { return proxy_port_; }
  19985. int target_port() const { return target_port_; }
  19986. int proxy_hits() const { return proxy_hits_.load(); }
  19987. int target_hits() const { return target_hits_.load(); }
  19988. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  19989. void reset_counters() {
  19990. proxy_hits_ = 0;
  19991. target_hits_ = 0;
  19992. last_had_proxy_authz_ = false;
  19993. }
  19994. private:
  19995. Server proxy_mock_;
  19996. Server target_;
  19997. std::thread proxy_thread_;
  19998. std::thread target_thread_;
  19999. int proxy_port_ = 0;
  20000. int target_port_ = 0;
  20001. std::atomic<int> proxy_hits_{0};
  20002. std::atomic<int> target_hits_{0};
  20003. std::atomic<bool> last_had_proxy_authz_{false};
  20004. };
  20005. inline std::unique_ptr<Client> make_client(const std::string &host,
  20006. ProxyAndTargetServers &s) {
  20007. auto cli = detail::make_unique<Client>(host, s.target_port());
  20008. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  20009. cli->set_proxy("127.0.0.1", s.proxy_port());
  20010. return cli;
  20011. }
  20012. } // namespace no_proxy_test
  20013. using no_proxy_test::make_client;
  20014. using no_proxy_test::ProxyAndTargetServers;
  20015. TEST(NoProxyTest, ExactHostnameBypasses) {
  20016. ProxyAndTargetServers s;
  20017. auto cli = make_client("example.com", s);
  20018. cli->set_no_proxy({"example.com"});
  20019. auto res = cli->Get("/");
  20020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20021. EXPECT_EQ(0, s.proxy_hits());
  20022. EXPECT_EQ(1, s.target_hits());
  20023. }
  20024. TEST(NoProxyTest, SubdomainBypasses) {
  20025. ProxyAndTargetServers s;
  20026. auto cli = make_client("foo.example.com", s);
  20027. cli->set_no_proxy({"example.com"});
  20028. auto res = cli->Get("/");
  20029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20030. EXPECT_EQ(0, s.proxy_hits());
  20031. EXPECT_EQ(1, s.target_hits());
  20032. }
  20033. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  20034. // Regression guard: "evilexample.com" must not be considered a subdomain
  20035. // of "example.com". Without the dot-boundary rule, a naive endsWith
  20036. // check would let traffic bypass the proxy and leak credentials direct
  20037. // to the attacker host.
  20038. ProxyAndTargetServers s;
  20039. auto cli = make_client("evilexample.com", s);
  20040. cli->set_no_proxy({"example.com"});
  20041. auto res = cli->Get("/");
  20042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20043. EXPECT_GE(s.proxy_hits(), 1);
  20044. EXPECT_EQ(0, s.target_hits());
  20045. }
  20046. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  20047. ProxyAndTargetServers s;
  20048. auto cli = make_client("example.com.evil.com", s);
  20049. cli->set_no_proxy({"example.com"});
  20050. auto res = cli->Get("/");
  20051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20052. EXPECT_GE(s.proxy_hits(), 1);
  20053. EXPECT_EQ(0, s.target_hits());
  20054. }
  20055. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  20056. ProxyAndTargetServers s;
  20057. auto cli = make_client("example.com", s);
  20058. cli->set_no_proxy({".example.com"});
  20059. auto res = cli->Get("/");
  20060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20061. EXPECT_EQ(0, s.proxy_hits());
  20062. EXPECT_EQ(1, s.target_hits());
  20063. }
  20064. TEST(NoProxyTest, CaseInsensitiveHostname) {
  20065. ProxyAndTargetServers s;
  20066. auto cli = make_client("Example.COM", s);
  20067. cli->set_no_proxy({"EXAMPLE.com"});
  20068. auto res = cli->Get("/");
  20069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20070. EXPECT_EQ(0, s.proxy_hits());
  20071. EXPECT_EQ(1, s.target_hits());
  20072. }
  20073. TEST(NoProxyTest, TrailingDotIsNormalized) {
  20074. ProxyAndTargetServers s;
  20075. auto cli = make_client("example.com.", s);
  20076. cli->set_no_proxy({"example.com"});
  20077. auto res = cli->Get("/");
  20078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20079. EXPECT_EQ(0, s.proxy_hits());
  20080. EXPECT_EQ(1, s.target_hits());
  20081. }
  20082. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  20083. // Trailing dots must be normalized on BOTH sides — host and entry.
  20084. // An implementation that only strips the host-side trailing dot would
  20085. // fail to match host "example.com" against entry "example.com." because
  20086. // a literal substring search would compare 11 chars against 12.
  20087. ProxyAndTargetServers s;
  20088. auto cli = make_client("example.com", s);
  20089. cli->set_no_proxy({"example.com."});
  20090. auto res = cli->Get("/");
  20091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20092. EXPECT_EQ(0, s.proxy_hits());
  20093. EXPECT_EQ(1, s.target_hits());
  20094. }
  20095. TEST(NoProxyTest, WildcardBypassesEverything) {
  20096. ProxyAndTargetServers s;
  20097. auto cli = make_client("anything.invalid.test", s);
  20098. cli->set_no_proxy({"*"});
  20099. auto res = cli->Get("/");
  20100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20101. EXPECT_EQ(0, s.proxy_hits());
  20102. EXPECT_EQ(1, s.target_hits());
  20103. }
  20104. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  20105. ProxyAndTargetServers s;
  20106. Client cli("127.0.0.1", s.target_port());
  20107. cli.set_proxy("127.0.0.1", s.proxy_port());
  20108. cli.set_no_proxy({"127.0.0.1"});
  20109. auto res = cli.Get("/");
  20110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20111. EXPECT_EQ(0, s.proxy_hits());
  20112. EXPECT_EQ(1, s.target_hits());
  20113. }
  20114. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  20115. ProxyAndTargetServers s;
  20116. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  20117. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  20118. cli.set_proxy("127.0.0.1", s.proxy_port());
  20119. cli.set_no_proxy({"::1"});
  20120. auto res = cli.Get("/");
  20121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20122. EXPECT_EQ(0, s.proxy_hits());
  20123. EXPECT_EQ(1, s.target_hits());
  20124. }
  20125. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  20126. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  20127. // must still be recognized as IPv6 for CIDR matching. Implementations
  20128. // that detect IPv6 only when the host begins with '[' would parse the
  20129. // host as a hostname and miss the match.
  20130. ProxyAndTargetServers s;
  20131. Client cli("fe80::1", s.target_port());
  20132. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20133. cli.set_proxy("127.0.0.1", s.proxy_port());
  20134. cli.set_no_proxy({"fe80::/10"});
  20135. auto res = cli.Get("/");
  20136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20137. EXPECT_EQ(0, s.proxy_hits());
  20138. EXPECT_EQ(1, s.target_hits());
  20139. }
  20140. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  20141. ProxyAndTargetServers s;
  20142. Client cli("::1", s.target_port());
  20143. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  20144. cli.set_proxy("127.0.0.1", s.proxy_port());
  20145. cli.set_no_proxy({"[::1]"});
  20146. auto res = cli.Get("/");
  20147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20148. EXPECT_EQ(0, s.proxy_hits());
  20149. EXPECT_EQ(1, s.target_hits());
  20150. }
  20151. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  20152. ProxyAndTargetServers s;
  20153. Client cli("fe80::1", s.target_port());
  20154. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20155. cli.set_proxy("127.0.0.1", s.proxy_port());
  20156. cli.set_no_proxy({"[fe80::]/10"});
  20157. auto res = cli.Get("/");
  20158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20159. EXPECT_EQ(0, s.proxy_hits());
  20160. EXPECT_EQ(1, s.target_hits());
  20161. }
  20162. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  20163. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  20164. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  20165. // tricks via address-family conversion.
  20166. ProxyAndTargetServers s;
  20167. Client cli("::ffff:127.0.0.1", s.target_port());
  20168. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  20169. cli.set_proxy("127.0.0.1", s.proxy_port());
  20170. cli.set_no_proxy({"127.0.0.1"});
  20171. auto res = cli.Get("/");
  20172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20173. EXPECT_GE(s.proxy_hits(), 1);
  20174. EXPECT_EQ(0, s.target_hits());
  20175. }
  20176. TEST(NoProxyTest, IPv4CidrMatch) {
  20177. ProxyAndTargetServers s;
  20178. Client cli("127.0.0.1", s.target_port());
  20179. cli.set_proxy("127.0.0.1", s.proxy_port());
  20180. cli.set_no_proxy({"127.0.0.0/8"});
  20181. auto res = cli.Get("/");
  20182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20183. EXPECT_EQ(0, s.proxy_hits());
  20184. EXPECT_EQ(1, s.target_hits());
  20185. }
  20186. TEST(NoProxyTest, IPv4CidrNonMatch) {
  20187. ProxyAndTargetServers s;
  20188. Client cli("127.0.0.1", s.target_port());
  20189. cli.set_proxy("127.0.0.1", s.proxy_port());
  20190. cli.set_no_proxy({"10.0.0.0/8"});
  20191. auto res = cli.Get("/");
  20192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20193. EXPECT_GE(s.proxy_hits(), 1);
  20194. EXPECT_EQ(0, s.target_hits());
  20195. }
  20196. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  20197. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  20198. // IPv4 target matches.
  20199. ProxyAndTargetServers s;
  20200. Client cli("127.0.0.1", s.target_port());
  20201. cli.set_proxy("127.0.0.1", s.proxy_port());
  20202. cli.set_no_proxy({"0.0.0.0/0"});
  20203. auto res = cli.Get("/");
  20204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20205. EXPECT_EQ(0, s.proxy_hits());
  20206. EXPECT_EQ(1, s.target_hits());
  20207. }
  20208. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  20209. ProxyAndTargetServers s;
  20210. Client cli("127.0.0.1", s.target_port());
  20211. cli.set_proxy("127.0.0.1", s.proxy_port());
  20212. cli.set_no_proxy({"127.0.0.1"});
  20213. auto res = cli.Get("/");
  20214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20215. EXPECT_EQ(0, s.proxy_hits());
  20216. EXPECT_EQ(1, s.target_hits());
  20217. }
  20218. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  20219. ProxyAndTargetServers s;
  20220. Client cli("127.0.0.1", s.target_port());
  20221. cli.set_proxy("127.0.0.1", s.proxy_port());
  20222. cli.set_no_proxy({"127.0.0.0/33"});
  20223. auto res = cli.Get("/");
  20224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20225. EXPECT_GE(s.proxy_hits(), 1);
  20226. EXPECT_EQ(0, s.target_hits());
  20227. }
  20228. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  20229. // Empty prefix after the slash must be rejected, not silently treated as /32.
  20230. ProxyAndTargetServers s;
  20231. Client cli("127.0.0.1", s.target_port());
  20232. cli.set_proxy("127.0.0.1", s.proxy_port());
  20233. cli.set_no_proxy({"127.0.0.1/"});
  20234. auto res = cli.Get("/");
  20235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20236. EXPECT_GE(s.proxy_hits(), 1);
  20237. EXPECT_EQ(0, s.target_hits());
  20238. }
  20239. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  20240. ProxyAndTargetServers s;
  20241. auto cli = make_client("internal.corp", s);
  20242. cli->set_proxy_basic_auth("u", "p");
  20243. cli->set_no_proxy({"internal.corp"});
  20244. auto res = cli->Get("/");
  20245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20246. EXPECT_EQ(1, s.target_hits());
  20247. EXPECT_EQ(0, s.proxy_hits());
  20248. EXPECT_FALSE(s.last_had_proxy_authz())
  20249. << "Proxy-Authorization must not be sent direct to the target";
  20250. }
  20251. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  20252. ProxyAndTargetServers s;
  20253. auto cli = make_client("public.example", s);
  20254. cli->set_proxy_basic_auth("u", "p");
  20255. cli->set_no_proxy({"internal.corp"}); // does not match
  20256. auto res = cli->Get("/");
  20257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20258. EXPECT_GE(s.proxy_hits(), 1);
  20259. EXPECT_TRUE(s.last_had_proxy_authz());
  20260. }
  20261. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  20262. ProxyAndTargetServers s;
  20263. auto cli = make_client("anything.test", s);
  20264. auto res = cli->Get("/");
  20265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20266. EXPECT_GE(s.proxy_hits(), 1);
  20267. EXPECT_EQ(0, s.target_hits());
  20268. }
  20269. TEST(NoProxyTest, PortSpecificEntryRejected) {
  20270. ProxyAndTargetServers s;
  20271. auto cli = make_client("example.com", s);
  20272. cli->set_no_proxy({"example.com:8080"});
  20273. auto res = cli->Get("/");
  20274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20275. EXPECT_GE(s.proxy_hits(), 1);
  20276. EXPECT_EQ(0, s.target_hits());
  20277. }
  20278. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  20279. ProxyAndTargetServers s;
  20280. auto cli = make_client("anything.test", s);
  20281. cli->set_no_proxy({"", " ", "\t"});
  20282. auto res = cli->Get("/");
  20283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20284. EXPECT_GE(s.proxy_hits(), 1);
  20285. EXPECT_EQ(0, s.target_hits());
  20286. }
  20287. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  20288. // An entry with leading/trailing whitespace must still match — env-style
  20289. // values are commonly pasted with stray spaces and an implementation
  20290. // that feeds the raw token directly to inet_pton would fail to match
  20291. // valid CIDRs because of the spaces.
  20292. ProxyAndTargetServers s;
  20293. Client cli("127.0.0.1", s.target_port());
  20294. cli.set_proxy("127.0.0.1", s.proxy_port());
  20295. cli.set_no_proxy({" 127.0.0.0/8 "});
  20296. auto res = cli.Get("/");
  20297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20298. EXPECT_EQ(0, s.proxy_hits());
  20299. EXPECT_EQ(1, s.target_hits());
  20300. }
  20301. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  20302. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  20303. // go direct and must NOT carry Proxy-Authorization.
  20304. std::atomic<int> proxy_hits{0};
  20305. std::atomic<int> target_hits{0};
  20306. std::atomic<bool> target_saw_authz{false};
  20307. no_proxy_test::ScopedServer proxy_mock, target;
  20308. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20309. proxy_hits++;
  20310. res.status = 302;
  20311. res.set_header("Location", "http://127.0.0.1:" +
  20312. std::to_string(target.port()) + "/landed");
  20313. });
  20314. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20315. target_hits++;
  20316. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  20317. res.set_content("direct", "text/plain");
  20318. });
  20319. proxy_mock.listen();
  20320. target.listen();
  20321. Client cli("public.example", target.port());
  20322. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20323. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20324. cli.set_proxy_basic_auth("u", "p");
  20325. cli.set_no_proxy({"127.0.0.1"});
  20326. cli.set_follow_location(true);
  20327. auto res = cli.Get("/redir");
  20328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20329. EXPECT_GE(proxy_hits.load(), 1);
  20330. EXPECT_GE(target_hits.load(), 1);
  20331. EXPECT_FALSE(target_saw_authz.load());
  20332. }
  20333. #ifdef CPPHTTPLIB_SSL_ENABLED
  20334. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  20335. // Direct origin replying 407 must not trigger the digest retry; otherwise
  20336. // proxy creds would be sent to the (possibly hostile) origin.
  20337. std::atomic<int> target_hits{0};
  20338. std::atomic<bool> target_saw_proxy_authz{false};
  20339. no_proxy_test::ScopedServer target;
  20340. target.svr().Get(".*", [&](const Request &req, Response &res) {
  20341. target_hits++;
  20342. if (req.has_header("Proxy-Authorization")) {
  20343. target_saw_proxy_authz = true;
  20344. }
  20345. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20346. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  20347. "nonce=\"abc\", algorithm=MD5");
  20348. });
  20349. target.listen();
  20350. // The proxy address is set to the target's port: the bypass MUST kick in;
  20351. // if it doesn't, the test still routes "via proxy" to the same server and
  20352. // the Proxy-Authorization assertion below catches the leak.
  20353. Client cli("evil.example", target.port());
  20354. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  20355. cli.set_proxy("127.0.0.1", target.port());
  20356. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20357. cli.set_no_proxy({"evil.example"});
  20358. auto res = cli.Get("/x");
  20359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20360. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20361. EXPECT_EQ(1, target_hits.load());
  20362. EXPECT_FALSE(target_saw_proxy_authz.load());
  20363. }
  20364. #endif
  20365. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  20366. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  20367. std::atomic<int> proxy_hits{0};
  20368. std::atomic<int> bypass_hits{0};
  20369. std::atomic<bool> proxy_saw_c_url{false};
  20370. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  20371. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  20372. proxy_hits++;
  20373. if (req.path.find("/start") != std::string::npos) {
  20374. res.status = 302;
  20375. res.set_header("Location", "http://127.0.0.1:" +
  20376. std::to_string(bypass_server.port()) +
  20377. "/middle");
  20378. return;
  20379. }
  20380. if (req.path.find("/end") != std::string::npos) {
  20381. proxy_saw_c_url = true;
  20382. res.set_content("c-via-proxy", "text/plain");
  20383. return;
  20384. }
  20385. res.set_content("unexpected", "text/plain");
  20386. });
  20387. // public.example's "advertised" port is arbitrary (the request never lands
  20388. // there — it goes through the proxy), but use a dynamic value to stay
  20389. // friendly with sharded parallel runs.
  20390. int public_port = bypass_server.port();
  20391. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  20392. bypass_hits++;
  20393. res.status = 302;
  20394. res.set_header("Location", "http://public.example:" +
  20395. std::to_string(public_port) + "/end");
  20396. });
  20397. proxy_mock.listen();
  20398. bypass_server.listen();
  20399. Client cli("public.example", public_port);
  20400. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20401. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20402. cli.set_no_proxy({"127.0.0.1"});
  20403. cli.set_follow_location(true);
  20404. auto res = cli.Get("/start");
  20405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20406. EXPECT_EQ(StatusCode::OK_200, res->status);
  20407. EXPECT_EQ("c-via-proxy", res->body);
  20408. EXPECT_GE(proxy_hits.load(), 2);
  20409. EXPECT_GE(bypass_hits.load(), 1);
  20410. EXPECT_TRUE(proxy_saw_c_url.load());
  20411. }
  20412. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  20413. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  20414. // request reconnects to the correct endpoint.
  20415. std::atomic<int> proxy_hits{0};
  20416. std::atomic<int> target_hits{0};
  20417. no_proxy_test::ScopedServer proxy_mock, target;
  20418. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  20419. proxy_hits++;
  20420. res.set_content("via-proxy", "text/plain");
  20421. });
  20422. target.svr().Get(".*", [&](const Request &, Response &res) {
  20423. target_hits++;
  20424. res.set_content("direct", "text/plain");
  20425. });
  20426. proxy_mock.listen();
  20427. target.listen();
  20428. Client cli("public.example", target.port());
  20429. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  20430. cli.set_proxy("127.0.0.1", proxy_mock.port());
  20431. cli.set_keep_alive(true);
  20432. auto res1 = cli.Get("/a");
  20433. ASSERT_TRUE(res1);
  20434. EXPECT_EQ("via-proxy", res1->body);
  20435. EXPECT_EQ(1, proxy_hits.load());
  20436. EXPECT_EQ(0, target_hits.load());
  20437. cli.set_no_proxy({"public.example"});
  20438. auto res2 = cli.Get("/b");
  20439. ASSERT_TRUE(res2);
  20440. EXPECT_EQ("direct", res2->body);
  20441. EXPECT_EQ(1, proxy_hits.load());
  20442. EXPECT_EQ(1, target_hits.load());
  20443. }
  20444. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  20445. namespace proxy_tunnel_test {
  20446. // SSLServer counterpart to no_proxy_test::ScopedServer.
  20447. class ScopedSSLServer {
  20448. public:
  20449. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  20450. port_ = svr_.bind_to_any_port("127.0.0.1");
  20451. }
  20452. ~ScopedSSLServer() {
  20453. svr_.stop();
  20454. if (th_.joinable()) { th_.join(); }
  20455. }
  20456. SSLServer &svr() { return svr_; }
  20457. int port() const { return port_; }
  20458. void listen() {
  20459. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20460. svr_.wait_until_ready();
  20461. }
  20462. private:
  20463. SSLServer svr_;
  20464. std::thread th_;
  20465. int port_ = 0;
  20466. };
  20467. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  20468. class ScopedConnectProxy {
  20469. public:
  20470. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  20471. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  20472. if (listen_fd_ < 0) { return; }
  20473. int yes = 1;
  20474. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  20475. sockaddr_in a{};
  20476. a.sin_family = AF_INET;
  20477. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20478. a.sin_port = 0;
  20479. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  20480. return;
  20481. }
  20482. socklen_t alen = sizeof(a);
  20483. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  20484. 0) {
  20485. return;
  20486. }
  20487. port_ = ntohs(a.sin_port);
  20488. if (::listen(listen_fd_, 1) != 0) { return; }
  20489. th_ = std::thread([this] { run(); });
  20490. }
  20491. ~ScopedConnectProxy() {
  20492. stop_ = true;
  20493. if (listen_fd_ >= 0) {
  20494. ::shutdown(listen_fd_, SHUT_RDWR);
  20495. ::close(listen_fd_);
  20496. }
  20497. if (th_.joinable()) { th_.join(); }
  20498. }
  20499. int port() const { return port_; }
  20500. int connect_hits() const { return connect_hits_.load(); }
  20501. private:
  20502. void run() {
  20503. while (!stop_.load()) {
  20504. fd_set rfds;
  20505. FD_ZERO(&rfds);
  20506. FD_SET(listen_fd_, &rfds);
  20507. timeval tv{0, 100 * 1000};
  20508. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  20509. if (sel <= 0) { continue; }
  20510. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  20511. if (client_fd < 0) { continue; }
  20512. std::string req;
  20513. char buf[2048];
  20514. while (req.find("\r\n\r\n") == std::string::npos) {
  20515. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  20516. if (n <= 0) { break; }
  20517. req.append(buf, static_cast<size_t>(n));
  20518. }
  20519. if (req.compare(0, 7, "CONNECT") != 0) {
  20520. ::close(client_fd);
  20521. continue;
  20522. }
  20523. connect_hits_++;
  20524. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  20525. ::send(client_fd, ok, std::strlen(ok), 0);
  20526. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  20527. sockaddr_in o{};
  20528. o.sin_family = AF_INET;
  20529. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  20530. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  20531. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  20532. 0) {
  20533. ::close(client_fd);
  20534. ::close(origin_fd);
  20535. continue;
  20536. }
  20537. auto forward = [](int from, int to) {
  20538. char b[8192];
  20539. for (;;) {
  20540. ssize_t n = ::recv(from, b, sizeof(b), 0);
  20541. if (n <= 0) { break; }
  20542. ssize_t off = 0;
  20543. while (off < n) {
  20544. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  20545. if (s <= 0) {
  20546. off = n;
  20547. break;
  20548. }
  20549. off += s;
  20550. }
  20551. }
  20552. ::shutdown(to, SHUT_WR);
  20553. };
  20554. std::thread t1([&] { forward(client_fd, origin_fd); });
  20555. std::thread t2([&] { forward(origin_fd, client_fd); });
  20556. t1.join();
  20557. t2.join();
  20558. ::close(client_fd);
  20559. ::close(origin_fd);
  20560. }
  20561. }
  20562. int forward_port_ = -1;
  20563. int listen_fd_ = -1;
  20564. int port_ = 0;
  20565. std::thread th_;
  20566. std::atomic<bool> stop_{false};
  20567. std::atomic<int> connect_hits_{0};
  20568. };
  20569. } // namespace proxy_tunnel_test
  20570. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  20571. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  20572. // retry; otherwise proxy creds would be sent to the origin.
  20573. std::atomic<int> origin_hits{0};
  20574. std::atomic<bool> origin_saw_proxy_authz{false};
  20575. proxy_tunnel_test::ScopedSSLServer origin;
  20576. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  20577. origin_hits++;
  20578. if (req.has_header("Proxy-Authorization")) {
  20579. origin_saw_proxy_authz = true;
  20580. }
  20581. res.status = StatusCode::ProxyAuthenticationRequired_407;
  20582. res.set_header("Proxy-Authenticate",
  20583. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  20584. "algorithm=MD5");
  20585. });
  20586. origin.listen();
  20587. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  20588. ASSERT_NE(0, proxy.port());
  20589. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  20590. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  20591. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  20592. // and answer with its own status, making this test flaky.
  20593. SSLClient cli("127.0.0.1", origin.port());
  20594. cli.enable_server_certificate_verification(false);
  20595. cli.set_proxy("127.0.0.1", proxy.port());
  20596. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  20597. auto res = cli.Get("/x");
  20598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20599. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20600. EXPECT_EQ(1, origin_hits.load());
  20601. EXPECT_FALSE(origin_saw_proxy_authz.load());
  20602. EXPECT_EQ(1, proxy.connect_hits());
  20603. }
  20604. #endif