test.cc 754 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(ClientTest, MoveConstructible) {
  305. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  306. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  307. }
  308. TEST(ClientTest, MoveAssignable) {
  309. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  310. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  311. }
  312. #ifdef _WIN32
  313. TEST(StartupTest, WSAStartup) {
  314. WSADATA wsaData;
  315. int ret = WSAStartup(0x0002, &wsaData);
  316. ASSERT_EQ(0, ret);
  317. }
  318. #endif
  319. TEST(DecodePathTest, PercentCharacter) {
  320. EXPECT_EQ(
  321. decode_path_component(
  322. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  323. U8("descrip=Gastos áéíóúñÑ 6"));
  324. }
  325. TEST(DecodePathTest, PercentCharacterNUL) {
  326. string expected;
  327. expected.push_back('x');
  328. expected.push_back('\0');
  329. expected.push_back('x');
  330. EXPECT_EQ(decode_path_component("x%00x"), expected);
  331. }
  332. TEST(DecodePathTest, UnicodeEncoding) {
  333. // %u0041 = 'A' (1-byte UTF-8)
  334. EXPECT_EQ("A", decode_path_component("%u0041"));
  335. // %u00E9 = 'é' (2-byte UTF-8)
  336. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  337. // %u3042 = 'あ' (3-byte UTF-8)
  338. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  339. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  340. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  341. // %uD800 = surrogate (invalid, silently dropped)
  342. EXPECT_EQ("", decode_path_component("%uD800"));
  343. }
  344. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  345. // A sign or whitespace inside the two-character escape window must not be
  346. // accepted as a valid percent-encoding; the sequence is passed through
  347. // literally, matching decode_uri_component / decode_path_component.
  348. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  349. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  350. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  351. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  352. // Well-formed escapes still decode.
  353. EXPECT_EQ("-", decode_query_component("%2D", false));
  354. EXPECT_EQ("A", decode_query_component("%41", false));
  355. }
  356. TEST(SanitizeFilenameTest, VariousPatterns) {
  357. // Path traversal
  358. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  359. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  360. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  361. // Normal and edge cases
  362. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  363. EXPECT_EQ("filename.txt",
  364. httplib::sanitize_filename("/path/to/filename.txt"));
  365. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  366. EXPECT_EQ("", httplib::sanitize_filename(".."));
  367. EXPECT_EQ("", httplib::sanitize_filename(""));
  368. // Null bytes stripped
  369. EXPECT_EQ("safe.txt",
  370. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  371. // Whitespace-only rejected
  372. EXPECT_EQ("", httplib::sanitize_filename(" "));
  373. }
  374. // Forward declaration (see the base64_encode note below): split builds move the
  375. // definition into httplib.cc, so re-declaring it here lets the test link.
  376. namespace httplib {
  377. namespace detail {
  378. bool is_chunked_transfer_encoding(const Headers &headers);
  379. } // namespace detail
  380. } // namespace httplib
  381. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  382. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  383. auto make = [](std::initializer_list<const char *> lines) {
  384. Headers h;
  385. for (auto te : lines) {
  386. if (te) { h.emplace("Transfer-Encoding", te); }
  387. }
  388. return h;
  389. };
  390. // Sole coding, matched case-insensitively.
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  392. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  393. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  394. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  395. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  396. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  397. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  398. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  399. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  400. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  401. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  403. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  404. // were received, into one list. Headers preserves that order, so the answer
  405. // is decided by the last coding of the last line and the order the lines
  406. // arrived in is significant.
  407. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  408. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  409. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  410. // The split can fall anywhere in the list.
  411. EXPECT_TRUE(
  412. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  413. EXPECT_FALSE(
  414. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  415. // A trailing line naming no coding leaves the list ending in nothing, so it
  416. // must not inherit the chunked from the line before it.
  417. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  418. }
  419. // Forward declaration: in split builds split.py strips `inline` and moves the
  420. // definition into httplib.cc, so detail::base64_encode is not visible from the
  421. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  422. // in both header-only and split builds.
  423. namespace httplib {
  424. namespace detail {
  425. std::string base64_encode(const std::string &in);
  426. } // namespace detail
  427. } // namespace httplib
  428. TEST(Base64EncodeTest, KnownAnswers) {
  429. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  430. // where the accumulator's top bit is already set before the next shift.
  431. EXPECT_EQ("", detail::base64_encode(""));
  432. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  433. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  434. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  435. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  436. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  437. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  438. // High bytes keep the top bit set across several rounds.
  439. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  440. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  441. }
  442. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  447. string reservedCharacters = ";,/?:@&=+$";
  448. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  449. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  450. }
  451. TEST(ClientQueryOrder, PreserveOrder) {
  452. // This test reproduces Issue #2259: client may reorder query parameters
  453. // when sending a GET request. The expected behavior is that the client
  454. // preserves the original query string order when the caller supplied it
  455. // as part of the path.
  456. Server svr;
  457. svr.Get("/", [&](const Request &req, Response &res) {
  458. // Echo back the raw target so the test can assert ordering
  459. res.set_content(req.target, "text/plain");
  460. });
  461. std::thread t{[&] { svr.listen(HOST, PORT); }};
  462. auto se = detail::scope_exit([&] {
  463. svr.stop();
  464. t.join();
  465. ASSERT_FALSE(svr.is_running());
  466. });
  467. svr.wait_until_ready();
  468. Client cli(HOST, PORT);
  469. ASSERT_TRUE(cli.is_valid());
  470. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  471. auto res = cli.Get(original);
  472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  473. // Expect the echoed target to exactly match the original path (order
  474. // preserved)
  475. EXPECT_EQ(res->body, original);
  476. }
  477. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  478. string chineseCharacters = U8("中国語");
  479. string russianCharacters = U8("дом");
  480. string brazilianCharacters = U8("óculos");
  481. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  482. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  483. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  484. "%D0%B4%D0%BE%D0%BC");
  485. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  486. }
  487. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  488. string unescapedCharacters = "-_.!~*'()";
  489. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  490. }
  491. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  492. string reservedCharacters = ";,/?:@&=+$";
  493. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  494. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  495. }
  496. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  497. string chineseCharacters = U8("中国語");
  498. string russianCharacters = U8("дом");
  499. string brazilianCharacters = U8("óculos");
  500. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  501. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  502. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  503. "%D0%B4%D0%BE%D0%BC");
  504. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  505. }
  506. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  507. // Issue #2082 use case: encoding path component with ampersand
  508. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  509. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  510. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  511. }
  512. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  513. string unescapedCharacters = "-_.!~*'()";
  514. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  515. }
  516. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  517. string reservedCharacters = ";,/?:@&=+$#";
  518. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  519. }
  520. TEST(EncodeUriTest, TestUTF8Characters) {
  521. string chineseCharacters = U8("中国語");
  522. string russianCharacters = U8("дом");
  523. string brazilianCharacters = U8("óculos");
  524. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  525. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  526. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  527. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  528. }
  529. TEST(EncodeUriTest, TestCompleteUri) {
  530. string uri =
  531. "https://example.com/path/to/resource?query=value&param=test#fragment";
  532. EXPECT_EQ(
  533. httplib::encode_uri(uri),
  534. "https://example.com/path/to/resource?query=value&param=test#fragment");
  535. }
  536. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  537. string uri =
  538. "https://example.com/path with spaces/file name.html?q=hello world";
  539. EXPECT_EQ(httplib::encode_uri(uri),
  540. "https://example.com/path%20with%20spaces/"
  541. "file%20name.html?q=hello%20world");
  542. }
  543. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  544. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  545. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  546. }
  547. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  548. string unescapedCharacters = "-_.!~*'()";
  549. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  550. }
  551. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  552. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  553. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  554. string encodedBrazilian = "%C3%B3culos";
  555. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  556. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  557. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  558. }
  559. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  560. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  561. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  562. "Piri Tommy Villiers - on & on");
  563. }
  564. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  565. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  566. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  567. }
  568. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  569. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  570. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  571. }
  572. TEST(DecodeUriTest, TestUTF8Characters) {
  573. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  574. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  575. string encodedBrazilian = "%C3%B3culos";
  576. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  577. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  578. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  579. }
  580. TEST(DecodeUriTest, TestCompleteUri) {
  581. string encodedUri = "https://example.com/path%20with%20spaces/"
  582. "file%20name.html?q=hello%20world";
  583. EXPECT_EQ(
  584. httplib::decode_uri(encodedUri),
  585. "https://example.com/path with spaces/file name.html?q=hello world");
  586. }
  587. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  588. string original =
  589. "https://example.com/path with spaces/file name.html?q=hello world";
  590. string encoded = httplib::encode_uri(original);
  591. string decoded = httplib::decode_uri(encoded);
  592. EXPECT_EQ(decoded, original);
  593. }
  594. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  595. // decode_uri is the inverse of encode_uri: an escaped reserved character
  596. // stays encoded so it is not promoted into a real delimiter, while
  597. // non-reserved escapes still decode (like JS decodeURI).
  598. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  599. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  600. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  601. "%3F%3A%40%26%3D%2B%24%2C%3B");
  602. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  603. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  604. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  605. "http://example.com/a%2Fb");
  606. // decode_uri_component still decodes the reserved character.
  607. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  608. }
  609. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  610. string original = "Piri Tommy Villiers - on & on";
  611. string encoded = httplib::encode_uri_component(original);
  612. string decoded = httplib::decode_uri_component(encoded);
  613. EXPECT_EQ(decoded, original);
  614. }
  615. TEST(TrimTests, TrimStringTests) {
  616. EXPECT_EQ("abc", detail::trim_copy("abc"));
  617. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  618. EXPECT_TRUE(detail::trim_copy("").empty());
  619. }
  620. TEST(AsciiTest, LocaleIndependentClassification) {
  621. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  622. // which consult the global C locale: std::isalnum(0xC5) can return true
  623. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  624. // helpers must classify every byte by the ASCII grammar alone.
  625. for (int i = 0; i < 256; i++) {
  626. auto c = static_cast<char>(i);
  627. auto is_digit = i >= '0' && i <= '9';
  628. auto is_upper = i >= 'A' && i <= 'Z';
  629. auto is_lower = i >= 'a' && i <= 'z';
  630. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  631. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  632. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  633. << "byte " << i;
  634. }
  635. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  636. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  637. // Non-ASCII bytes must be percent-encoded, never passed through as
  638. // alphanumeric.
  639. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  640. }
  641. TEST(FromCharsTest, Double) {
  642. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  643. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  644. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  645. auto parse = [](const std::string &s, double &v) {
  646. return detail::from_chars(s.data(), s.data() + s.size(), v);
  647. };
  648. double v = -1.0;
  649. // Representative quality values.
  650. EXPECT_EQ(parse("0", v).ec, std::errc{});
  651. EXPECT_DOUBLE_EQ(v, 0.0);
  652. EXPECT_EQ(parse("1", v).ec, std::errc{});
  653. EXPECT_DOUBLE_EQ(v, 1.0);
  654. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  655. EXPECT_DOUBLE_EQ(v, 0.8);
  656. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  657. EXPECT_DOUBLE_EQ(v, 0.001);
  658. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  659. EXPECT_DOUBLE_EQ(v, 1.0);
  660. // A missing integer or fractional part is tolerated.
  661. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  662. EXPECT_DOUBLE_EQ(v, 0.5);
  663. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  664. EXPECT_DOUBLE_EQ(v, 5.0);
  665. // Values outside [0, 1] still parse; the caller range-checks them.
  666. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  667. EXPECT_DOUBLE_EQ(v, 123.456);
  668. // Stops at the first byte that is not part of the number and reports where.
  669. std::string trailing = "0.9, text/html";
  670. auto r = parse(trailing, v);
  671. EXPECT_EQ(r.ec, std::errc{});
  672. EXPECT_DOUBLE_EQ(v, 0.9);
  673. EXPECT_EQ(*r.ptr, ',');
  674. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  675. // outright, and an 'e'/'E' simply ends the number.
  676. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  677. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  678. std::string exp_input = "1.5e3";
  679. r = parse(exp_input, v);
  680. EXPECT_EQ(r.ec, std::errc{});
  681. EXPECT_DOUBLE_EQ(v, 1.5);
  682. EXPECT_EQ(*r.ptr, 'e');
  683. // Invalid inputs.
  684. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  685. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  686. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  687. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  688. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  689. // Pathological but well-formed inputs must stay bounded (no overflow, no
  690. // out-of-bounds table access) and stay within [0, 1] for the caller.
  691. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  692. std::errc{});
  693. EXPECT_DOUBLE_EQ(v, 0.0);
  694. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  695. std::errc{});
  696. EXPECT_GE(v, 0.0);
  697. EXPECT_LE(v, 1.0);
  698. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  699. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  700. }
  701. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  702. // Simple case without quality values
  703. std::vector<std::string> result1;
  704. EXPECT_TRUE(detail::parse_accept_header(
  705. "text/html,application/json,text/plain", result1));
  706. EXPECT_EQ(result1.size(), 3U);
  707. EXPECT_EQ(result1[0], "text/html");
  708. EXPECT_EQ(result1[1], "application/json");
  709. EXPECT_EQ(result1[2], "text/plain");
  710. // With quality values
  711. std::vector<std::string> result2;
  712. EXPECT_TRUE(detail::parse_accept_header(
  713. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  714. EXPECT_EQ(result2.size(), 3U);
  715. EXPECT_EQ(result2[0], "application/json"); // highest q value
  716. EXPECT_EQ(result2[1], "text/html");
  717. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  718. }
  719. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  720. // Mixed with and without quality values
  721. std::vector<std::string> result;
  722. EXPECT_TRUE(detail::parse_accept_header(
  723. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  724. EXPECT_EQ(result.size(), 3U);
  725. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  726. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  727. EXPECT_EQ(result[2], "application/json"); // q=0.5
  728. }
  729. TEST(ParseAcceptHeaderTest, EdgeCases) {
  730. // Empty header
  731. std::vector<std::string> empty_result;
  732. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  733. EXPECT_TRUE(empty_result.empty());
  734. // Single type
  735. std::vector<std::string> single_result;
  736. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  737. EXPECT_EQ(single_result.size(), 1U);
  738. EXPECT_EQ(single_result[0], "application/json");
  739. // Wildcard types
  740. std::vector<std::string> wildcard_result;
  741. EXPECT_TRUE(detail::parse_accept_header(
  742. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  743. EXPECT_EQ(wildcard_result.size(), 3U);
  744. EXPECT_EQ(wildcard_result[0], "application/json");
  745. EXPECT_EQ(wildcard_result[1], "text/*");
  746. EXPECT_EQ(wildcard_result[2], "*/*");
  747. }
  748. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  749. // Common browser Accept header
  750. std::vector<std::string> browser_result;
  751. EXPECT_TRUE(
  752. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  753. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  754. browser_result));
  755. EXPECT_EQ(browser_result.size(), 6U);
  756. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  757. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  758. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  759. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  760. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  761. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  762. // API client header
  763. std::vector<std::string> api_result;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  766. api_result));
  767. EXPECT_EQ(api_result.size(), 3U);
  768. EXPECT_EQ(api_result[0], "application/json");
  769. EXPECT_EQ(api_result[1], "application/xml");
  770. EXPECT_EQ(api_result[2], "text/plain");
  771. }
  772. TEST(ParseAcceptHeaderTest, SpecialCases) {
  773. // Quality value with 3 decimal places
  774. std::vector<std::string> decimal_result;
  775. EXPECT_TRUE(detail::parse_accept_header(
  776. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  777. EXPECT_EQ(decimal_result.size(), 2U);
  778. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  779. EXPECT_EQ(decimal_result[1], "text/html");
  780. // Zero quality (should still be included but with lowest priority)
  781. std::vector<std::string> zero_q_result;
  782. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  783. zero_q_result));
  784. EXPECT_EQ(zero_q_result.size(), 2U);
  785. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  786. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  787. // No spaces around commas
  788. std::vector<std::string> no_space_result;
  789. EXPECT_TRUE(detail::parse_accept_header(
  790. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  791. no_space_result));
  792. EXPECT_EQ(no_space_result.size(), 3U);
  793. EXPECT_EQ(no_space_result[0], "text/html");
  794. EXPECT_EQ(no_space_result[1], "application/json");
  795. EXPECT_EQ(no_space_result[2], "text/plain");
  796. }
  797. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  798. // Quality values always use '.' as the decimal separator, so parsing must
  799. // not depend on the process locale. An embedding application may have
  800. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  801. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  802. std::string saved = cur ? cur : "C";
  803. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  804. "fr_FR.UTF-8"};
  805. bool switched = false;
  806. for (const auto loc : comma_locales) {
  807. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  808. std::localeconv()->decimal_point[0] == ',') {
  809. switched = true;
  810. break;
  811. }
  812. }
  813. if (!switched) {
  814. std::setlocale(LC_NUMERIC, saved.c_str());
  815. GTEST_SKIP() << "no comma-decimal locale available on this host";
  816. }
  817. // The higher-weighted type appears later in the list, so a correct parse
  818. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  819. // sensitive parse reads both weights as 0 and leaves the original order.
  820. std::vector<std::string> result;
  821. EXPECT_TRUE(detail::parse_accept_header(
  822. "application/json;q=0.1,text/html;q=0.9", result));
  823. ASSERT_EQ(result.size(), 2U);
  824. EXPECT_EQ(result[0], "text/html");
  825. EXPECT_EQ(result[1], "application/json");
  826. std::setlocale(LC_NUMERIC, saved.c_str());
  827. }
  828. TEST(ParseAcceptHeaderTest, InvalidCases) {
  829. std::vector<std::string> result;
  830. // Invalid quality value (> 1.0)
  831. EXPECT_FALSE(
  832. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  833. // Invalid quality value (< 0.0)
  834. EXPECT_FALSE(
  835. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  836. // Invalid quality value (not a number)
  837. EXPECT_FALSE(detail::parse_accept_header(
  838. "text/html;q=invalid,application/json", result));
  839. // Empty quality value
  840. EXPECT_FALSE(
  841. detail::parse_accept_header("text/html;q=,application/json", result));
  842. // Invalid media type format (no slash and not wildcard)
  843. EXPECT_FALSE(
  844. detail::parse_accept_header("invalidtype,application/json", result));
  845. // Empty media type
  846. result.clear();
  847. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  848. // Only commas
  849. result.clear();
  850. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  851. // Valid cases should still work
  852. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  853. EXPECT_EQ(result.size(), 1U);
  854. EXPECT_EQ(result[0], "*/*");
  855. EXPECT_TRUE(detail::parse_accept_header("*", result));
  856. EXPECT_EQ(result.size(), 1U);
  857. EXPECT_EQ(result[0], "*");
  858. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  859. EXPECT_EQ(result.size(), 1U);
  860. EXPECT_EQ(result[0], "text/*");
  861. }
  862. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  863. Server svr;
  864. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  865. EXPECT_EQ(req.accept_content_types.size(), 3U);
  866. EXPECT_EQ(req.accept_content_types[0], "application/json");
  867. EXPECT_EQ(req.accept_content_types[1], "text/html");
  868. EXPECT_EQ(req.accept_content_types[2], "*/*");
  869. res.set_content("ok", "text/plain");
  870. });
  871. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  872. EXPECT_TRUE(false);
  873. res.set_content("bad request", "text/plain");
  874. });
  875. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  876. auto se = detail::scope_exit([&] {
  877. svr.stop();
  878. listen_thread.join();
  879. ASSERT_FALSE(svr.is_running());
  880. });
  881. svr.wait_until_ready();
  882. Client cli("localhost", PORT);
  883. {
  884. auto res = cli.Get(
  885. "/accept_ok",
  886. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  888. EXPECT_EQ(StatusCode::OK_200, res->status);
  889. }
  890. {
  891. auto res = cli.Get("/accept_bad_request",
  892. Headers{{"Accept", "text/html;q=abc,application/json"}});
  893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  894. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  895. }
  896. }
  897. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  898. Server svr;
  899. svr.Get("/", [](const Request & /*req*/, Response &res) {
  900. res.set_content("ok", "text/plain");
  901. });
  902. std::atomic<int> start_count{0};
  903. std::atomic<bool> running_when_called{false};
  904. svr.set_start_handler([&]() {
  905. running_when_called = svr.is_running();
  906. start_count++;
  907. });
  908. auto port = svr.bind_to_any_port(HOST);
  909. std::thread t([&]() { svr.listen_after_bind(); });
  910. auto se = detail::scope_exit([&] {
  911. svr.stop();
  912. t.join();
  913. ASSERT_FALSE(svr.is_running());
  914. });
  915. svr.wait_until_ready();
  916. // A successful request proves the accept loop is running, which the start
  917. // handler precedes; so by now the handler must have run exactly once.
  918. Client cli(HOST, port);
  919. cli.set_connection_timeout(std::chrono::seconds(5));
  920. auto res = cli.Get("/");
  921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  922. EXPECT_EQ(StatusCode::OK_200, res->status);
  923. EXPECT_EQ(1, start_count.load());
  924. EXPECT_TRUE(running_when_called.load());
  925. }
  926. TEST(DivideTest, DivideStringTests) {
  927. auto divide = [](const std::string &str, char d) {
  928. std::string lhs;
  929. std::string rhs;
  930. detail::divide(str, d,
  931. [&](const char *lhs_data, std::size_t lhs_size,
  932. const char *rhs_data, std::size_t rhs_size) {
  933. lhs.assign(lhs_data, lhs_size);
  934. rhs.assign(rhs_data, rhs_size);
  935. });
  936. return std::make_pair(std::move(lhs), std::move(rhs));
  937. };
  938. {
  939. const auto res = divide("", '=');
  940. EXPECT_EQ(res.first, "");
  941. EXPECT_EQ(res.second, "");
  942. }
  943. {
  944. const auto res = divide("=", '=');
  945. EXPECT_EQ(res.first, "");
  946. EXPECT_EQ(res.second, "");
  947. }
  948. {
  949. const auto res = divide(" ", '=');
  950. EXPECT_EQ(res.first, " ");
  951. EXPECT_EQ(res.second, "");
  952. }
  953. {
  954. const auto res = divide("a", '=');
  955. EXPECT_EQ(res.first, "a");
  956. EXPECT_EQ(res.second, "");
  957. }
  958. {
  959. const auto res = divide("a=", '=');
  960. EXPECT_EQ(res.first, "a");
  961. EXPECT_EQ(res.second, "");
  962. }
  963. {
  964. const auto res = divide("=b", '=');
  965. EXPECT_EQ(res.first, "");
  966. EXPECT_EQ(res.second, "b");
  967. }
  968. {
  969. const auto res = divide("a=b", '=');
  970. EXPECT_EQ(res.first, "a");
  971. EXPECT_EQ(res.second, "b");
  972. }
  973. {
  974. const auto res = divide("a=b=", '=');
  975. EXPECT_EQ(res.first, "a");
  976. EXPECT_EQ(res.second, "b=");
  977. }
  978. {
  979. const auto res = divide("a=b=c", '=');
  980. EXPECT_EQ(res.first, "a");
  981. EXPECT_EQ(res.second, "b=c");
  982. }
  983. }
  984. TEST(SplitTest, ParseQueryString) {
  985. string s = "key1=val1&key2=val2&key3=val3";
  986. Params dic;
  987. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  988. [&](const char *b, const char *e) {
  989. string key, val;
  990. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  991. if (key.empty()) {
  992. key.assign(b2, e2);
  993. } else {
  994. val.assign(b2, e2);
  995. }
  996. });
  997. dic.emplace(key, val);
  998. });
  999. EXPECT_EQ("val1", dic.find("key1")->second);
  1000. EXPECT_EQ("val2", dic.find("key2")->second);
  1001. EXPECT_EQ("val3", dic.find("key3")->second);
  1002. }
  1003. TEST(SplitTest, ParseInvalidQueryTests) {
  1004. {
  1005. string s = " ";
  1006. Params dict;
  1007. detail::parse_query_text(s, dict);
  1008. EXPECT_TRUE(dict.empty());
  1009. }
  1010. {
  1011. string s = " = =";
  1012. Params dict;
  1013. detail::parse_query_text(s, dict);
  1014. EXPECT_TRUE(dict.empty());
  1015. }
  1016. }
  1017. TEST(ParseQueryTest, ParseQueryString) {
  1018. {
  1019. std::string s = "key1=val1&key2=val2&key3=val3";
  1020. Params dic;
  1021. detail::parse_query_text(s, dic);
  1022. EXPECT_EQ("val1", dic.find("key1")->second);
  1023. EXPECT_EQ("val2", dic.find("key2")->second);
  1024. EXPECT_EQ("val3", dic.find("key3")->second);
  1025. }
  1026. {
  1027. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1028. Params dic;
  1029. detail::parse_query_text(s, dic);
  1030. EXPECT_EQ("", dic.find("key1")->second);
  1031. EXPECT_EQ("val1", dic.find("key2")->second);
  1032. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1033. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1034. }
  1035. }
  1036. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1037. Params dic;
  1038. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1039. dic.emplace("key1", "val1");
  1040. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1041. dic.emplace("key2", "val2");
  1042. dic.emplace("key3", "val3");
  1043. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1044. }
  1045. // Joins every entry of a Headers or Params into "key=value " so a whole
  1046. // traversal can be compared in one assertion. Both are instantiations of the
  1047. // same insertion-ordered container, so one helper serves both.
  1048. template <typename Map> static std::string entries_to_string(const Map &m) {
  1049. std::string s;
  1050. for (const auto &entry : m) {
  1051. s += entry.first + "=" + entry.second + " ";
  1052. }
  1053. return s;
  1054. }
  1055. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1056. // Params used to be a std::multimap, which sorted by name and handed the
  1057. // caller's query back alphabetised. A client signing its query string could
  1058. // not reproduce the order it asked for.
  1059. Params dic;
  1060. dic.emplace("zulu", "1");
  1061. dic.emplace("alpha", "2");
  1062. dic.emplace("mike", "3");
  1063. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1064. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1065. }
  1066. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1067. Params dic;
  1068. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1069. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1070. }
  1071. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1072. Request req;
  1073. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1074. req.params);
  1075. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1076. EXPECT_EQ("first", req.get_param_value("tag"));
  1077. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1078. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1079. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1080. EXPECT_EQ("", req.get_param_value("tag", 3));
  1081. }
  1082. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1083. // Params shares its container with Headers, which matches field names
  1084. // case-insensitively. Parameter names must not pick that up.
  1085. Params dic;
  1086. dic.emplace("Key", "upper");
  1087. dic.emplace("key", "lower");
  1088. EXPECT_EQ(2U, dic.size());
  1089. EXPECT_EQ(1U, dic.count("Key"));
  1090. EXPECT_EQ(1U, dic.count("key"));
  1091. EXPECT_EQ("upper", dic.find("Key")->second);
  1092. EXPECT_EQ("lower", dic.find("key")->second);
  1093. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1094. }
  1095. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1096. Server svr;
  1097. std::string order;
  1098. svr.Get("/order", [&](const Request &req, Response &res) {
  1099. order = entries_to_string(req.params);
  1100. res.set_content("ok", "text/plain");
  1101. });
  1102. auto port = svr.bind_to_any_port(HOST);
  1103. thread t = thread([&] { svr.listen_after_bind(); });
  1104. auto se = detail::scope_exit([&] {
  1105. svr.stop();
  1106. t.join();
  1107. ASSERT_FALSE(svr.is_running());
  1108. });
  1109. svr.wait_until_ready();
  1110. Client cli(HOST, port);
  1111. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1112. ASSERT_TRUE(res);
  1113. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1114. }
  1115. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1116. Server svr;
  1117. std::string field_order, file_order;
  1118. svr.Post("/order", [&](const Request &req, Response &res) {
  1119. for (const auto &field : req.form.fields) {
  1120. field_order += field.first + "=" + field.second.content + " ";
  1121. }
  1122. for (const auto &file : req.form.files) {
  1123. file_order += file.first + "=" + file.second.filename + " ";
  1124. }
  1125. res.set_content("ok", "text/plain");
  1126. });
  1127. auto port = svr.bind_to_any_port(HOST);
  1128. thread t = thread([&] { svr.listen_after_bind(); });
  1129. auto se = detail::scope_exit([&] {
  1130. svr.stop();
  1131. t.join();
  1132. ASSERT_FALSE(svr.is_running());
  1133. });
  1134. svr.wait_until_ready();
  1135. UploadFormDataItems items = {
  1136. {"zulu", "1", "", ""},
  1137. {"alpha", "2", "", ""},
  1138. {"mike", "3", "", ""},
  1139. {"zebra", "z", "z.txt", "text/plain"},
  1140. {"apple", "a", "a.txt", "text/plain"},
  1141. };
  1142. Client cli(HOST, port);
  1143. auto res = cli.Post("/order", items);
  1144. ASSERT_TRUE(res);
  1145. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1146. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1147. }
  1148. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1149. Server svr;
  1150. std::vector<std::string> values;
  1151. std::string first, second, out_of_range, order;
  1152. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1153. values = req.form.get_fields("tag");
  1154. first = req.form.get_field("tag", 0);
  1155. second = req.form.get_field("tag", 1);
  1156. out_of_range = req.form.get_field("tag", 2);
  1157. for (const auto &field : req.form.fields) {
  1158. order += field.first + "=" + field.second.content + " ";
  1159. }
  1160. res.set_content("ok", "text/plain");
  1161. });
  1162. auto port = svr.bind_to_any_port(HOST);
  1163. thread t = thread([&] { svr.listen_after_bind(); });
  1164. auto se = detail::scope_exit([&] {
  1165. svr.stop();
  1166. t.join();
  1167. ASSERT_FALSE(svr.is_running());
  1168. });
  1169. svr.wait_until_ready();
  1170. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1171. // not adjacent in the container.
  1172. UploadFormDataItems items = {
  1173. {"tag", "first", "", ""},
  1174. {"other", "x", "", ""},
  1175. {"tag", "second", "", ""},
  1176. };
  1177. Client cli(HOST, port);
  1178. auto res = cli.Post("/repeated", items);
  1179. ASSERT_TRUE(res);
  1180. ASSERT_EQ(2U, values.size());
  1181. EXPECT_EQ("first", values[0]);
  1182. EXPECT_EQ("second", values[1]);
  1183. EXPECT_EQ("first", first);
  1184. EXPECT_EQ("second", second);
  1185. // std::multimap already kept entries sharing a name in insertion order, so
  1186. // everything above passes without this change too. The whole traversal is
  1187. // what tells the two apart: sorting by name would hoist "other" to the front
  1188. // and the two "tag" parts would end up adjacent.
  1189. EXPECT_EQ("tag=first other=x tag=second ", order);
  1190. // Advancing past the last entry of a name used to run off the container;
  1191. // the container's saturating increment makes it return the default instead.
  1192. EXPECT_EQ("", out_of_range);
  1193. }
  1194. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1195. // Server::read_content() keeps a FormFields::iterator alive across the
  1196. // content callbacks that fill the part it points at. The container is
  1197. // vector-backed, so a later emplace can reallocate and invalidate an older
  1198. // iterator; 64 parts grow the vector through seven reallocations, which
  1199. // checks that every part's content still lands in its own entry.
  1200. const size_t part_count = 64;
  1201. // One formula for both the parts sent and the values expected back, so the
  1202. // two cannot drift apart.
  1203. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1204. auto content_of = [](size_t i) {
  1205. return std::string(64, static_cast<char>('a' + (i % 26)));
  1206. };
  1207. Server svr;
  1208. std::vector<std::pair<std::string, std::string>> received;
  1209. svr.Post("/many", [&](const Request &req, Response &res) {
  1210. for (const auto &field : req.form.fields) {
  1211. received.emplace_back(field.first, field.second.content);
  1212. }
  1213. res.set_content("ok", "text/plain");
  1214. });
  1215. auto port = svr.bind_to_any_port(HOST);
  1216. thread t = thread([&] { svr.listen_after_bind(); });
  1217. auto se = detail::scope_exit([&] {
  1218. svr.stop();
  1219. t.join();
  1220. ASSERT_FALSE(svr.is_running());
  1221. });
  1222. svr.wait_until_ready();
  1223. UploadFormDataItems items;
  1224. for (size_t i = 0; i < part_count; i++) {
  1225. items.push_back({name_of(i), content_of(i), "", ""});
  1226. }
  1227. Client cli(HOST, port);
  1228. auto res = cli.Post("/many", items);
  1229. ASSERT_TRUE(res);
  1230. ASSERT_EQ(part_count, received.size());
  1231. for (size_t i = 0; i < part_count; i++) {
  1232. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1233. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1234. }
  1235. }
  1236. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1237. string content_type = "multipart/form-data; boundary=something";
  1238. string boundary;
  1239. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1240. EXPECT_TRUE(ret);
  1241. EXPECT_EQ(boundary, "something");
  1242. }
  1243. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1244. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1245. string boundary;
  1246. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1247. EXPECT_TRUE(ret);
  1248. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1249. }
  1250. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1251. string content_type =
  1252. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1253. string boundary;
  1254. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1255. EXPECT_TRUE(ret);
  1256. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1257. }
  1258. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1259. string content_type =
  1260. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1261. string boundary;
  1262. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1263. EXPECT_TRUE(ret);
  1264. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1265. }
  1266. TEST(GetHeaderValueTest, DefaultValue) {
  1267. Headers headers = {{"Dummy", "Dummy"}};
  1268. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1269. EXPECT_STREQ("text/plain", val);
  1270. }
  1271. TEST(GetHeaderValueTest, DefaultValueInt) {
  1272. Headers headers = {{"Dummy", "Dummy"}};
  1273. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1274. EXPECT_EQ(100ull, val);
  1275. }
  1276. TEST(GetHeaderValueTest, RegularValue) {
  1277. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1278. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1279. EXPECT_STREQ("text/html", val);
  1280. }
  1281. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1282. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1283. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1284. EXPECT_STREQ("text/html", val);
  1285. }
  1286. TEST(GetHeaderValueTest, SetContent) {
  1287. Response res;
  1288. res.set_content("html", "text/html");
  1289. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1290. res.set_content("text", "text/plain");
  1291. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1292. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1293. }
  1294. TEST(GetHeaderValueTest, RegularValueInt) {
  1295. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1296. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1297. EXPECT_EQ(100ull, val);
  1298. }
  1299. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1300. Headers headers = {{"Content-Length", "x"}};
  1301. auto is_invalid_value = false;
  1302. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1303. is_invalid_value);
  1304. EXPECT_EQ(0ull, val);
  1305. EXPECT_TRUE(is_invalid_value);
  1306. }
  1307. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1308. // An all-digit value that overflows size_t must be reported as invalid, not
  1309. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1310. // a large length to a small one on 32-bit builds, leaving the framing length
  1311. // wrong while is_invalid_value stayed false.
  1312. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1313. auto is_invalid_value = false;
  1314. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1315. is_invalid_value);
  1316. EXPECT_TRUE(is_invalid_value);
  1317. // A well-formed length is unaffected.
  1318. Headers ok = {{"Content-Length", "1234"}};
  1319. is_invalid_value = false;
  1320. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1321. is_invalid_value);
  1322. EXPECT_EQ(1234ull, val);
  1323. EXPECT_FALSE(is_invalid_value);
  1324. }
  1325. TEST(GetHeaderValueTest, Range) {
  1326. {
  1327. Headers headers = {make_range_header({{1, -1}})};
  1328. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1329. EXPECT_STREQ("bytes=1-", val);
  1330. }
  1331. {
  1332. Headers headers = {make_range_header({{-1, 1}})};
  1333. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1334. EXPECT_STREQ("bytes=-1", val);
  1335. }
  1336. {
  1337. Headers headers = {make_range_header({{1, 10}})};
  1338. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1339. EXPECT_STREQ("bytes=1-10", val);
  1340. }
  1341. {
  1342. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1343. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1344. EXPECT_STREQ("bytes=1-10, 100-", val);
  1345. }
  1346. {
  1347. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1348. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1349. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1350. }
  1351. {
  1352. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1353. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1354. EXPECT_STREQ("bytes=0-0, -1", val);
  1355. }
  1356. }
  1357. TEST(BearerTokenAuthTest, SchemeValidation) {
  1358. // A value shorter than "Bearer " must not throw from the fixed-length
  1359. // substr, and a non-Bearer scheme must not be reported as a token.
  1360. struct {
  1361. const char *value;
  1362. const char *expected;
  1363. } cases[] = {
  1364. {"x", ""},
  1365. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1366. {"Bearer abc123", "abc123"},
  1367. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1368. };
  1369. for (const auto &c : cases) {
  1370. Request req;
  1371. req.set_header("Authorization", c.value);
  1372. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1373. }
  1374. }
  1375. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1376. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1377. // to depend on the standard library (libstdc++ handed back duplicates in
  1378. // reverse insertion order, libc++ in insertion order).
  1379. Request req;
  1380. req.set_header("Accept-Encoding", "gzip");
  1381. req.set_header("Accept-Encoding", "deflate");
  1382. req.set_header("Accept-Encoding", "br");
  1383. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1384. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1385. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1386. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1387. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1388. }
  1389. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1390. Request req;
  1391. req.set_header("X-Test", "only");
  1392. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1393. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1394. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1395. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1396. }
  1397. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1398. Headers headers;
  1399. headers.emplace("Host", "example.com");
  1400. headers.emplace("Accept-Encoding", "gzip");
  1401. headers.emplace("User-Agent", "test");
  1402. headers.emplace("Accept-Encoding", "deflate");
  1403. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1404. "Accept-Encoding=deflate ",
  1405. entries_to_string(headers));
  1406. }
  1407. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1408. Headers headers = {{"Content-Type", "text/html"},
  1409. {"CONTENT-TYPE", "text/xml"}};
  1410. EXPECT_EQ(2U, headers.count("content-type"));
  1411. auto it = headers.find("content-type");
  1412. ASSERT_TRUE(it != headers.end());
  1413. EXPECT_EQ("text/html", it->second);
  1414. }
  1415. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1416. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1417. // drop only those fields and leave everything positioned between them.
  1418. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1419. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1420. auto rng = headers.equal_range("a");
  1421. headers.erase(rng.first, rng.second);
  1422. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1423. }
  1424. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1425. Headers headers = {
  1426. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1427. EXPECT_EQ(3U, headers.erase("A"));
  1428. EXPECT_EQ(0U, headers.count("A"));
  1429. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1430. }
  1431. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1432. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1433. headers.emplace_front("Host", "example.com");
  1434. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1435. entries_to_string(headers));
  1436. }
  1437. TEST(ParseHeaderValueTest, Range) {
  1438. {
  1439. Ranges ranges;
  1440. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1441. EXPECT_TRUE(ret);
  1442. EXPECT_EQ(1u, ranges.size());
  1443. EXPECT_EQ(1u, ranges[0].first);
  1444. EXPECT_EQ(-1, ranges[0].second);
  1445. }
  1446. {
  1447. Ranges ranges;
  1448. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1449. EXPECT_TRUE(ret);
  1450. EXPECT_EQ(1u, ranges.size());
  1451. EXPECT_EQ(-1, ranges[0].first);
  1452. EXPECT_EQ(1u, ranges[0].second);
  1453. }
  1454. {
  1455. Ranges ranges;
  1456. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1457. EXPECT_TRUE(ret);
  1458. EXPECT_EQ(1u, ranges.size());
  1459. EXPECT_EQ(1u, ranges[0].first);
  1460. EXPECT_EQ(10u, ranges[0].second);
  1461. }
  1462. {
  1463. Ranges ranges;
  1464. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1465. EXPECT_FALSE(ret);
  1466. }
  1467. {
  1468. Ranges ranges;
  1469. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1470. EXPECT_TRUE(ret);
  1471. EXPECT_EQ(2u, ranges.size());
  1472. EXPECT_EQ(1u, ranges[0].first);
  1473. EXPECT_EQ(10u, ranges[0].second);
  1474. EXPECT_EQ(100u, ranges[1].first);
  1475. EXPECT_EQ(-1, ranges[1].second);
  1476. }
  1477. {
  1478. Ranges ranges;
  1479. auto ret =
  1480. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1481. EXPECT_TRUE(ret);
  1482. EXPECT_EQ(3u, ranges.size());
  1483. EXPECT_EQ(1u, ranges[0].first);
  1484. EXPECT_EQ(10u, ranges[0].second);
  1485. EXPECT_EQ(100u, ranges[1].first);
  1486. EXPECT_EQ(200u, ranges[1].second);
  1487. EXPECT_EQ(300u, ranges[2].first);
  1488. EXPECT_EQ(400u, ranges[2].second);
  1489. }
  1490. {
  1491. Ranges ranges;
  1492. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1493. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1494. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1495. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1496. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1497. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1498. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1499. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1500. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1501. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1502. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1503. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1504. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1505. EXPECT_TRUE(ranges.empty());
  1506. }
  1507. }
  1508. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1509. Request req;
  1510. req.set_header("Accept-Encoding", "gzip");
  1511. Response res;
  1512. res.set_header("Content-Type", "text/plain");
  1513. auto ret = detail::encoding_type(req, res);
  1514. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1515. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1516. #else
  1517. EXPECT_TRUE(ret == detail::EncodingType::None);
  1518. #endif
  1519. }
  1520. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1521. Request req;
  1522. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1523. Response res;
  1524. res.set_header("Content-Type", "text/plain");
  1525. auto ret = detail::encoding_type(req, res);
  1526. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1527. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1528. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1529. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1530. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1531. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1532. #else
  1533. EXPECT_TRUE(ret == detail::EncodingType::None);
  1534. #endif
  1535. }
  1536. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1537. Request req;
  1538. req.set_header("Accept-Encoding",
  1539. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1540. Response res;
  1541. res.set_header("Content-Type", "text/plain");
  1542. auto ret = detail::encoding_type(req, res);
  1543. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1544. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1545. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1546. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1547. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1548. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1549. #else
  1550. EXPECT_TRUE(ret == detail::EncodingType::None);
  1551. #endif
  1552. }
  1553. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1554. // All supported encodings rejected with q=0 should return None
  1555. Request req;
  1556. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1557. Response res;
  1558. res.set_header("Content-Type", "text/plain");
  1559. auto ret = detail::encoding_type(req, res);
  1560. EXPECT_TRUE(ret == detail::EncodingType::None);
  1561. }
  1562. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1563. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1564. Request req;
  1565. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1566. Response res;
  1567. res.set_header("Content-Type", "text/plain");
  1568. auto ret = detail::encoding_type(req, res);
  1569. EXPECT_TRUE(ret == detail::EncodingType::None);
  1570. }
  1571. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1572. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1573. Request req;
  1574. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1575. Response res;
  1576. res.set_header("Content-Type", "text/plain");
  1577. auto ret = detail::encoding_type(req, res);
  1578. EXPECT_TRUE(ret == detail::EncodingType::None);
  1579. }
  1580. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1581. // RFC 7231: Accept-Encoding values are case-insensitive
  1582. Request req;
  1583. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1584. Response res;
  1585. res.set_header("Content-Type", "text/plain");
  1586. auto ret = detail::encoding_type(req, res);
  1587. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1588. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1589. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1590. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1591. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1592. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1593. #else
  1594. EXPECT_TRUE(ret == detail::EncodingType::None);
  1595. #endif
  1596. }
  1597. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1598. // q value should determine priority, not hardcoded order
  1599. Request req;
  1600. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1601. Response res;
  1602. res.set_header("Content-Type", "text/plain");
  1603. auto ret = detail::encoding_type(req, res);
  1604. // gzip has highest q=1.0, so it should be selected even though
  1605. // br and zstd are also supported
  1606. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1607. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1608. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1609. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1610. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1611. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1612. #else
  1613. EXPECT_TRUE(ret == detail::EncodingType::None);
  1614. #endif
  1615. }
  1616. TEST(BufferStreamTest, read) {
  1617. detail::BufferStream strm1;
  1618. Stream &strm = strm1;
  1619. EXPECT_EQ(5, strm.write("hello"));
  1620. char buf[512];
  1621. EXPECT_EQ(2, strm.read(buf, 2));
  1622. EXPECT_EQ('h', buf[0]);
  1623. EXPECT_EQ('e', buf[1]);
  1624. EXPECT_EQ(2, strm.read(buf, 2));
  1625. EXPECT_EQ('l', buf[0]);
  1626. EXPECT_EQ('l', buf[1]);
  1627. EXPECT_EQ(1, strm.read(buf, 1));
  1628. EXPECT_EQ('o', buf[0]);
  1629. EXPECT_EQ(0, strm.read(buf, 1));
  1630. }
  1631. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1632. auto host = "www.httpwatch.com";
  1633. auto ip = hosted_at(host);
  1634. EXPECT_EQ("23.96.13.243", ip);
  1635. std::vector<std::string> addrs;
  1636. hosted_at(host, addrs);
  1637. EXPECT_EQ(1u, addrs.size());
  1638. }
  1639. #if 0 // It depends on each test environment...
  1640. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1641. auto host = "www.youtube.com";
  1642. std::vector<std::string> addrs;
  1643. hosted_at(host, addrs);
  1644. EXPECT_EQ(20u, addrs.size());
  1645. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1646. EXPECT_TRUE(it != addrs.end());
  1647. }
  1648. #endif
  1649. class ChunkedEncodingTest : public ::testing::Test {
  1650. protected:
  1651. ChunkedEncodingTest()
  1652. : cli_(HOST, PORT)
  1653. #ifdef CPPHTTPLIB_SSL_ENABLED
  1654. ,
  1655. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1656. #endif
  1657. {
  1658. cli_.set_connection_timeout(2);
  1659. #ifdef CPPHTTPLIB_SSL_ENABLED
  1660. cli_.enable_server_certificate_verification(false);
  1661. #endif
  1662. }
  1663. virtual void SetUp() {
  1664. read_file("./image.jpg", image_data_);
  1665. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1666. res.set_content("Hello World!", "text/plain");
  1667. });
  1668. svr_.Get(
  1669. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1670. res.set_chunked_content_provider(
  1671. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1672. size_t remaining = image_data_.size() - offset;
  1673. if (remaining == 0) {
  1674. sink.done();
  1675. } else {
  1676. constexpr size_t CHUNK_SIZE = 1024;
  1677. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1678. sink.write(&image_data_[offset], send_size);
  1679. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1680. }
  1681. return true;
  1682. });
  1683. });
  1684. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1685. svr_.wait_until_ready();
  1686. }
  1687. virtual void TearDown() {
  1688. svr_.stop();
  1689. if (!request_threads_.empty()) {
  1690. std::this_thread::sleep_for(std::chrono::seconds(1));
  1691. for (auto &t : request_threads_) {
  1692. t.join();
  1693. }
  1694. }
  1695. t_.join();
  1696. }
  1697. #ifdef CPPHTTPLIB_SSL_ENABLED
  1698. SSLClient cli_;
  1699. SSLServer svr_;
  1700. #else
  1701. Client cli_;
  1702. Server svr_;
  1703. #endif
  1704. thread t_;
  1705. std::vector<thread> request_threads_;
  1706. std::string image_data_;
  1707. };
  1708. TEST_F(ChunkedEncodingTest, NormalGet) {
  1709. auto res = cli_.Get("/chunked");
  1710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1711. std::string out;
  1712. read_file("./image.jpg", out);
  1713. EXPECT_EQ(StatusCode::OK_200, res->status);
  1714. EXPECT_EQ(out, res->body);
  1715. }
  1716. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1717. std::string body;
  1718. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1719. body.append(data, data_length);
  1720. return true;
  1721. });
  1722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1723. std::string out;
  1724. read_file("./image.jpg", out);
  1725. EXPECT_EQ(StatusCode::OK_200, res->status);
  1726. EXPECT_EQ(out, body);
  1727. }
  1728. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1729. std::string body;
  1730. auto res = cli_.Get(
  1731. "/chunked",
  1732. [&](const Response &response) {
  1733. EXPECT_EQ(StatusCode::OK_200, response.status);
  1734. return true;
  1735. },
  1736. [&](const char *data, size_t data_length) {
  1737. body.append(data, data_length);
  1738. return true;
  1739. });
  1740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1741. std::string out;
  1742. read_file("./image.jpg", out);
  1743. EXPECT_EQ(StatusCode::OK_200, res->status);
  1744. EXPECT_EQ(out, body);
  1745. }
  1746. TEST(RangeTest, FromHTTPBin_Online) {
  1747. auto host = "httpbingo.org";
  1748. auto path = std::string{"/range/32"};
  1749. #ifdef CPPHTTPLIB_SSL_ENABLED
  1750. auto port = 443;
  1751. SSLClient cli(host, port);
  1752. #else
  1753. auto port = 80;
  1754. Client cli(host, port);
  1755. #endif
  1756. cli.set_connection_timeout(5);
  1757. {
  1758. auto res = cli.Get(path);
  1759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1760. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1761. EXPECT_EQ(StatusCode::OK_200, res->status);
  1762. }
  1763. {
  1764. Headers headers = {make_range_header({{1, -1}})};
  1765. auto res = cli.Get(path, headers);
  1766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1767. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1768. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1769. }
  1770. {
  1771. Headers headers = {make_range_header({{1, 10}})};
  1772. auto res = cli.Get(path, headers);
  1773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1774. EXPECT_EQ("bcdefghijk", res->body);
  1775. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1776. }
  1777. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1778. // entire resource, while the original httpbin returned 200. Both are
  1779. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1780. {
  1781. Headers headers = {make_range_header({{0, 31}})};
  1782. auto res = cli.Get(path, headers);
  1783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1784. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1785. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1786. res->status == StatusCode::PartialContent_206);
  1787. }
  1788. {
  1789. Headers headers = {make_range_header({{0, -1}})};
  1790. auto res = cli.Get(path, headers);
  1791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1792. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1793. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1794. res->status == StatusCode::PartialContent_206);
  1795. }
  1796. // go-httpbin returns 206 with clamped range for over-range requests,
  1797. // while the original httpbin returned 416. Both behaviors are observed
  1798. // in real servers, so we only verify the request succeeds.
  1799. {
  1800. Headers headers = {make_range_header({{0, 32}})};
  1801. auto res = cli.Get(path, headers);
  1802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1803. }
  1804. }
  1805. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1806. auto host = "unresolvableaddress.local";
  1807. auto path = std::string{"/"};
  1808. #ifdef CPPHTTPLIB_SSL_ENABLED
  1809. auto port = 443;
  1810. SSLClient cli(host, port);
  1811. #else
  1812. auto port = 80;
  1813. Client cli(host, port);
  1814. #endif
  1815. cli.set_connection_timeout(1);
  1816. {
  1817. auto res = cli.Get(path);
  1818. ASSERT_FALSE(res);
  1819. }
  1820. std::this_thread::sleep_for(std::chrono::seconds(8));
  1821. }
  1822. #if defined(__linux__) && defined(__GLIBC__) && \
  1823. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1824. // Forward declaration: in split builds split.py strips `inline` and moves the
  1825. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1826. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1827. // against the symbol in both header-only and split builds.
  1828. namespace httplib {
  1829. namespace detail {
  1830. int getaddrinfo_with_timeout(const char *node, const char *service,
  1831. const struct addrinfo *hints,
  1832. struct addrinfo **res, time_t timeout_sec);
  1833. } // namespace detail
  1834. } // namespace httplib
  1835. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1836. //
  1837. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1838. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1839. // gai_suspend() call hits the connection timeout the function calls
  1840. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1841. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1842. // still alive and still references the now-destroyed stack frame.
  1843. //
  1844. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1845. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1846. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1847. // and runs them in a container.
  1848. namespace {
  1849. bool should_run_issue_2431_tests() {
  1850. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1851. return v && *v && std::string(v) != "0";
  1852. }
  1853. std::string unique_unresolvable_host(int n) {
  1854. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1855. // glibc still asks the configured nameserver — which is exactly the path
  1856. // we want to exercise. A unique label per call avoids the resolver cache.
  1857. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1858. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1859. std::to_string(n) + ".invalid";
  1860. }
  1861. } // namespace
  1862. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1863. if (!should_run_issue_2431_tests()) {
  1864. GTEST_SKIP()
  1865. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1866. }
  1867. for (int i = 0; i < 8; ++i) {
  1868. struct addrinfo hints;
  1869. memset(&hints, 0, sizeof(hints));
  1870. hints.ai_family = AF_UNSPEC;
  1871. hints.ai_socktype = SOCK_STREAM;
  1872. auto host = unique_unresolvable_host(i);
  1873. struct addrinfo *result = nullptr;
  1874. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1875. &result, /*timeout_sec=*/1);
  1876. if (rc == 0 && result) { freeaddrinfo(result); }
  1877. }
  1878. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1879. // stack region they still believe holds their gaicb.
  1880. std::this_thread::sleep_for(std::chrono::seconds(3));
  1881. }
  1882. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1883. if (!should_run_issue_2431_tests()) {
  1884. GTEST_SKIP()
  1885. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1886. }
  1887. std::atomic<bool> stop{false};
  1888. std::vector<std::thread> threads;
  1889. for (int t = 0; t < 8; ++t) {
  1890. threads.emplace_back([t, &stop] {
  1891. int i = 0;
  1892. while (!stop.load(std::memory_order_relaxed)) {
  1893. struct addrinfo hints;
  1894. memset(&hints, 0, sizeof(hints));
  1895. hints.ai_family = AF_UNSPEC;
  1896. hints.ai_socktype = SOCK_STREAM;
  1897. auto host = unique_unresolvable_host(t * 100000 + i++);
  1898. struct addrinfo *result = nullptr;
  1899. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1900. &result, /*timeout_sec=*/1);
  1901. if (rc == 0 && result) { freeaddrinfo(result); }
  1902. }
  1903. });
  1904. }
  1905. std::this_thread::sleep_for(std::chrono::seconds(8));
  1906. stop.store(true, std::memory_order_relaxed);
  1907. for (auto &th : threads) {
  1908. th.join();
  1909. }
  1910. std::this_thread::sleep_for(std::chrono::seconds(3));
  1911. }
  1912. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1913. if (!should_run_issue_2431_tests()) {
  1914. GTEST_SKIP()
  1915. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1916. }
  1917. std::atomic<bool> stop{false};
  1918. std::vector<std::thread> threads;
  1919. for (int t = 0; t < 8; ++t) {
  1920. threads.emplace_back([t, &stop] {
  1921. int i = 0;
  1922. while (!stop.load(std::memory_order_relaxed)) {
  1923. auto host = unique_unresolvable_host(t * 100000 + i++);
  1924. Client cli(host, 80);
  1925. cli.set_connection_timeout(1, 0);
  1926. cli.set_read_timeout(1, 0);
  1927. cli.set_write_timeout(1, 0);
  1928. (void)cli.Get("/");
  1929. }
  1930. });
  1931. }
  1932. std::this_thread::sleep_for(std::chrono::seconds(8));
  1933. stop.store(true, std::memory_order_relaxed);
  1934. for (auto &th : threads) {
  1935. th.join();
  1936. }
  1937. std::this_thread::sleep_for(std::chrono::seconds(3));
  1938. }
  1939. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1940. TEST(ConnectionErrorTest, InvalidHost) {
  1941. auto host = "-abcde.com";
  1942. #ifdef CPPHTTPLIB_SSL_ENABLED
  1943. auto port = 443;
  1944. SSLClient cli(host, port);
  1945. #else
  1946. auto port = 80;
  1947. Client cli(host, port);
  1948. #endif
  1949. cli.set_connection_timeout(std::chrono::seconds(2));
  1950. auto res = cli.Get("/");
  1951. ASSERT_TRUE(!res);
  1952. EXPECT_EQ(Error::Connection, res.error());
  1953. }
  1954. TEST(ConnectionErrorTest, InvalidHost2) {
  1955. auto host = "httpcan.org/";
  1956. #ifdef CPPHTTPLIB_SSL_ENABLED
  1957. SSLClient cli(host);
  1958. #else
  1959. Client cli(host);
  1960. #endif
  1961. cli.set_connection_timeout(std::chrono::seconds(2));
  1962. auto res = cli.Get("/");
  1963. ASSERT_TRUE(!res);
  1964. EXPECT_EQ(Error::Connection, res.error());
  1965. }
  1966. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1967. auto host = "httpcan.org/";
  1968. #ifdef CPPHTTPLIB_SSL_ENABLED
  1969. SSLClient cli(host);
  1970. #else
  1971. Client cli(host);
  1972. #endif
  1973. cli.set_connection_timeout(std::chrono::seconds(2));
  1974. auto res = cli.Get("/");
  1975. ASSERT_TRUE(!res);
  1976. stringstream s;
  1977. s << "error code: " << res.error();
  1978. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1979. }
  1980. TEST(ConnectionErrorTest, InvalidPort) {
  1981. auto host = "localhost";
  1982. auto port = 44380;
  1983. #ifdef CPPHTTPLIB_SSL_ENABLED
  1984. SSLClient cli(host, port);
  1985. #else
  1986. Client cli(host, port);
  1987. #endif
  1988. cli.set_connection_timeout(std::chrono::seconds(2));
  1989. auto res = cli.Get("/");
  1990. ASSERT_TRUE(!res);
  1991. EXPECT_TRUE(Error::Connection == res.error() ||
  1992. Error::ConnectionTimeout == res.error());
  1993. }
  1994. TEST(ConnectionErrorTest, Timeout_Online) {
  1995. auto host = "google.com";
  1996. #ifdef CPPHTTPLIB_SSL_ENABLED
  1997. auto port = 44380;
  1998. SSLClient cli(host, port);
  1999. #else
  2000. auto port = 8080;
  2001. Client cli(host, port);
  2002. #endif
  2003. cli.set_connection_timeout(std::chrono::seconds(2));
  2004. // only probe one address type so that the error reason
  2005. // correlates to the timed-out IPv4, not the unsupported
  2006. // IPv6 connection attempt
  2007. cli.set_address_family(AF_INET);
  2008. auto res = cli.Get("/");
  2009. ASSERT_TRUE(!res);
  2010. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2011. }
  2012. TEST(CancelTest, NoCancel_Online) {
  2013. auto host = "httpbingo.org";
  2014. auto path = std::string{"/range/32"};
  2015. #ifdef CPPHTTPLIB_SSL_ENABLED
  2016. auto port = 443;
  2017. SSLClient cli(host, port);
  2018. #else
  2019. auto port = 80;
  2020. Client cli(host, port);
  2021. #endif
  2022. cli.set_connection_timeout(std::chrono::seconds(5));
  2023. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2025. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2026. EXPECT_EQ(StatusCode::OK_200, res->status);
  2027. }
  2028. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2029. // Use /bytes with a large payload so that the DownloadProgress callback
  2030. // (which only fires for Content-Length responses) is invoked before the
  2031. // entire body is received, giving cancellation a chance to fire.
  2032. auto host = "httpbingo.org";
  2033. auto path = std::string{"/bytes/524288"};
  2034. #ifdef CPPHTTPLIB_SSL_ENABLED
  2035. auto port = 443;
  2036. SSLClient cli(host, port);
  2037. #else
  2038. auto port = 80;
  2039. Client cli(host, port);
  2040. #endif
  2041. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2042. cli.set_connection_timeout(std::chrono::seconds(5));
  2043. ASSERT_TRUE(!res);
  2044. EXPECT_EQ(Error::Canceled, res.error());
  2045. }
  2046. TEST(CancelTest, WithCancelLargePayload_Online) {
  2047. auto host = "httpbingo.org";
  2048. auto path = std::string{"/bytes/524288"};
  2049. #ifdef CPPHTTPLIB_SSL_ENABLED
  2050. auto port = 443;
  2051. SSLClient cli(host, port);
  2052. #else
  2053. auto port = 80;
  2054. Client cli(host, port);
  2055. #endif
  2056. cli.set_connection_timeout(std::chrono::seconds(5));
  2057. uint32_t count = 0;
  2058. auto res =
  2059. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2060. ASSERT_TRUE(!res);
  2061. EXPECT_EQ(Error::Canceled, res.error());
  2062. }
  2063. TEST(CancelTest, NoCancelPost) {
  2064. Server svr;
  2065. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2066. res.set_content("Hello World!", "text/plain");
  2067. });
  2068. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2069. auto se = detail::scope_exit([&] {
  2070. svr.stop();
  2071. thread.join();
  2072. ASSERT_FALSE(svr.is_running());
  2073. });
  2074. svr.wait_until_ready();
  2075. Client cli(HOST, PORT);
  2076. cli.set_connection_timeout(std::chrono::seconds(5));
  2077. auto res =
  2078. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2079. "application/json", [](uint64_t, uint64_t) { return true; });
  2080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2081. EXPECT_EQ("Hello World!", res->body);
  2082. EXPECT_EQ(StatusCode::OK_200, res->status);
  2083. }
  2084. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2085. Server svr;
  2086. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2087. res.set_content("Hello World!", "text/plain");
  2088. });
  2089. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2090. auto se = detail::scope_exit([&] {
  2091. svr.stop();
  2092. thread.join();
  2093. ASSERT_FALSE(svr.is_running());
  2094. });
  2095. svr.wait_until_ready();
  2096. Client cli(HOST, PORT);
  2097. cli.set_connection_timeout(std::chrono::seconds(5));
  2098. auto res =
  2099. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2100. "application/json", [](uint64_t, uint64_t) { return false; });
  2101. ASSERT_TRUE(!res);
  2102. EXPECT_EQ(Error::Canceled, res.error());
  2103. }
  2104. TEST(CancelTest, WithCancelLargePayloadPost) {
  2105. Server svr;
  2106. svr.set_payload_max_length(200 * 1024 * 1024);
  2107. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2108. res.set_content(LARGE_DATA, "text/plain");
  2109. });
  2110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2111. auto se = detail::scope_exit([&] {
  2112. svr.stop();
  2113. thread.join();
  2114. ASSERT_FALSE(svr.is_running());
  2115. });
  2116. svr.wait_until_ready();
  2117. Client cli(HOST, PORT);
  2118. cli.set_payload_max_length(200 * 1024 * 1024);
  2119. cli.set_connection_timeout(std::chrono::seconds(5));
  2120. auto res =
  2121. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2122. "application/json", [](uint64_t, uint64_t) { return false; });
  2123. ASSERT_TRUE(!res);
  2124. EXPECT_EQ(Error::Canceled, res.error());
  2125. }
  2126. TEST(CancelTest, NoCancelPut) {
  2127. Server svr;
  2128. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2129. res.set_content("Hello World!", "text/plain");
  2130. });
  2131. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2132. auto se = detail::scope_exit([&] {
  2133. svr.stop();
  2134. thread.join();
  2135. ASSERT_FALSE(svr.is_running());
  2136. });
  2137. svr.wait_until_ready();
  2138. Client cli(HOST, PORT);
  2139. cli.set_connection_timeout(std::chrono::seconds(5));
  2140. auto res =
  2141. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2142. "application/json", [](uint64_t, uint64_t) { return true; });
  2143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2144. EXPECT_EQ("Hello World!", res->body);
  2145. EXPECT_EQ(StatusCode::OK_200, res->status);
  2146. }
  2147. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2148. Server svr;
  2149. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2150. res.set_content("Hello World!", "text/plain");
  2151. });
  2152. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2153. auto se = detail::scope_exit([&] {
  2154. svr.stop();
  2155. thread.join();
  2156. ASSERT_FALSE(svr.is_running());
  2157. });
  2158. svr.wait_until_ready();
  2159. Client cli(HOST, PORT);
  2160. cli.set_connection_timeout(std::chrono::seconds(5));
  2161. auto res =
  2162. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2163. "application/json", [](uint64_t, uint64_t) { return false; });
  2164. ASSERT_TRUE(!res);
  2165. EXPECT_EQ(Error::Canceled, res.error());
  2166. }
  2167. TEST(CancelTest, WithCancelLargePayloadPut) {
  2168. Server svr;
  2169. svr.set_payload_max_length(200 * 1024 * 1024);
  2170. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2171. res.set_content(LARGE_DATA, "text/plain");
  2172. });
  2173. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2174. auto se = detail::scope_exit([&] {
  2175. svr.stop();
  2176. thread.join();
  2177. ASSERT_FALSE(svr.is_running());
  2178. });
  2179. svr.wait_until_ready();
  2180. Client cli(HOST, PORT);
  2181. cli.set_payload_max_length(200 * 1024 * 1024);
  2182. cli.set_connection_timeout(std::chrono::seconds(5));
  2183. auto res =
  2184. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2185. "application/json", [](uint64_t, uint64_t) { return false; });
  2186. ASSERT_TRUE(!res);
  2187. EXPECT_EQ(Error::Canceled, res.error());
  2188. }
  2189. TEST(CancelTest, NoCancelPatch) {
  2190. Server svr;
  2191. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2192. res.set_content("Hello World!", "text/plain");
  2193. });
  2194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2195. auto se = detail::scope_exit([&] {
  2196. svr.stop();
  2197. thread.join();
  2198. ASSERT_FALSE(svr.is_running());
  2199. });
  2200. svr.wait_until_ready();
  2201. Client cli(HOST, PORT);
  2202. cli.set_connection_timeout(std::chrono::seconds(5));
  2203. auto res =
  2204. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2205. "application/json", [](uint64_t, uint64_t) { return true; });
  2206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2207. EXPECT_EQ("Hello World!", res->body);
  2208. EXPECT_EQ(StatusCode::OK_200, res->status);
  2209. }
  2210. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2211. Server svr;
  2212. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2213. res.set_content("Hello World!", "text/plain");
  2214. });
  2215. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2216. auto se = detail::scope_exit([&] {
  2217. svr.stop();
  2218. thread.join();
  2219. ASSERT_FALSE(svr.is_running());
  2220. });
  2221. svr.wait_until_ready();
  2222. Client cli(HOST, PORT);
  2223. cli.set_connection_timeout(std::chrono::seconds(5));
  2224. auto res =
  2225. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2226. "application/json", [](uint64_t, uint64_t) { return false; });
  2227. ASSERT_TRUE(!res);
  2228. EXPECT_EQ(Error::Canceled, res.error());
  2229. }
  2230. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2231. Server svr;
  2232. svr.set_payload_max_length(200 * 1024 * 1024);
  2233. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2234. res.set_content(LARGE_DATA, "text/plain");
  2235. });
  2236. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2237. auto se = detail::scope_exit([&] {
  2238. svr.stop();
  2239. thread.join();
  2240. ASSERT_FALSE(svr.is_running());
  2241. });
  2242. svr.wait_until_ready();
  2243. Client cli(HOST, PORT);
  2244. cli.set_payload_max_length(200 * 1024 * 1024);
  2245. cli.set_connection_timeout(std::chrono::seconds(5));
  2246. auto res =
  2247. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2248. "application/json", [](uint64_t, uint64_t) { return false; });
  2249. ASSERT_TRUE(!res);
  2250. EXPECT_EQ(Error::Canceled, res.error());
  2251. }
  2252. TEST(CancelTest, NoCancelDelete) {
  2253. Server svr;
  2254. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2255. res.set_content("Hello World!", "text/plain");
  2256. });
  2257. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2258. auto se = detail::scope_exit([&] {
  2259. svr.stop();
  2260. thread.join();
  2261. ASSERT_FALSE(svr.is_running());
  2262. });
  2263. svr.wait_until_ready();
  2264. Client cli(HOST, PORT);
  2265. cli.set_connection_timeout(std::chrono::seconds(5));
  2266. auto res =
  2267. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2268. "application/json", [](uint64_t, uint64_t) { return true; });
  2269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2270. EXPECT_EQ("Hello World!", res->body);
  2271. EXPECT_EQ(StatusCode::OK_200, res->status);
  2272. }
  2273. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2274. Server svr;
  2275. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2276. res.set_content("Hello World!", "text/plain");
  2277. });
  2278. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2279. auto se = detail::scope_exit([&] {
  2280. svr.stop();
  2281. thread.join();
  2282. ASSERT_FALSE(svr.is_running());
  2283. });
  2284. svr.wait_until_ready();
  2285. Client cli(HOST, PORT);
  2286. cli.set_connection_timeout(std::chrono::seconds(5));
  2287. auto res =
  2288. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2289. "application/json", [](uint64_t, uint64_t) { return false; });
  2290. ASSERT_TRUE(!res);
  2291. EXPECT_EQ(Error::Canceled, res.error());
  2292. }
  2293. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2294. Server svr;
  2295. svr.set_payload_max_length(200 * 1024 * 1024);
  2296. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2297. res.set_content(LARGE_DATA, "text/plain");
  2298. });
  2299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2300. auto se = detail::scope_exit([&] {
  2301. svr.stop();
  2302. thread.join();
  2303. ASSERT_FALSE(svr.is_running());
  2304. });
  2305. svr.wait_until_ready();
  2306. Client cli(HOST, PORT);
  2307. cli.set_payload_max_length(200 * 1024 * 1024);
  2308. cli.set_connection_timeout(std::chrono::seconds(5));
  2309. auto res =
  2310. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2311. "application/json", [](uint64_t, uint64_t) { return false; });
  2312. ASSERT_TRUE(!res);
  2313. EXPECT_EQ(Error::Canceled, res.error());
  2314. }
  2315. static std::string remove_whitespace(const std::string &input) {
  2316. std::string output;
  2317. output.reserve(input.size());
  2318. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2319. [](unsigned char c) { return !std::isspace(c); });
  2320. return output;
  2321. }
  2322. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2323. auto host = "httpbingo.org";
  2324. auto path = std::string{"/basic-auth/hello/world"};
  2325. #ifdef CPPHTTPLIB_SSL_ENABLED
  2326. auto port = 443;
  2327. SSLClient cli(host, port);
  2328. #else
  2329. auto port = 80;
  2330. Client cli(host, port);
  2331. #endif
  2332. {
  2333. auto res = cli.Get(path);
  2334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2335. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2336. }
  2337. {
  2338. auto res = cli.Get(
  2339. path, Headers{make_basic_authentication_header("hello", "world")});
  2340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2341. auto body = remove_whitespace(res->body);
  2342. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2343. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2344. EXPECT_EQ(StatusCode::OK_200, res->status);
  2345. }
  2346. {
  2347. cli.set_basic_auth("hello", "world");
  2348. auto res = cli.Get(path);
  2349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2350. auto body = remove_whitespace(res->body);
  2351. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2352. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2353. EXPECT_EQ(StatusCode::OK_200, res->status);
  2354. }
  2355. {
  2356. cli.set_basic_auth("hello", "bad");
  2357. auto res = cli.Get(path);
  2358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2359. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2360. }
  2361. {
  2362. cli.set_basic_auth("bad", "world");
  2363. auto res = cli.Get(path);
  2364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2365. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2366. }
  2367. }
  2368. #ifdef CPPHTTPLIB_SSL_ENABLED
  2369. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2370. auto host = "httpbingo.org";
  2371. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2372. auto paths = std::vector<std::string>{
  2373. "/digest-auth/auth/hello/world/MD5",
  2374. "/digest-auth/auth/hello/world/SHA-256",
  2375. };
  2376. auto port = 443;
  2377. SSLClient cli(host, port);
  2378. {
  2379. auto res = cli.Get(unauth_path);
  2380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2381. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2382. }
  2383. {
  2384. cli.set_digest_auth("hello", "world");
  2385. for (const auto &path : paths) {
  2386. auto res = cli.Get(path.c_str());
  2387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2388. auto body = remove_whitespace(res->body);
  2389. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2390. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2391. EXPECT_EQ(StatusCode::OK_200, res->status);
  2392. }
  2393. cli.set_digest_auth("hello", "bad");
  2394. for (const auto &path : paths) {
  2395. auto res = cli.Get(path.c_str());
  2396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2397. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2398. }
  2399. }
  2400. }
  2401. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2402. // comma-separated list of challenges, and each challenge may itself carry a
  2403. // comma-separated auth-param list, so a server can legally offer Basic
  2404. // before Digest, either as two field lines or packed into one. Runs one 401
  2405. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2406. // value() joins them in receipt order) and checks that the retry carries a
  2407. // well-formed Digest Authorization header naming expected_realm.
  2408. static void
  2409. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2410. const std::string &expected_realm) {
  2411. std::atomic<int> hits{0};
  2412. Server svr;
  2413. svr.Get("/x", [&](const Request &req, Response &res) {
  2414. if (++hits == 1) {
  2415. res.status = StatusCode::Unauthorized_401;
  2416. for (const auto &challenge : challenges) {
  2417. res.set_header("WWW-Authenticate", challenge);
  2418. }
  2419. } else {
  2420. auto authorization = req.get_header_value("Authorization");
  2421. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2422. EXPECT_NE(std::string::npos,
  2423. authorization.find("realm=\"" + expected_realm + "\""));
  2424. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2425. res.set_content("ok", "text/plain");
  2426. }
  2427. });
  2428. auto port = svr.bind_to_any_port(HOST);
  2429. std::thread t([&]() { svr.listen_after_bind(); });
  2430. auto se = detail::scope_exit([&] {
  2431. svr.stop();
  2432. t.join();
  2433. });
  2434. svr.wait_until_ready();
  2435. Client cli(HOST, port);
  2436. cli.set_digest_auth("hello", "world");
  2437. auto res = cli.Get("/x");
  2438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2439. EXPECT_EQ(2, hits.load());
  2440. }
  2441. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2442. static const char *kDigestChallenge =
  2443. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2444. "algorithm=MD5";
  2445. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2446. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2447. "testrealm");
  2448. }
  2449. // Same challenge list with the schemes in the opposite order, to make sure
  2450. // the fix above didn't just special-case "Basic first".
  2451. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2452. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2453. "testrealm");
  2454. }
  2455. // A comma inside a quoted auth-param value must not be mistaken for the
  2456. // separator between two challenges (or two auth-params).
  2457. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2458. run_digest_challenge_list_test(
  2459. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2460. "algorithm=MD5"},
  2461. "test,realm");
  2462. }
  2463. #endif
  2464. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2465. auto host = "google.com";
  2466. auto another_host = "example.com";
  2467. auto wrong_ip = "0.0.0.0";
  2468. #ifdef CPPHTTPLIB_SSL_ENABLED
  2469. SSLClient cli(host);
  2470. #else
  2471. Client cli(host);
  2472. #endif
  2473. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2476. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2477. }
  2478. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2479. auto host = "google.com";
  2480. auto wrong_ip = "0.0.0.0";
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. SSLClient cli(host);
  2483. #else
  2484. Client cli(host);
  2485. #endif
  2486. cli.set_hostname_addr_map({{host, wrong_ip}});
  2487. auto res = cli.Get("/");
  2488. ASSERT_TRUE(!res);
  2489. EXPECT_EQ(Error::Connection, res.error());
  2490. }
  2491. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2492. // A mapped value that is not an IP literal must be resolved. "localhost"
  2493. // resolves from the hosts file, so this test needs no external DNS.
  2494. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2495. auto host = "target.invalid";
  2496. Server svr;
  2497. std::string received_host;
  2498. svr.Get("/hi", [&](const Request &req, Response &res) {
  2499. received_host = req.get_header_value("Host");
  2500. res.set_content("Hello World!", "text/plain");
  2501. });
  2502. auto port = svr.bind_to_any_port(HOST);
  2503. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2504. auto se = detail::scope_exit([&] {
  2505. svr.stop();
  2506. thread.join();
  2507. ASSERT_FALSE(svr.is_running());
  2508. });
  2509. svr.wait_until_ready();
  2510. Client cli(host, port);
  2511. cli.set_hostname_addr_map({{host, HOST}});
  2512. auto res = cli.Get("/hi");
  2513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2514. EXPECT_EQ(StatusCode::OK_200, res->status);
  2515. // The mapping only redirects the connection; the identity stays host_.
  2516. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2517. }
  2518. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2519. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2520. auto host = "target.invalid";
  2521. Server svr;
  2522. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2523. res.set_content("Hello World!", "text/plain");
  2524. });
  2525. auto port = svr.bind_to_any_port("127.0.0.1");
  2526. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2527. auto se = detail::scope_exit([&] {
  2528. svr.stop();
  2529. thread.join();
  2530. ASSERT_FALSE(svr.is_running());
  2531. });
  2532. svr.wait_until_ready();
  2533. Client cli(host, port);
  2534. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2535. auto res = cli.Get("/hi");
  2536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. }
  2539. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2540. // An empty mapped value must leave host_ as the connection target. Without
  2541. // that guard the empty value would become the host argument, getaddrinfo
  2542. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2543. // loopback - silently connecting somewhere the caller never asked for.
  2544. // The server listens on loopback, so such a fallback would succeed and is
  2545. // therefore observable as a failure of this test.
  2546. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2547. Server svr;
  2548. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2549. res.set_content("Hello World!", "text/plain");
  2550. });
  2551. auto port = svr.bind_to_any_port(HOST);
  2552. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2553. auto se = detail::scope_exit([&] {
  2554. svr.stop();
  2555. thread.join();
  2556. ASSERT_FALSE(svr.is_running());
  2557. });
  2558. svr.wait_until_ready();
  2559. Client cli(blackhole, port);
  2560. cli.set_hostname_addr_map({{blackhole, ""}});
  2561. cli.set_connection_timeout(1);
  2562. auto res = cli.Get("/hi");
  2563. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2564. }
  2565. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2566. auto host = "httpbingo.org";
  2567. auto path = std::string{"/absolute-redirect/3"};
  2568. #ifdef CPPHTTPLIB_SSL_ENABLED
  2569. SSLClient cli(host);
  2570. #else
  2571. Client cli(host);
  2572. #endif
  2573. cli.set_follow_location(true);
  2574. auto res = cli.Get(path);
  2575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2576. EXPECT_EQ(StatusCode::OK_200, res->status);
  2577. }
  2578. TEST(RedirectTest, Redirect_Online) {
  2579. auto host = "httpbingo.org";
  2580. auto path = std::string{"/redirect/3"};
  2581. #ifdef CPPHTTPLIB_SSL_ENABLED
  2582. SSLClient cli(host);
  2583. #else
  2584. Client cli(host);
  2585. #endif
  2586. cli.set_follow_location(true);
  2587. auto res = cli.Get(path);
  2588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2589. EXPECT_EQ(StatusCode::OK_200, res->status);
  2590. }
  2591. TEST(RelativeRedirectTest, Redirect_Online) {
  2592. auto host = "httpbingo.org";
  2593. auto path = std::string{"/relative-redirect/3"};
  2594. #ifdef CPPHTTPLIB_SSL_ENABLED
  2595. SSLClient cli(host);
  2596. #else
  2597. Client cli(host);
  2598. #endif
  2599. cli.set_follow_location(true);
  2600. auto res = cli.Get(path);
  2601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2602. EXPECT_EQ(StatusCode::OK_200, res->status);
  2603. }
  2604. TEST(TooManyRedirectTest, Redirect_Online) {
  2605. auto host = "httpbingo.org";
  2606. auto path = std::string{"/redirect/21"};
  2607. #ifdef CPPHTTPLIB_SSL_ENABLED
  2608. SSLClient cli(host);
  2609. #else
  2610. Client cli(host);
  2611. #endif
  2612. cli.set_follow_location(true);
  2613. auto res = cli.Get(path);
  2614. ASSERT_TRUE(!res);
  2615. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2616. }
  2617. #ifdef CPPHTTPLIB_SSL_ENABLED
  2618. TEST(YahooRedirectTest, Redirect_Online) {
  2619. Client cli("yahoo.com");
  2620. auto res = cli.Get("/");
  2621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2622. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2623. cli.set_follow_location(true);
  2624. res = cli.Get("/");
  2625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2626. EXPECT_EQ(StatusCode::OK_200, res->status);
  2627. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2628. }
  2629. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2630. #define REDIR_HOST "httpbingo.org"
  2631. #define REDIR_PATH "/redirect-to"
  2632. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2633. SSLClient cli(REDIR_HOST);
  2634. cli.set_follow_location(true);
  2635. auto res =
  2636. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2638. EXPECT_EQ(StatusCode::OK_200, res->status);
  2639. }
  2640. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2641. SSLClient cli(REDIR_HOST);
  2642. cli.set_follow_location(true);
  2643. Params params;
  2644. params.emplace("url", "http://example.com");
  2645. params.emplace("status_code", "302");
  2646. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2648. EXPECT_EQ(StatusCode::OK_200, res->status);
  2649. }
  2650. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2651. SSLClient cli(REDIR_HOST);
  2652. cli.set_follow_location(true);
  2653. Params params;
  2654. params.emplace("url", "http://example.com");
  2655. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2657. EXPECT_EQ(StatusCode::OK_200, res->status);
  2658. }
  2659. TEST(UrlWithSpace, Redirect_Online) {
  2660. SSLClient cli("edge.forgecdn.net");
  2661. cli.set_follow_location(true);
  2662. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2664. EXPECT_EQ(StatusCode::OK_200, res->status);
  2665. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2666. }
  2667. #endif
  2668. #if !defined(_WIN32) && !defined(_WIN64)
  2669. TEST(ReceiveSignals, Signal) {
  2670. auto setupSignalHandlers = []() {
  2671. struct sigaction act;
  2672. sigemptyset(&act.sa_mask);
  2673. act.sa_flags = SA_SIGINFO;
  2674. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2675. switch (sig) {
  2676. case SIGINT:
  2677. default: break;
  2678. }
  2679. };
  2680. ::sigaction(SIGINT, &act, nullptr);
  2681. };
  2682. Server svr;
  2683. int port = 0;
  2684. auto thread = std::thread([&]() {
  2685. setupSignalHandlers();
  2686. port = svr.bind_to_any_port(HOST);
  2687. svr.listen_after_bind();
  2688. });
  2689. auto se = detail::scope_exit([&] {
  2690. svr.stop();
  2691. thread.join();
  2692. ASSERT_FALSE(svr.is_running());
  2693. });
  2694. svr.wait_until_ready();
  2695. ASSERT_TRUE(svr.is_running());
  2696. pthread_kill(thread.native_handle(), SIGINT);
  2697. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2698. ASSERT_TRUE(svr.is_running());
  2699. }
  2700. #endif
  2701. TEST(RedirectToDifferentPort, Redirect) {
  2702. Server svr1;
  2703. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2704. res.set_content("Hello World!", "text/plain");
  2705. });
  2706. int svr1_port = 0;
  2707. auto thread1 = std::thread([&]() {
  2708. svr1_port = svr1.bind_to_any_port(HOST);
  2709. svr1.listen_after_bind();
  2710. });
  2711. Server svr2;
  2712. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2713. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2714. });
  2715. int svr2_port = 0;
  2716. auto thread2 = std::thread([&]() {
  2717. svr2_port = svr2.bind_to_any_port(HOST);
  2718. svr2.listen_after_bind();
  2719. });
  2720. auto se = detail::scope_exit([&] {
  2721. svr2.stop();
  2722. thread2.join();
  2723. svr1.stop();
  2724. thread1.join();
  2725. ASSERT_FALSE(svr2.is_running());
  2726. ASSERT_FALSE(svr1.is_running());
  2727. });
  2728. svr1.wait_until_ready();
  2729. svr2.wait_until_ready();
  2730. Client cli("localhost", svr2_port);
  2731. cli.set_follow_location(true);
  2732. auto res = cli.Get("/2");
  2733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2734. EXPECT_EQ(StatusCode::OK_200, res->status);
  2735. EXPECT_EQ("Hello World!", res->body);
  2736. }
  2737. static void
  2738. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2739. Server svr1;
  2740. std::string captured_authorization;
  2741. svr1.Get("/target", [&](const Request &req, Response &res) {
  2742. captured_authorization = req.get_header_value("Authorization");
  2743. res.set_content("OK", "text/plain");
  2744. });
  2745. int svr1_port = 0;
  2746. auto thread1 = std::thread([&]() {
  2747. svr1_port = svr1.bind_to_any_port(HOST);
  2748. svr1.listen_after_bind();
  2749. });
  2750. Server svr2;
  2751. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2752. res.set_redirect(
  2753. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2754. });
  2755. int svr2_port = 0;
  2756. auto thread2 = std::thread([&]() {
  2757. svr2_port = svr2.bind_to_any_port(HOST);
  2758. svr2.listen_after_bind();
  2759. });
  2760. auto se = detail::scope_exit([&] {
  2761. svr2.stop();
  2762. thread2.join();
  2763. svr1.stop();
  2764. thread1.join();
  2765. ASSERT_FALSE(svr2.is_running());
  2766. ASSERT_FALSE(svr1.is_running());
  2767. });
  2768. svr1.wait_until_ready();
  2769. svr2.wait_until_ready();
  2770. Client cli("localhost", svr2_port);
  2771. cli.set_follow_location(true);
  2772. set_auth(cli);
  2773. auto res = cli.Get("/redir");
  2774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2775. EXPECT_EQ(StatusCode::OK_200, res->status);
  2776. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2777. EXPECT_TRUE(captured_authorization.empty());
  2778. }
  2779. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2780. TestDoNotForwardCredentialsOnRedirect(
  2781. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2782. }
  2783. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2784. TestDoNotForwardCredentialsOnRedirect(
  2785. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2786. }
  2787. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2788. Server svr1;
  2789. std::string captured_cookie;
  2790. bool target_hit = false;
  2791. svr1.Get("/target", [&](const Request &req, Response &res) {
  2792. captured_cookie = req.get_header_value("Cookie");
  2793. target_hit = true;
  2794. res.set_content("OK", "text/plain");
  2795. });
  2796. int svr1_port = 0;
  2797. auto thread1 = std::thread([&]() {
  2798. svr1_port = svr1.bind_to_any_port(HOST);
  2799. svr1.listen_after_bind();
  2800. });
  2801. Server svr2;
  2802. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2803. res.set_redirect(
  2804. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2805. });
  2806. int svr2_port = 0;
  2807. auto thread2 = std::thread([&]() {
  2808. svr2_port = svr2.bind_to_any_port(HOST);
  2809. svr2.listen_after_bind();
  2810. });
  2811. auto se = detail::scope_exit([&] {
  2812. svr2.stop();
  2813. thread2.join();
  2814. svr1.stop();
  2815. thread1.join();
  2816. ASSERT_FALSE(svr2.is_running());
  2817. ASSERT_FALSE(svr1.is_running());
  2818. });
  2819. svr1.wait_until_ready();
  2820. svr2.wait_until_ready();
  2821. Client cli("localhost", svr2_port);
  2822. cli.set_follow_location(true);
  2823. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2824. auto res = cli.Get("/redir", headers);
  2825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2826. EXPECT_EQ(StatusCode::OK_200, res->status);
  2827. EXPECT_TRUE(target_hit);
  2828. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2829. EXPECT_TRUE(captured_cookie.empty());
  2830. }
  2831. TEST(RedirectToSamePort, ForwardCookie) {
  2832. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2833. // header so that ordinary session flows keep working.
  2834. Server svr;
  2835. std::string captured_cookie;
  2836. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2837. res.set_redirect("/target", 302);
  2838. });
  2839. svr.Get("/target", [&](const Request &req, Response &res) {
  2840. captured_cookie = req.get_header_value("Cookie");
  2841. res.set_content("OK", "text/plain");
  2842. });
  2843. auto port = svr.bind_to_any_port(HOST);
  2844. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2845. auto se = detail::scope_exit([&] {
  2846. svr.stop();
  2847. thread.join();
  2848. ASSERT_FALSE(svr.is_running());
  2849. });
  2850. svr.wait_until_ready();
  2851. Client cli(HOST, port);
  2852. cli.set_follow_location(true);
  2853. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2854. auto res = cli.Get("/redir", headers);
  2855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2856. EXPECT_EQ(StatusCode::OK_200, res->status);
  2857. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2858. }
  2859. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2860. Server svr;
  2861. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2862. // Port number that overflows int — should not crash
  2863. res.set_redirect("http://localhost:99999999999999999999/target");
  2864. });
  2865. auto port = svr.bind_to_any_port(HOST);
  2866. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2867. auto se = detail::scope_exit([&] {
  2868. svr.stop();
  2869. thread.join();
  2870. ASSERT_FALSE(svr.is_running());
  2871. });
  2872. svr.wait_until_ready();
  2873. Client cli(HOST, port);
  2874. cli.set_follow_location(true);
  2875. auto res = cli.Get("/redir");
  2876. // Should fail gracefully, not crash (no valid response due to bad port)
  2877. EXPECT_FALSE(res);
  2878. }
  2879. TEST(RedirectFromPageWithContent, Redirect) {
  2880. Server svr;
  2881. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2882. res.set_content("___", "text/plain");
  2883. res.set_redirect("/2");
  2884. });
  2885. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2886. res.set_content("Hello World!", "text/plain");
  2887. });
  2888. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2889. auto se = detail::scope_exit([&] {
  2890. svr.stop();
  2891. th.join();
  2892. ASSERT_FALSE(svr.is_running());
  2893. });
  2894. svr.wait_until_ready();
  2895. {
  2896. Client cli("localhost", PORT);
  2897. cli.set_follow_location(true);
  2898. std::string body;
  2899. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2900. body.append(data, data_length);
  2901. return true;
  2902. });
  2903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2904. EXPECT_EQ(StatusCode::OK_200, res->status);
  2905. EXPECT_EQ("Hello World!", body);
  2906. }
  2907. {
  2908. Client cli("localhost", PORT);
  2909. std::string body;
  2910. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2911. body.append(data, data_length);
  2912. return true;
  2913. });
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::Found_302, res->status);
  2916. EXPECT_EQ("___", body);
  2917. }
  2918. }
  2919. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2920. Server svr;
  2921. auto port_str = std::to_string(PORT);
  2922. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2923. auto expected_host = "[::1]:" + port_str;
  2924. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2925. res.set_content("___", "text/plain");
  2926. // res.set_redirect("/2");
  2927. res.set_redirect(redirect_url);
  2928. });
  2929. svr.Get("/2", [&](const Request &req, Response &res) {
  2930. auto host_header = req.headers.find("Host");
  2931. ASSERT_TRUE(host_header != req.headers.end());
  2932. EXPECT_EQ(expected_host, host_header->second);
  2933. res.set_content("Hello World!", "text/plain");
  2934. });
  2935. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2936. auto se = detail::scope_exit([&] {
  2937. svr.stop();
  2938. th.join();
  2939. ASSERT_FALSE(svr.is_running());
  2940. });
  2941. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2942. // actually starts anything, so the condition !svr.is_running() will
  2943. // always remain true, and the loop never stops.
  2944. // This basically counts how many milliseconds have passed since the
  2945. // call to svr.listen(), and if after 5 seconds nothing started yet
  2946. // aborts the test.
  2947. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2948. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2949. ASSERT_LT(milliseconds, 5000U);
  2950. }
  2951. {
  2952. Client cli("::1", PORT);
  2953. cli.set_follow_location(true);
  2954. std::string body;
  2955. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2956. body.append(data, data_length);
  2957. return true;
  2958. });
  2959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2960. EXPECT_EQ(StatusCode::OK_200, res->status);
  2961. EXPECT_EQ("Hello World!", body);
  2962. }
  2963. {
  2964. Client cli("::1", PORT);
  2965. std::string body;
  2966. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2967. body.append(data, data_length);
  2968. return true;
  2969. });
  2970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2971. EXPECT_EQ(StatusCode::Found_302, res->status);
  2972. EXPECT_EQ("___", body);
  2973. }
  2974. }
  2975. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2976. Server svr;
  2977. svr.Get("/foo", [](const Request &req, Response &res) {
  2978. auto a = req.params.find("a");
  2979. if (a != req.params.end()) {
  2980. res.set_content((*a).second, "text/plain");
  2981. res.status = StatusCode::OK_200;
  2982. } else {
  2983. res.status = StatusCode::BadRequest_400;
  2984. }
  2985. });
  2986. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2987. auto se = detail::scope_exit([&] {
  2988. svr.stop();
  2989. thread.join();
  2990. ASSERT_FALSE(svr.is_running());
  2991. });
  2992. svr.wait_until_ready();
  2993. {
  2994. Client cli(HOST, PORT);
  2995. cli.set_path_encode(false);
  2996. auto res = cli.Get("/foo?a=explicitly+encoded");
  2997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2998. EXPECT_EQ(StatusCode::OK_200, res->status);
  2999. // This expects it back with a space, as the `+` won't have been
  3000. // url-encoded, and server-side the params get decoded turning `+`
  3001. // into spaces.
  3002. EXPECT_EQ("explicitly encoded", res->body);
  3003. }
  3004. }
  3005. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3006. // When path encoding is disabled the client must transmit the supplied
  3007. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3008. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3009. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3010. // than a space (0x20). Assert on the raw wire target to catch this.
  3011. Server svr;
  3012. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3013. svr.Get("/foo", [&](const Request &req, Response &res) {
  3014. EXPECT_EQ(expected_target, req.target);
  3015. res.status = StatusCode::OK_200;
  3016. });
  3017. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3018. auto se = detail::scope_exit([&] {
  3019. svr.stop();
  3020. thread.join();
  3021. ASSERT_FALSE(svr.is_running());
  3022. });
  3023. svr.wait_until_ready();
  3024. {
  3025. Client cli(HOST, PORT);
  3026. cli.set_path_encode(false);
  3027. auto res = cli.Get(expected_target.c_str());
  3028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3029. EXPECT_EQ(StatusCode::OK_200, res->status);
  3030. }
  3031. }
  3032. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3033. // `open_stream()` used to skip the path encoding that the buffered send
  3034. // path applies, so the same `path` produced different bytes in the request
  3035. // line depending on which API was used. Assert the two agree.
  3036. Server svr;
  3037. std::string target;
  3038. svr.Get(".*", [&](const Request &req, Response &res) {
  3039. target = req.target;
  3040. res.status = StatusCode::OK_200;
  3041. });
  3042. auto port = svr.bind_to_any_port(HOST);
  3043. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3044. auto se = detail::scope_exit([&] {
  3045. svr.stop();
  3046. thread.join();
  3047. ASSERT_FALSE(svr.is_running());
  3048. });
  3049. svr.wait_until_ready();
  3050. struct {
  3051. const char *path;
  3052. const char *expected;
  3053. } cases[] = {
  3054. {"/a b?x=1", "/a%20b?x=1"},
  3055. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3056. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3057. };
  3058. for (const auto &c : cases) {
  3059. Client cli(HOST, port);
  3060. target.clear();
  3061. auto res = cli.Get(c.path);
  3062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3063. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3064. auto buffered_target = target;
  3065. target.clear();
  3066. auto handle = cli.open_stream("GET", c.path);
  3067. EXPECT_TRUE(handle.is_valid())
  3068. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3069. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3070. }
  3071. }
  3072. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3073. // The `set_path_encode(false)` contract — transmit the supplied target
  3074. // verbatim — must hold for the streaming API too.
  3075. Server svr;
  3076. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3077. std::string target;
  3078. svr.Get("/foo", [&](const Request &req, Response &res) {
  3079. target = req.target;
  3080. res.status = StatusCode::OK_200;
  3081. });
  3082. auto port = svr.bind_to_any_port(HOST);
  3083. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3084. auto se = detail::scope_exit([&] {
  3085. svr.stop();
  3086. thread.join();
  3087. ASSERT_FALSE(svr.is_running());
  3088. });
  3089. svr.wait_until_ready();
  3090. {
  3091. Client cli(HOST, port);
  3092. cli.set_path_encode(false);
  3093. auto handle = cli.open_stream("GET", expected_target);
  3094. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3095. EXPECT_EQ(expected_target, target);
  3096. }
  3097. }
  3098. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3099. // With path encoding enabled a CR/LF in the target is percent-encoded
  3100. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3101. // write_request_line still backstops `set_path_encode(false)`, which is
  3102. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3103. Server svr;
  3104. // Captured before routing: the decoded path contains a newline, which a
  3105. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3106. std::string target;
  3107. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3108. target = req.target;
  3109. res.status = StatusCode::OK_200;
  3110. return Server::HandlerResponse::Handled;
  3111. });
  3112. auto port = svr.bind_to_any_port(HOST);
  3113. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3114. auto se = detail::scope_exit([&] {
  3115. svr.stop();
  3116. thread.join();
  3117. ASSERT_FALSE(svr.is_running());
  3118. });
  3119. svr.wait_until_ready();
  3120. {
  3121. Client cli(HOST, port);
  3122. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3123. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3124. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3125. }
  3126. }
  3127. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3128. // Nothing may reach the wire: a raw CR/LF target would split the request
  3129. // line and inject headers.
  3130. Server svr;
  3131. // Pre-routing so that "not called" means nothing reached the server at all,
  3132. // rather than merely failing to match a handler pattern.
  3133. auto handler_called = false;
  3134. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3135. handler_called = true;
  3136. res.status = StatusCode::OK_200;
  3137. return Server::HandlerResponse::Handled;
  3138. });
  3139. auto port = svr.bind_to_any_port(HOST);
  3140. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3141. auto se = detail::scope_exit([&] {
  3142. svr.stop();
  3143. thread.join();
  3144. ASSERT_FALSE(svr.is_running());
  3145. });
  3146. svr.wait_until_ready();
  3147. {
  3148. Client cli(HOST, port);
  3149. cli.set_path_encode(false);
  3150. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3151. EXPECT_FALSE(handle.is_valid());
  3152. EXPECT_EQ(Error::Write, handle.error);
  3153. EXPECT_FALSE(handler_called);
  3154. }
  3155. }
  3156. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3157. // Which of the two branches runs is decided by whether the query component
  3158. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3159. // an empty query and must still fall back to building one from
  3160. // `req.params`, while a non-empty query must win over `req.params`.
  3161. Server svr;
  3162. std::string target;
  3163. svr.Get("/foo", [&](const Request &req, Response &res) {
  3164. target = req.target;
  3165. res.status = StatusCode::OK_200;
  3166. });
  3167. auto port = svr.bind_to_any_port(HOST);
  3168. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3169. auto se = detail::scope_exit([&] {
  3170. svr.stop();
  3171. thread.join();
  3172. ASSERT_FALSE(svr.is_running());
  3173. });
  3174. svr.wait_until_ready();
  3175. {
  3176. // Trailing `?` -> empty query component -> `req.params` is used.
  3177. Client cli(HOST, port);
  3178. Request req;
  3179. req.method = "GET";
  3180. req.path = "/foo?";
  3181. req.params.emplace("a", "1");
  3182. target.clear();
  3183. auto res = cli.send(req);
  3184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3185. EXPECT_EQ("/foo?a=1", target);
  3186. }
  3187. {
  3188. // Non-empty query in `req.path` -> `req.params` is not appended.
  3189. Client cli(HOST, port);
  3190. Request req;
  3191. req.method = "GET";
  3192. req.path = "/foo?b=2";
  3193. req.params.emplace("a", "1");
  3194. target.clear();
  3195. auto res = cli.send(req);
  3196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3197. EXPECT_EQ("/foo?b=2", target);
  3198. }
  3199. }
  3200. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3201. Server svr;
  3202. svr.Get("/", [](const Request &req, Response &) {
  3203. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3204. });
  3205. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3206. auto se = detail::scope_exit([&] {
  3207. svr.stop();
  3208. thread.join();
  3209. ASSERT_FALSE(svr.is_running());
  3210. });
  3211. svr.wait_until_ready();
  3212. {
  3213. Client cli(HOST, PORT);
  3214. cli.set_path_encode(false);
  3215. auto res = cli.Get("/?something=%0A");
  3216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3217. EXPECT_EQ(StatusCode::OK_200, res->status);
  3218. }
  3219. }
  3220. TEST(BindServerTest, BindDualStack) {
  3221. Server svr;
  3222. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3223. res.set_content("Hello World!", "text/plain");
  3224. });
  3225. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3226. auto se = detail::scope_exit([&] {
  3227. svr.stop();
  3228. thread.join();
  3229. ASSERT_FALSE(svr.is_running());
  3230. });
  3231. svr.wait_until_ready();
  3232. {
  3233. Client cli("127.0.0.1", PORT);
  3234. auto res = cli.Get("/1");
  3235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3236. EXPECT_EQ(StatusCode::OK_200, res->status);
  3237. EXPECT_EQ("Hello World!", res->body);
  3238. }
  3239. {
  3240. Client cli("::1", PORT);
  3241. auto res = cli.Get("/1");
  3242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3243. EXPECT_EQ(StatusCode::OK_200, res->status);
  3244. EXPECT_EQ("Hello World!", res->body);
  3245. }
  3246. }
  3247. TEST(BindServerTest, BindAndListenSeparately) {
  3248. Server svr;
  3249. int port = svr.bind_to_any_port("0.0.0.0");
  3250. ASSERT_TRUE(svr.is_valid());
  3251. ASSERT_TRUE(port > 0);
  3252. svr.stop();
  3253. }
  3254. // Reports whether anything is still listening on a loopback port. A plain
  3255. // connect() is used instead of a Client request because a socket left bound by
  3256. // mistake accepts the connection into its backlog and never answers, which
  3257. // would hang the test instead of failing it.
  3258. static bool is_loopback_port_accepting(int port) {
  3259. sockaddr_in addr{};
  3260. addr.sin_family = AF_INET;
  3261. addr.sin_port = htons(static_cast<uint16_t>(port));
  3262. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3263. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3264. EXPECT_NE(sock, INVALID_SOCKET);
  3265. if (sock == INVALID_SOCKET) { return false; }
  3266. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3267. static_cast<socklen_t>(sizeof(addr)));
  3268. detail::close_socket(sock);
  3269. return ret == 0;
  3270. }
  3271. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3272. Server svr;
  3273. auto port = svr.bind_to_any_port("127.0.0.1");
  3274. ASSERT_TRUE(port > 0);
  3275. svr.stop();
  3276. // bind_to_any_port() already called listen(2), so until stop() closed the
  3277. // descriptor the port kept accepting connections into the backlog. ASSERT
  3278. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3279. // below blocks forever in the accept loop.
  3280. ASSERT_FALSE(is_loopback_port_accepting(port));
  3281. // Nothing is left to accept on, so listen_after_bind() must report failure
  3282. // instead of returning success without ever serving.
  3283. EXPECT_FALSE(svr.listen_after_bind());
  3284. // The failed listen marks the server decommissioned, so a waiter returns
  3285. // instead of spinning forever.
  3286. svr.wait_until_ready();
  3287. }
  3288. #ifdef CPPHTTPLIB_SSL_ENABLED
  3289. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3290. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3291. CLIENT_CA_CERT_DIR);
  3292. int port = svr.bind_to_any_port("0.0.0.0");
  3293. ASSERT_TRUE(svr.is_valid());
  3294. ASSERT_TRUE(port > 0);
  3295. svr.stop();
  3296. }
  3297. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3298. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3299. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3300. int port = svr.bind_to_any_port("0.0.0.0");
  3301. ASSERT_TRUE(svr.is_valid());
  3302. ASSERT_TRUE(port > 0);
  3303. svr.stop();
  3304. }
  3305. TEST(BindServerTest, UpdateCertsPem) {
  3306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3307. int port = svr.bind_to_any_port("0.0.0.0");
  3308. ASSERT_TRUE(svr.is_valid());
  3309. ASSERT_TRUE(port > 0);
  3310. // Read PEM files
  3311. std::string cert_pem, key_pem, ca_pem;
  3312. read_file(SERVER_CERT_FILE, cert_pem);
  3313. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3314. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3315. // Update server certificates using PEM API
  3316. ASSERT_TRUE(
  3317. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3318. ASSERT_TRUE(svr.is_valid());
  3319. svr.stop();
  3320. }
  3321. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3322. // Start server with client CA (enables client auth)
  3323. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3324. ASSERT_TRUE(svr.is_valid());
  3325. bool handler_called = false;
  3326. svr.Get("/test", [&](const Request &req, Response &res) {
  3327. handler_called = true;
  3328. // Verify client certificate is present
  3329. auto cert = req.peer_cert();
  3330. EXPECT_TRUE(static_cast<bool>(cert));
  3331. res.set_content("ok", "text/plain");
  3332. });
  3333. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3334. auto se = detail::scope_exit([&] {
  3335. svr.stop();
  3336. t.join();
  3337. ASSERT_FALSE(svr.is_running());
  3338. });
  3339. svr.wait_until_ready();
  3340. // Read PEM files
  3341. std::string cert_pem, key_pem, ca_pem;
  3342. read_file(SERVER_CERT_FILE, cert_pem);
  3343. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3344. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3345. // Update server certificates and client CA using PEM API while server running
  3346. ASSERT_TRUE(
  3347. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3348. // Connect with client certificate
  3349. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3350. cli.enable_server_certificate_verification(false);
  3351. cli.set_connection_timeout(30);
  3352. auto res = cli.Get("/test");
  3353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3354. ASSERT_EQ(StatusCode::OK_200, res->status);
  3355. ASSERT_TRUE(handler_called);
  3356. EXPECT_EQ("ok", res->body);
  3357. }
  3358. #endif
  3359. TEST(ErrorHandlerTest, ContentLength) {
  3360. Server svr;
  3361. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3362. res.status = StatusCode::OK_200;
  3363. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3364. "text/html"); // <= Content-Length still 13
  3365. });
  3366. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3367. res.set_content("Hello World!\n", "text/plain");
  3368. res.status = 524;
  3369. });
  3370. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3371. auto se = detail::scope_exit([&] {
  3372. svr.stop();
  3373. thread.join();
  3374. ASSERT_FALSE(svr.is_running());
  3375. });
  3376. svr.wait_until_ready();
  3377. {
  3378. Client cli(HOST, PORT);
  3379. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3381. EXPECT_EQ(StatusCode::OK_200, res->status);
  3382. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3383. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3384. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3385. }
  3386. }
  3387. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3388. TEST(ExceptionTest, WithoutExceptionHandler) {
  3389. Server svr;
  3390. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3391. throw std::runtime_error("exception...");
  3392. });
  3393. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3394. throw std::runtime_error("exception\r\n...");
  3395. });
  3396. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3397. auto se = detail::scope_exit([&] {
  3398. svr.stop();
  3399. listen_thread.join();
  3400. ASSERT_FALSE(svr.is_running());
  3401. });
  3402. svr.wait_until_ready();
  3403. Client cli("localhost", PORT);
  3404. {
  3405. auto res = cli.Get("/exception");
  3406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3407. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3408. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3409. }
  3410. {
  3411. auto res = cli.Get("/unknown");
  3412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3413. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3414. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3415. }
  3416. }
  3417. TEST(ExceptionTest, WithExceptionHandler) {
  3418. Server svr;
  3419. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3420. std::exception_ptr ep) {
  3421. EXPECT_FALSE(ep == nullptr);
  3422. try {
  3423. std::rethrow_exception(ep);
  3424. } catch (std::exception &e) {
  3425. EXPECT_EQ("abc", std::string(e.what()));
  3426. } catch (...) {}
  3427. res.status = StatusCode::InternalServerError_500;
  3428. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3429. "text/html"); // <= Content-Length still 13 at this point
  3430. });
  3431. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3432. res.set_content("Hello World!\n", "text/plain");
  3433. throw std::runtime_error("abc");
  3434. });
  3435. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3436. auto se = detail::scope_exit([&] {
  3437. svr.stop();
  3438. thread.join();
  3439. ASSERT_FALSE(svr.is_running());
  3440. });
  3441. svr.wait_until_ready();
  3442. for (size_t i = 0; i < 10; i++) {
  3443. Client cli(HOST, PORT);
  3444. for (size_t j = 0; j < 100; j++) {
  3445. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3447. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3448. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3449. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3450. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3451. }
  3452. cli.set_keep_alive(true);
  3453. for (size_t j = 0; j < 100; j++) {
  3454. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3456. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3457. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3458. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3459. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3460. }
  3461. }
  3462. }
  3463. TEST(ExceptionTest, AndErrorHandler) {
  3464. Server svr;
  3465. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3466. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3467. });
  3468. svr.set_exception_handler(
  3469. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3470. EXPECT_FALSE(ep == nullptr);
  3471. try {
  3472. std::rethrow_exception(ep);
  3473. } catch (std::exception &e) {
  3474. res.set_content(e.what(), "text/html");
  3475. } catch (...) {}
  3476. res.status = StatusCode::InternalServerError_500;
  3477. });
  3478. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3479. throw std::runtime_error("EXCEPTION");
  3480. });
  3481. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3482. res.set_content("ERROR", "text/html");
  3483. res.status = StatusCode::InternalServerError_500;
  3484. });
  3485. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3486. auto se = detail::scope_exit([&] {
  3487. svr.stop();
  3488. thread.join();
  3489. ASSERT_FALSE(svr.is_running());
  3490. });
  3491. svr.wait_until_ready();
  3492. Client cli(HOST, PORT);
  3493. {
  3494. auto res = cli.Get("/exception");
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3497. EXPECT_EQ("EXCEPTION", res->body);
  3498. }
  3499. {
  3500. auto res = cli.Get("/error");
  3501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3502. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3503. EXPECT_EQ("ERROR", res->body);
  3504. }
  3505. {
  3506. auto res = cli.Get("/invalid");
  3507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3508. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3509. EXPECT_EQ("NOT_FOUND", res->body);
  3510. }
  3511. }
  3512. #endif
  3513. TEST(NoContentTest, ContentLength) {
  3514. Server svr;
  3515. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3516. res.status = StatusCode::NoContent_204;
  3517. });
  3518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3519. auto se = detail::scope_exit([&] {
  3520. svr.stop();
  3521. thread.join();
  3522. ASSERT_FALSE(svr.is_running());
  3523. });
  3524. svr.wait_until_ready();
  3525. {
  3526. Client cli(HOST, PORT);
  3527. auto res = cli.Get("/hi");
  3528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3529. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3530. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3531. }
  3532. }
  3533. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3534. #ifdef CPPHTTPLIB_SSL_ENABLED
  3535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3536. ASSERT_TRUE(svr.is_valid());
  3537. #else
  3538. Server svr;
  3539. #endif
  3540. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3541. if (req.path == "/routing_handler") {
  3542. res.set_header("PRE_ROUTING", "on");
  3543. res.set_content("Routing Handler", "text/plain");
  3544. return httplib::Server::HandlerResponse::Handled;
  3545. }
  3546. return httplib::Server::HandlerResponse::Unhandled;
  3547. });
  3548. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3549. res.set_content("Error", "text/html");
  3550. });
  3551. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3552. if (req.path == "/routing_handler") {
  3553. res.set_header("POST_ROUTING", "on");
  3554. }
  3555. });
  3556. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3557. res.set_content("Hello World!\n", "text/plain");
  3558. });
  3559. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3560. auto se = detail::scope_exit([&] {
  3561. svr.stop();
  3562. thread.join();
  3563. ASSERT_FALSE(svr.is_running());
  3564. });
  3565. svr.wait_until_ready();
  3566. {
  3567. #ifdef CPPHTTPLIB_SSL_ENABLED
  3568. SSLClient cli(HOST, PORT);
  3569. cli.enable_server_certificate_verification(false);
  3570. #else
  3571. Client cli(HOST, PORT);
  3572. #endif
  3573. auto res = cli.Get("/routing_handler");
  3574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3575. EXPECT_EQ(StatusCode::OK_200, res->status);
  3576. EXPECT_EQ("Routing Handler", res->body);
  3577. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3578. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3579. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3580. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3581. }
  3582. {
  3583. #ifdef CPPHTTPLIB_SSL_ENABLED
  3584. SSLClient cli(HOST, PORT);
  3585. cli.enable_server_certificate_verification(false);
  3586. #else
  3587. Client cli(HOST, PORT);
  3588. #endif
  3589. auto res = cli.Get("/hi");
  3590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3591. EXPECT_EQ(StatusCode::OK_200, res->status);
  3592. EXPECT_EQ("Hello World!\n", res->body);
  3593. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3594. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3595. }
  3596. {
  3597. #ifdef CPPHTTPLIB_SSL_ENABLED
  3598. SSLClient cli(HOST, PORT);
  3599. cli.enable_server_certificate_verification(false);
  3600. #else
  3601. Client cli(HOST, PORT);
  3602. #endif
  3603. auto res = cli.Get("/aaa");
  3604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3605. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3606. EXPECT_EQ("Error", res->body);
  3607. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3608. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3609. }
  3610. }
  3611. TEST(RequestHandlerTest, PreRequestHandler) {
  3612. auto route_path = "/user/:user";
  3613. Server svr;
  3614. svr.Get("/hi", [](const Request &, Response &res) {
  3615. res.set_content("hi", "text/plain");
  3616. });
  3617. svr.Get(route_path, [](const Request &req, Response &res) {
  3618. res.set_content(req.path_params.at("user"), "text/plain");
  3619. });
  3620. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3621. if (req.matched_route == route_path) {
  3622. auto user = req.path_params.at("user");
  3623. if (user != "john") {
  3624. res.status = StatusCode::Forbidden_403;
  3625. res.set_content("error", "text/html");
  3626. return Server::HandlerResponse::Handled;
  3627. }
  3628. }
  3629. return Server::HandlerResponse::Unhandled;
  3630. });
  3631. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3632. auto se = detail::scope_exit([&] {
  3633. svr.stop();
  3634. thread.join();
  3635. ASSERT_FALSE(svr.is_running());
  3636. });
  3637. svr.wait_until_ready();
  3638. Client cli(HOST, PORT);
  3639. {
  3640. auto res = cli.Get("/hi");
  3641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3642. EXPECT_EQ(StatusCode::OK_200, res->status);
  3643. EXPECT_EQ("hi", res->body);
  3644. }
  3645. {
  3646. auto res = cli.Get("/user/john");
  3647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3648. EXPECT_EQ(StatusCode::OK_200, res->status);
  3649. EXPECT_EQ("john", res->body);
  3650. }
  3651. {
  3652. auto res = cli.Get("/user/invalid-user");
  3653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3654. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3655. EXPECT_EQ("error", res->body);
  3656. }
  3657. }
  3658. // The pre-request handler must run before the request body is read, so a
  3659. // rejected request never forces the server to buffer a (potentially large)
  3660. // body. Here the posted body is larger than the payload limit: if the body
  3661. // were read first the server would answer 413, but because the pre-request
  3662. // handler runs first it answers 403 and the body is never read.
  3663. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3664. Server svr;
  3665. svr.set_payload_max_length(8);
  3666. auto handler_ran = false;
  3667. svr.Post("/reject", [&](const Request &req, Response &res) {
  3668. handler_ran = true;
  3669. res.set_content(req.body, "text/plain");
  3670. });
  3671. svr.Post("/accept", [](const Request &req, Response &res) {
  3672. res.set_content(req.body, "text/plain");
  3673. });
  3674. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3675. if (req.matched_route == "/reject") {
  3676. res.status = StatusCode::Forbidden_403;
  3677. res.set_content("denied", "text/plain");
  3678. return Server::HandlerResponse::Handled;
  3679. }
  3680. return Server::HandlerResponse::Unhandled;
  3681. });
  3682. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3683. auto se = detail::scope_exit([&] {
  3684. svr.stop();
  3685. thread.join();
  3686. ASSERT_FALSE(svr.is_running());
  3687. });
  3688. svr.wait_until_ready();
  3689. Client cli(HOST, PORT);
  3690. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3691. // rejects with 403 before the body is read, so 413 is never reached.
  3692. {
  3693. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3695. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3696. EXPECT_EQ("denied", res->body);
  3697. EXPECT_FALSE(handler_ran);
  3698. }
  3699. // An approved route still reads the body and enforces the payload limit.
  3700. {
  3701. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3703. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3704. }
  3705. }
  3706. TEST(UserDataTest, BasicOperations) {
  3707. httplib::UserData ud;
  3708. // Initially empty
  3709. EXPECT_FALSE(ud.has("key"));
  3710. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3711. // set and get
  3712. ud.set("key", 42);
  3713. EXPECT_TRUE(ud.has("key"));
  3714. auto *p = ud.get<int>("key");
  3715. ASSERT_NE(nullptr, p);
  3716. EXPECT_EQ(42, *p);
  3717. // Type mismatch → nullptr
  3718. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3719. // Overwrite with different type
  3720. ud.set("key", std::string("hello"));
  3721. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3722. auto *s = ud.get<std::string>("key");
  3723. ASSERT_NE(nullptr, s);
  3724. EXPECT_EQ("hello", *s);
  3725. // erase
  3726. ud.erase("key");
  3727. EXPECT_FALSE(ud.has("key"));
  3728. // clear
  3729. ud.set("a", 1);
  3730. ud.set("b", 2);
  3731. ud.clear();
  3732. EXPECT_FALSE(ud.has("a"));
  3733. EXPECT_FALSE(ud.has("b"));
  3734. }
  3735. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3736. struct AuthCtx {
  3737. std::string user_id;
  3738. };
  3739. Server svr;
  3740. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3741. res.user_data.set("auth", AuthCtx{"alice"});
  3742. return Server::HandlerResponse::Unhandled;
  3743. });
  3744. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3745. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3746. ASSERT_NE(nullptr, ctx);
  3747. res.set_content("Hello " + ctx->user_id, "text/plain");
  3748. });
  3749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3750. auto se = detail::scope_exit([&] {
  3751. svr.stop();
  3752. thread.join();
  3753. ASSERT_FALSE(svr.is_running());
  3754. });
  3755. svr.wait_until_ready();
  3756. Client cli(HOST, PORT);
  3757. auto res = cli.Get("/me");
  3758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3759. EXPECT_EQ(StatusCode::OK_200, res->status);
  3760. EXPECT_EQ("Hello alice", res->body);
  3761. }
  3762. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3763. struct RoleCtx {
  3764. std::string role;
  3765. };
  3766. Server svr;
  3767. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3768. res.user_data.set("role", RoleCtx{"admin"});
  3769. return Server::HandlerResponse::Unhandled;
  3770. });
  3771. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3772. auto *ctx = res.user_data.get<RoleCtx>("role");
  3773. ASSERT_NE(nullptr, ctx);
  3774. res.set_content(ctx->role, "text/plain");
  3775. });
  3776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3777. auto se = detail::scope_exit([&] {
  3778. svr.stop();
  3779. thread.join();
  3780. ASSERT_FALSE(svr.is_running());
  3781. });
  3782. svr.wait_until_ready();
  3783. Client cli(HOST, PORT);
  3784. auto res = cli.Get("/role");
  3785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3786. EXPECT_EQ(StatusCode::OK_200, res->status);
  3787. EXPECT_EQ("admin", res->body);
  3788. }
  3789. TEST(InvalidFormatTest, StatusCode) {
  3790. Server svr;
  3791. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3792. res.set_content("Hello World!\n", "text/plain");
  3793. res.status = 9999; // Status should be a three-digit code...
  3794. });
  3795. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3796. auto se = detail::scope_exit([&] {
  3797. svr.stop();
  3798. thread.join();
  3799. ASSERT_FALSE(svr.is_running());
  3800. });
  3801. svr.wait_until_ready();
  3802. {
  3803. Client cli(HOST, PORT);
  3804. auto res = cli.Get("/hi");
  3805. ASSERT_FALSE(res);
  3806. }
  3807. }
  3808. TEST(URLFragmentTest, WithFragment) {
  3809. Server svr;
  3810. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3811. EXPECT_TRUE(req.target == "/hi");
  3812. });
  3813. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3814. auto se = detail::scope_exit([&] {
  3815. svr.stop();
  3816. thread.join();
  3817. ASSERT_FALSE(svr.is_running());
  3818. });
  3819. svr.wait_until_ready();
  3820. {
  3821. Client cli(HOST, PORT);
  3822. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3823. EXPECT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::OK_200, res->status);
  3825. res = cli.Get("/hi%23key1=val1=key2=val2");
  3826. EXPECT_TRUE(res);
  3827. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3828. }
  3829. }
  3830. TEST(HeaderWriter, SetHeaderWriter) {
  3831. Server svr;
  3832. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3833. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3834. return detail::write_headers(strm, hdrs);
  3835. });
  3836. svr.Get("/hi", [](const Request &req, Response &res) {
  3837. auto it = req.headers.find("CustomClientHeader");
  3838. EXPECT_TRUE(it != req.headers.end());
  3839. EXPECT_EQ(it->second, "CustomClientValue");
  3840. res.set_content("Hello World!\n", "text/plain");
  3841. });
  3842. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3843. auto se = detail::scope_exit([&] {
  3844. svr.stop();
  3845. thread.join();
  3846. ASSERT_FALSE(svr.is_running());
  3847. });
  3848. svr.wait_until_ready();
  3849. {
  3850. Client cli(HOST, PORT);
  3851. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3852. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3853. return detail::write_headers(strm, hdrs);
  3854. });
  3855. auto res = cli.Get("/hi");
  3856. EXPECT_TRUE(res);
  3857. EXPECT_EQ(StatusCode::OK_200, res->status);
  3858. auto it = res->headers.find("CustomServerHeader");
  3859. EXPECT_TRUE(it != res->headers.end());
  3860. EXPECT_EQ(it->second, "CustomServerValue");
  3861. }
  3862. }
  3863. class ServerTest : public ::testing::Test {
  3864. protected:
  3865. ServerTest()
  3866. : cli_(HOST, PORT)
  3867. #ifdef CPPHTTPLIB_SSL_ENABLED
  3868. ,
  3869. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3870. #endif
  3871. {
  3872. #ifdef CPPHTTPLIB_SSL_ENABLED
  3873. cli_.enable_server_certificate_verification(false);
  3874. #endif
  3875. // Allow LARGE_DATA (100MB) responses
  3876. cli_.set_payload_max_length(200 * 1024 * 1024);
  3877. }
  3878. virtual void SetUp() {
  3879. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3880. svr_.set_payload_max_length(200 * 1024 * 1024);
  3881. svr_.set_mount_point("/", "./www");
  3882. svr_.set_mount_point("/mount", "./www2");
  3883. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3884. svr_.Get("/hi",
  3885. [&](const Request & /*req*/, Response &res) {
  3886. res.set_content("Hello World!", "text/plain");
  3887. })
  3888. .Get("/file_content",
  3889. [&](const Request & /*req*/, Response &res) {
  3890. res.set_file_content("./www/dir/test.html");
  3891. })
  3892. .Get("/file_content_with_content_type",
  3893. [&](const Request & /*req*/, Response &res) {
  3894. res.set_file_content("./www/file", "text/plain");
  3895. })
  3896. .Get("/invalid_file_content",
  3897. [&](const Request & /*req*/, Response &res) {
  3898. res.set_file_content("./www/dir/invalid_file_path");
  3899. })
  3900. .Get("/http_response_splitting",
  3901. [&](const Request & /*req*/, Response &res) {
  3902. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3903. EXPECT_EQ(0U, res.headers.size());
  3904. EXPECT_FALSE(res.has_header("a"));
  3905. res.set_header("a", "1\nSet-Cookie: a=1");
  3906. EXPECT_EQ(0U, res.headers.size());
  3907. EXPECT_FALSE(res.has_header("a"));
  3908. res.set_header("a", "1\rSet-Cookie: a=1");
  3909. EXPECT_EQ(0U, res.headers.size());
  3910. EXPECT_FALSE(res.has_header("a"));
  3911. res.set_header("a\r\nb", "0");
  3912. EXPECT_EQ(0U, res.headers.size());
  3913. EXPECT_FALSE(res.has_header("a"));
  3914. res.set_header("a\rb", "0");
  3915. EXPECT_EQ(0U, res.headers.size());
  3916. EXPECT_FALSE(res.has_header("a"));
  3917. res.set_header("a\nb", "0");
  3918. EXPECT_EQ(0U, res.headers.size());
  3919. EXPECT_FALSE(res.has_header("a"));
  3920. res.set_redirect("1\r\nSet-Cookie: a=1");
  3921. EXPECT_EQ(0U, res.headers.size());
  3922. EXPECT_FALSE(res.has_header("Location"));
  3923. })
  3924. .Get("/slow",
  3925. [&](const Request & /*req*/, Response &res) {
  3926. std::this_thread::sleep_for(std::chrono::seconds(4));
  3927. res.set_content("slow", "text/plain");
  3928. })
  3929. #if 0
  3930. .Post("/slowpost",
  3931. [&](const Request & /*req*/, Response &res) {
  3932. std::this_thread::sleep_for(std::chrono::seconds(2));
  3933. res.set_content("slow", "text/plain");
  3934. })
  3935. #endif
  3936. .Get("/remote_addr",
  3937. [&](const Request &req, Response &res) {
  3938. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3939. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3940. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3941. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3942. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3943. #endif
  3944. res.set_content(req.remote_addr, "text/plain");
  3945. })
  3946. .Get("/local_addr",
  3947. [&](const Request &req, Response &res) {
  3948. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3949. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3950. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3951. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3952. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3953. #endif
  3954. auto local_addr = req.local_addr;
  3955. auto local_port = std::to_string(req.local_port);
  3956. res.set_content(local_addr.append(":").append(local_port),
  3957. "text/plain");
  3958. })
  3959. .Get("/endwith%",
  3960. [&](const Request & /*req*/, Response &res) {
  3961. res.set_content("Hello World!", "text/plain");
  3962. })
  3963. .Get("/a\\+\\+b",
  3964. [&](const Request &req, Response &res) {
  3965. ASSERT_TRUE(req.has_param("a +b"));
  3966. auto val = req.get_param_value("a +b");
  3967. res.set_content(val, "text/plain");
  3968. })
  3969. .Get("/", [&](const Request & /*req*/,
  3970. Response &res) { res.set_redirect("/hi"); })
  3971. .Post("/1",
  3972. [](const Request & /*req*/, Response &res) {
  3973. res.set_redirect("/2", StatusCode::SeeOther_303);
  3974. })
  3975. .Get("/2",
  3976. [](const Request & /*req*/, Response &res) {
  3977. res.set_content("redirected.", "text/plain");
  3978. res.status = StatusCode::OK_200;
  3979. })
  3980. .Post("/person",
  3981. [&](const Request &req, Response &res) {
  3982. if (req.has_param("name") && req.has_param("note")) {
  3983. persons_[req.get_param_value("name")] =
  3984. req.get_param_value("note");
  3985. } else {
  3986. res.status = StatusCode::BadRequest_400;
  3987. }
  3988. })
  3989. .Put("/person",
  3990. [&](const Request &req, Response &res) {
  3991. if (req.has_param("name") && req.has_param("note")) {
  3992. persons_[req.get_param_value("name")] =
  3993. req.get_param_value("note");
  3994. } else {
  3995. res.status = StatusCode::BadRequest_400;
  3996. }
  3997. })
  3998. .Get("/person/(.*)",
  3999. [&](const Request &req, Response &res) {
  4000. string name = req.matches[1];
  4001. if (persons_.find(name) != persons_.end()) {
  4002. auto note = persons_[name];
  4003. res.set_content(note, "text/plain");
  4004. } else {
  4005. res.status = StatusCode::NotFound_404;
  4006. }
  4007. })
  4008. .Delete("/person",
  4009. [&](const Request &req, Response &res) {
  4010. if (req.has_param("name")) {
  4011. string name = req.get_param_value("name");
  4012. if (persons_.find(name) != persons_.end()) {
  4013. persons_.erase(name);
  4014. res.set_content("DELETED", "text/plain");
  4015. } else {
  4016. res.status = StatusCode::NotFound_404;
  4017. }
  4018. } else {
  4019. res.status = StatusCode::BadRequest_400;
  4020. }
  4021. })
  4022. .Post("/x-www-form-urlencoded-json",
  4023. [&](const Request &req, Response &res) {
  4024. auto json = req.get_param_value("json");
  4025. ASSERT_EQ(JSON_DATA, json);
  4026. res.set_content(json, "appliation/json");
  4027. res.status = StatusCode::OK_200;
  4028. })
  4029. .Get("/streamed-chunked",
  4030. [&](const Request & /*req*/, Response &res) {
  4031. res.set_chunked_content_provider(
  4032. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4033. sink.os << "123";
  4034. sink.os << "456";
  4035. sink.os << "789";
  4036. sink.done();
  4037. return true;
  4038. });
  4039. })
  4040. .Get("/streamed-chunked-with-prohibited-trailer",
  4041. [&](const Request & /*req*/, Response &res) {
  4042. auto i = new int(0);
  4043. // Declare both a prohibited trailer (Content-Length) and an
  4044. // allowed one
  4045. res.set_header("Trailer", "Content-Length, X-Allowed");
  4046. res.set_chunked_content_provider(
  4047. "text/plain",
  4048. [i](size_t /*offset*/, DataSink &sink) {
  4049. switch (*i) {
  4050. case 0: sink.os << "123"; break;
  4051. case 1: sink.os << "456"; break;
  4052. case 2: sink.os << "789"; break;
  4053. case 3: {
  4054. sink.done_with_trailer(
  4055. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4056. } break;
  4057. }
  4058. (*i)++;
  4059. return true;
  4060. },
  4061. [i](bool success) {
  4062. EXPECT_TRUE(success);
  4063. delete i;
  4064. });
  4065. })
  4066. .Get("/streamed-chunked2",
  4067. [&](const Request & /*req*/, Response &res) {
  4068. auto i = new int(0);
  4069. res.set_chunked_content_provider(
  4070. "text/plain",
  4071. [i](size_t /*offset*/, DataSink &sink) {
  4072. switch (*i) {
  4073. case 0: sink.os << "123"; break;
  4074. case 1: sink.os << "456"; break;
  4075. case 2: sink.os << "789"; break;
  4076. case 3: sink.done(); break;
  4077. }
  4078. (*i)++;
  4079. return true;
  4080. },
  4081. [i](bool success) {
  4082. EXPECT_TRUE(success);
  4083. delete i;
  4084. });
  4085. })
  4086. .Get("/streamed-chunked-with-trailer",
  4087. [&](const Request & /*req*/, Response &res) {
  4088. auto i = new int(0);
  4089. res.set_header("Trailer", "Dummy1, Dummy2");
  4090. res.set_chunked_content_provider(
  4091. "text/plain",
  4092. [i](size_t /*offset*/, DataSink &sink) {
  4093. switch (*i) {
  4094. case 0: sink.os << "123"; break;
  4095. case 1: sink.os << "456"; break;
  4096. case 2: sink.os << "789"; break;
  4097. case 3: {
  4098. sink.done_with_trailer(
  4099. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4100. } break;
  4101. }
  4102. (*i)++;
  4103. return true;
  4104. },
  4105. [i](bool success) {
  4106. EXPECT_TRUE(success);
  4107. delete i;
  4108. });
  4109. })
  4110. .Get("/streamed",
  4111. [&](const Request & /*req*/, Response &res) {
  4112. res.set_content_provider(
  4113. 6, "text/plain",
  4114. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4115. sink.os << (offset < 3 ? "a" : "b");
  4116. return true;
  4117. });
  4118. })
  4119. .Get("/streamed-without-length",
  4120. [&](const Request & /*req*/, Response &res) {
  4121. auto data = new std::string("abcdefg");
  4122. res.set_content_provider(
  4123. "text/plain",
  4124. [data](size_t offset, DataSink &sink) {
  4125. if (offset < data->size()) {
  4126. sink.os << data->substr(offset);
  4127. }
  4128. sink.done();
  4129. return true;
  4130. },
  4131. [data](bool success) {
  4132. EXPECT_TRUE(success);
  4133. delete data;
  4134. });
  4135. })
  4136. .Get("/streamed-with-range",
  4137. [&](const Request &req, Response &res) {
  4138. auto data = new std::string("abcdefg");
  4139. // An explicit status keeps the server from picking the 206 it
  4140. // would otherwise choose for a ranged request, so the response
  4141. // is not a partial representation.
  4142. auto status = req.get_param_value("status");
  4143. if (status == "200") {
  4144. res.status = StatusCode::OK_200;
  4145. } else if (status == "403") {
  4146. res.status = StatusCode::Forbidden_403;
  4147. }
  4148. res.set_content_provider(
  4149. data->size(), "text/plain",
  4150. [data](size_t offset, size_t length, DataSink &sink) {
  4151. size_t DATA_CHUNK_SIZE = 4;
  4152. const auto &d = *data;
  4153. auto out_len =
  4154. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4155. auto ret =
  4156. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4157. EXPECT_TRUE(ret);
  4158. return true;
  4159. },
  4160. [data, &req](bool success) {
  4161. EXPECT_EQ(success, !req.has_param("error"));
  4162. delete data;
  4163. });
  4164. })
  4165. .Get("/streamed-cancel",
  4166. [&](const Request & /*req*/, Response &res) {
  4167. res.set_content_provider(
  4168. size_t(-1), "text/plain",
  4169. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4170. sink.os << "data_chunk";
  4171. return true;
  4172. });
  4173. })
  4174. .Get("/regex-with-delimiter",
  4175. [&](const Request &req, Response & /*res*/) {
  4176. ASSERT_TRUE(req.has_param("key"));
  4177. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4178. })
  4179. .Get("/with-range",
  4180. [&](const Request & /*req*/, Response &res) {
  4181. res.set_content("abcdefg", "text/plain");
  4182. })
  4183. .Get("/test-start-time",
  4184. [&](const Request &req, Response & /*res*/) {
  4185. EXPECT_NE(req.start_time_,
  4186. std::chrono::steady_clock::time_point::min());
  4187. })
  4188. .Get("/with-range-customized-response",
  4189. [&](const Request & /*req*/, Response &res) {
  4190. res.status = StatusCode::BadRequest_400;
  4191. res.set_content(JSON_DATA, "application/json");
  4192. })
  4193. .Post("/chunked",
  4194. [&](const Request &req, Response & /*res*/) {
  4195. EXPECT_EQ(req.body, "dechunked post body");
  4196. })
  4197. .Post("/large-chunked",
  4198. [&](const Request &req, Response & /*res*/) {
  4199. std::string expected(6 * 30 * 1024u, 'a');
  4200. EXPECT_EQ(req.body, expected);
  4201. })
  4202. .Post("/multipart",
  4203. [&](const Request &req, Response & /*res*/) {
  4204. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4205. req.form.get_field_count("text2") +
  4206. req.form.get_field_count("file3") +
  4207. req.form.get_field_count("file4"));
  4208. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4209. req.form.get_file_count("file2"));
  4210. ASSERT_TRUE(!req.form.has_file("???"));
  4211. ASSERT_TRUE(!req.form.has_field("???"));
  4212. ASSERT_TRUE(req.body.empty());
  4213. {
  4214. const auto &text = req.form.get_field("text1");
  4215. EXPECT_EQ("text default", text);
  4216. }
  4217. {
  4218. const auto &text = req.form.get_field("text2");
  4219. EXPECT_EQ("aωb", text);
  4220. }
  4221. {
  4222. const auto &file = req.form.get_file("file1");
  4223. EXPECT_EQ("hello.txt", file.filename);
  4224. EXPECT_EQ("text/plain", file.content_type);
  4225. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4226. }
  4227. {
  4228. const auto &file = req.form.get_file("file2");
  4229. EXPECT_EQ("world.json", file.filename);
  4230. EXPECT_EQ("application/json", file.content_type);
  4231. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4232. }
  4233. {
  4234. const auto &text = req.form.get_field("file3");
  4235. EXPECT_EQ(0u, text.size());
  4236. }
  4237. {
  4238. const auto &text = req.form.get_field("file4");
  4239. EXPECT_EQ(0u, text.size());
  4240. }
  4241. })
  4242. .Post("/multipart/multi_file_values",
  4243. [&](const Request &req, Response & /*res*/) {
  4244. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4245. req.form.get_field_count("multi_text1"));
  4246. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4247. ASSERT_TRUE(!req.form.has_file("???"));
  4248. ASSERT_TRUE(!req.form.has_field("???"));
  4249. ASSERT_TRUE(req.body.empty());
  4250. {
  4251. const auto &text = req.form.get_field("text");
  4252. EXPECT_EQ("default text", text);
  4253. }
  4254. {
  4255. const auto &text1_values = req.form.get_fields("multi_text1");
  4256. EXPECT_EQ(2u, text1_values.size());
  4257. EXPECT_EQ("aaaaa", text1_values[0]);
  4258. EXPECT_EQ("bbbbb", text1_values[1]);
  4259. }
  4260. {
  4261. const auto &file1_values = req.form.get_files("multi_file1");
  4262. EXPECT_EQ(2u, file1_values.size());
  4263. auto file1 = file1_values[0];
  4264. EXPECT_EQ(file1.filename, "hello.txt");
  4265. EXPECT_EQ(file1.content_type, "text/plain");
  4266. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4267. auto file2 = file1_values[1];
  4268. EXPECT_EQ(file2.filename, "world.json");
  4269. EXPECT_EQ(file2.content_type, "application/json");
  4270. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4271. }
  4272. })
  4273. .Post("/empty",
  4274. [&](const Request &req, Response &res) {
  4275. EXPECT_EQ(req.body, "");
  4276. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4277. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4278. res.set_content("empty", "text/plain");
  4279. })
  4280. .Post("/empty-no-content-type",
  4281. [&](const Request &req, Response &res) {
  4282. EXPECT_EQ(req.body, "");
  4283. EXPECT_FALSE(req.has_header("Content-Type"));
  4284. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4285. res.set_content("empty-no-content-type", "text/plain");
  4286. })
  4287. .Post("/path-only",
  4288. [&](const Request &req, Response &res) {
  4289. EXPECT_EQ(req.body, "");
  4290. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4291. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4292. res.set_content("path-only", "text/plain");
  4293. })
  4294. .Post("/path-headers-only",
  4295. [&](const Request &req, Response &res) {
  4296. EXPECT_EQ(req.body, "");
  4297. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4298. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4299. EXPECT_EQ("world", req.get_header_value("hello"));
  4300. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4301. res.set_content("path-headers-only", "text/plain");
  4302. })
  4303. .Post("/post-large",
  4304. [&](const Request &req, Response &res) {
  4305. EXPECT_EQ(req.body, LARGE_DATA);
  4306. res.set_content(req.body, "text/plain");
  4307. })
  4308. .Post("/post-loopback",
  4309. [&](const Request &, Response &res,
  4310. ContentReader const &content_reader) {
  4311. std::string body;
  4312. content_reader([&](const char *data, size_t data_length) {
  4313. body.append(data, data_length);
  4314. return true;
  4315. });
  4316. res.set_content(body, "text/plain");
  4317. })
  4318. .Put("/put-loopback",
  4319. [&](const Request &, Response &res,
  4320. ContentReader const &content_reader) {
  4321. std::string body;
  4322. content_reader([&](const char *data, size_t data_length) {
  4323. body.append(data, data_length);
  4324. return true;
  4325. });
  4326. res.set_content(body, "text/plain");
  4327. })
  4328. .Patch("/patch-loopback",
  4329. [&](const Request &, Response &res,
  4330. ContentReader const &content_reader) {
  4331. std::string body;
  4332. content_reader([&](const char *data, size_t data_length) {
  4333. body.append(data, data_length);
  4334. return true;
  4335. });
  4336. res.set_content(body, "text/plain");
  4337. })
  4338. .Put("/empty-no-content-type",
  4339. [&](const Request &req, Response &res) {
  4340. EXPECT_EQ(req.body, "");
  4341. EXPECT_FALSE(req.has_header("Content-Type"));
  4342. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4343. res.set_content("empty-no-content-type", "text/plain");
  4344. })
  4345. .Put("/put",
  4346. [&](const Request &req, Response &res) {
  4347. EXPECT_EQ(req.body, "PUT");
  4348. res.set_content(req.body, "text/plain");
  4349. })
  4350. .Put("/put-large",
  4351. [&](const Request &req, Response &res) {
  4352. EXPECT_EQ(req.body, LARGE_DATA);
  4353. res.set_content(req.body, "text/plain");
  4354. })
  4355. .Patch("/patch",
  4356. [&](const Request &req, Response &res) {
  4357. EXPECT_EQ(req.body, "PATCH");
  4358. res.set_content(req.body, "text/plain");
  4359. })
  4360. .Delete("/delete",
  4361. [&](const Request & /*req*/, Response &res) {
  4362. res.set_content("DELETE", "text/plain");
  4363. })
  4364. .Delete("/delete-body",
  4365. [&](const Request &req, Response &res) {
  4366. EXPECT_EQ(req.body, "content");
  4367. res.set_content(req.body, "text/plain");
  4368. })
  4369. .Options(R"(\*)",
  4370. [&](const Request & /*req*/, Response &res) {
  4371. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4372. })
  4373. .Get("/request-target",
  4374. [&](const Request &req, Response & /*res*/) {
  4375. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4376. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4377. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4378. })
  4379. .Get("/long-query-value",
  4380. [&](const Request &req, Response & /*res*/) {
  4381. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4382. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4383. })
  4384. .Get("/too-long-query-value",
  4385. [&](const Request &req, Response & /*res*/) {
  4386. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4387. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4388. })
  4389. .Get("/array-param",
  4390. [&](const Request &req, Response & /*res*/) {
  4391. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4392. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4393. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4394. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4395. })
  4396. .Get("/array-param-values",
  4397. [&](const Request &req, Response & /*res*/) {
  4398. auto values = req.get_param_values("array");
  4399. EXPECT_EQ(3u, values.size());
  4400. EXPECT_EQ("value1", values[0]);
  4401. EXPECT_EQ("value2", values[1]);
  4402. EXPECT_EQ("value3", values[2]);
  4403. auto empty = req.get_param_values("nonexistent");
  4404. EXPECT_TRUE(empty.empty());
  4405. })
  4406. .Post("/validate-no-multiple-headers",
  4407. [&](const Request &req, Response & /*res*/) {
  4408. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4409. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4410. })
  4411. .Post("/content_receiver",
  4412. [&](const Request &req, Response &res,
  4413. const ContentReader &content_reader) {
  4414. if (req.is_multipart_form_data()) {
  4415. std::vector<FormData> items;
  4416. content_reader(
  4417. [&](const FormData &file) {
  4418. items.push_back(file);
  4419. return true;
  4420. },
  4421. [&](const char *data, size_t data_length) {
  4422. items.back().content.append(data, data_length);
  4423. return true;
  4424. });
  4425. EXPECT_EQ(5u, items.size());
  4426. {
  4427. const auto &file = get_file_value(items, "text1");
  4428. EXPECT_TRUE(file.filename.empty());
  4429. EXPECT_EQ("text default", file.content);
  4430. }
  4431. {
  4432. const auto &file = get_file_value(items, "text2");
  4433. EXPECT_TRUE(file.filename.empty());
  4434. EXPECT_EQ("aωb", file.content);
  4435. }
  4436. {
  4437. const auto &file = get_file_value(items, "file1");
  4438. EXPECT_EQ("hello.txt", file.filename);
  4439. EXPECT_EQ("text/plain", file.content_type);
  4440. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4441. }
  4442. {
  4443. const auto &file = get_file_value(items, "file2");
  4444. EXPECT_EQ("world.json", file.filename);
  4445. EXPECT_EQ("application/json", file.content_type);
  4446. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4447. }
  4448. {
  4449. const auto &file = get_file_value(items, "file3");
  4450. EXPECT_TRUE(file.filename.empty());
  4451. EXPECT_EQ("application/octet-stream", file.content_type);
  4452. EXPECT_EQ(0u, file.content.size());
  4453. }
  4454. } else {
  4455. std::string body;
  4456. content_reader([&](const char *data, size_t data_length) {
  4457. EXPECT_EQ(7U, data_length);
  4458. body.append(data, data_length);
  4459. return true;
  4460. });
  4461. EXPECT_EQ(body, "content");
  4462. res.set_content(body, "text/plain");
  4463. }
  4464. })
  4465. .Put("/content_receiver",
  4466. [&](const Request & /*req*/, Response &res,
  4467. const ContentReader &content_reader) {
  4468. std::string body;
  4469. content_reader([&](const char *data, size_t data_length) {
  4470. body.append(data, data_length);
  4471. return true;
  4472. });
  4473. EXPECT_EQ(body, "content");
  4474. res.set_content(body, "text/plain");
  4475. })
  4476. .Patch("/content_receiver",
  4477. [&](const Request & /*req*/, Response &res,
  4478. const ContentReader &content_reader) {
  4479. std::string body;
  4480. content_reader([&](const char *data, size_t data_length) {
  4481. body.append(data, data_length);
  4482. return true;
  4483. });
  4484. EXPECT_EQ(body, "content");
  4485. res.set_content(body, "text/plain");
  4486. })
  4487. .Post("/query-string-and-body",
  4488. [&](const Request &req, Response & /*res*/) {
  4489. ASSERT_TRUE(req.has_param("key"));
  4490. EXPECT_EQ(req.get_param_value("key"), "value");
  4491. EXPECT_EQ(req.body, "content");
  4492. })
  4493. .Get("/last-request",
  4494. [&](const Request &req, Response & /*res*/) {
  4495. EXPECT_EQ("close", req.get_header_value("Connection"));
  4496. })
  4497. .Get(R"(/redirect/(\d+))",
  4498. [&](const Request &req, Response &res) {
  4499. auto num = std::stoi(req.matches[1]) + 1;
  4500. std::string url = "/redirect/" + std::to_string(num);
  4501. res.set_redirect(url);
  4502. })
  4503. .Post("/binary",
  4504. [&](const Request &req, Response &res) {
  4505. EXPECT_EQ(4U, req.body.size());
  4506. EXPECT_EQ("application/octet-stream",
  4507. req.get_header_value("Content-Type"));
  4508. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4509. res.set_content(req.body, "application/octet-stream");
  4510. })
  4511. .Put("/binary",
  4512. [&](const Request &req, Response &res) {
  4513. EXPECT_EQ(4U, req.body.size());
  4514. EXPECT_EQ("application/octet-stream",
  4515. req.get_header_value("Content-Type"));
  4516. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4517. res.set_content(req.body, "application/octet-stream");
  4518. })
  4519. .Patch("/binary",
  4520. [&](const Request &req, Response &res) {
  4521. EXPECT_EQ(4U, req.body.size());
  4522. EXPECT_EQ("application/octet-stream",
  4523. req.get_header_value("Content-Type"));
  4524. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4525. res.set_content(req.body, "application/octet-stream");
  4526. })
  4527. .Delete("/binary",
  4528. [&](const Request &req, Response &res) {
  4529. EXPECT_EQ(4U, req.body.size());
  4530. EXPECT_EQ("application/octet-stream",
  4531. req.get_header_value("Content-Type"));
  4532. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4533. res.set_content(req.body, "application/octet-stream");
  4534. })
  4535. .Get("/issue1772",
  4536. [&](const Request & /*req*/, Response &res) {
  4537. res.status = 401;
  4538. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4539. })
  4540. .Delete("/issue609",
  4541. [](const httplib::Request &, httplib::Response &res,
  4542. const httplib::ContentReader &) {
  4543. res.set_content("ok", "text/plain");
  4544. })
  4545. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4546. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4547. .Get("/compress",
  4548. [&](const Request & /*req*/, Response &res) {
  4549. res.set_content(
  4550. "12345678901234567890123456789012345678901234567890123456789"
  4551. "01234567890123456789012345678901234567890",
  4552. "text/plain");
  4553. })
  4554. .Get("/compress-with-charset",
  4555. [&](const Request & /*req*/, Response &res) {
  4556. res.set_content(
  4557. "12345678901234567890123456789012345678901234567890123456789"
  4558. "01234567890123456789012345678901234567890",
  4559. "application/json; charset=utf-8");
  4560. })
  4561. .Get("/nocompress",
  4562. [&](const Request & /*req*/, Response &res) {
  4563. res.set_content(
  4564. "12345678901234567890123456789012345678901234567890123456789"
  4565. "01234567890123456789012345678901234567890",
  4566. "application/octet-stream");
  4567. })
  4568. .Post("/compress-multipart",
  4569. [&](const Request &req, Response & /*res*/) {
  4570. EXPECT_EQ(2u, req.form.fields.size());
  4571. ASSERT_TRUE(!req.form.has_field("???"));
  4572. {
  4573. const auto &text = req.form.get_field("key1");
  4574. EXPECT_EQ("test", text);
  4575. }
  4576. {
  4577. const auto &text = req.form.get_field("key2");
  4578. EXPECT_EQ("--abcdefg123", text);
  4579. }
  4580. })
  4581. #endif
  4582. ;
  4583. persons_["john"] = "programmer";
  4584. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4585. svr_.wait_until_ready();
  4586. }
  4587. virtual void TearDown() {
  4588. svr_.stop();
  4589. if (!request_threads_.empty()) {
  4590. std::this_thread::sleep_for(std::chrono::seconds(1));
  4591. for (auto &t : request_threads_) {
  4592. t.join();
  4593. }
  4594. }
  4595. t_.join();
  4596. }
  4597. map<string, string> persons_;
  4598. #ifdef CPPHTTPLIB_SSL_ENABLED
  4599. SSLClient cli_;
  4600. SSLServer svr_;
  4601. #else
  4602. Client cli_;
  4603. Server svr_;
  4604. #endif
  4605. thread t_;
  4606. std::vector<thread> request_threads_;
  4607. };
  4608. TEST_F(ServerTest, GetMethod200) {
  4609. auto res = cli_.Get("/hi");
  4610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4611. EXPECT_EQ("HTTP/1.1", res->version);
  4612. EXPECT_EQ(StatusCode::OK_200, res->status);
  4613. EXPECT_EQ("OK", res->reason);
  4614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4615. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4616. EXPECT_EQ("Hello World!", res->body);
  4617. }
  4618. TEST_F(ServerTest, GetEmptyFile) {
  4619. auto res = cli_.Get("/empty_file");
  4620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4621. EXPECT_EQ(StatusCode::OK_200, res->status);
  4622. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4623. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4624. EXPECT_EQ("", res->body);
  4625. }
  4626. TEST_F(ServerTest, GetFileContent) {
  4627. auto res = cli_.Get("/file_content");
  4628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4629. EXPECT_EQ(StatusCode::OK_200, res->status);
  4630. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4631. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4632. EXPECT_EQ("test.html", res->body);
  4633. }
  4634. TEST_F(ServerTest, GetFileContentWithRange) {
  4635. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4638. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4639. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4640. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4641. EXPECT_EQ("est", res->body);
  4642. }
  4643. TEST_F(ServerTest, GetFileContentWithContentType) {
  4644. auto res = cli_.Get("/file_content_with_content_type");
  4645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4646. EXPECT_EQ(StatusCode::OK_200, res->status);
  4647. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4648. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4649. EXPECT_EQ("file\n", res->body);
  4650. }
  4651. TEST_F(ServerTest, GetInvalidFileContent) {
  4652. auto res = cli_.Get("/invalid_file_content");
  4653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4654. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4655. }
  4656. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4657. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4659. EXPECT_EQ("HTTP/1.1", res->version);
  4660. EXPECT_EQ(StatusCode::OK_200, res->status);
  4661. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4662. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4663. EXPECT_EQ("Hello World!", res->body);
  4664. }
  4665. TEST_F(ServerTest, GetMethod302) {
  4666. auto res = cli_.Get("/");
  4667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4668. EXPECT_EQ(StatusCode::Found_302, res->status);
  4669. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4670. }
  4671. TEST_F(ServerTest, GetMethod302Redirect) {
  4672. cli_.set_follow_location(true);
  4673. auto res = cli_.Get("/");
  4674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4675. EXPECT_EQ(StatusCode::OK_200, res->status);
  4676. EXPECT_EQ("Hello World!", res->body);
  4677. EXPECT_EQ("/hi", res->location);
  4678. }
  4679. TEST_F(ServerTest, GetMethod404) {
  4680. auto res = cli_.Get("/invalid");
  4681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4682. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4683. }
  4684. TEST_F(ServerTest, HeadMethod200) {
  4685. auto res = cli_.Head("/hi");
  4686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4687. EXPECT_EQ(StatusCode::OK_200, res->status);
  4688. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4689. EXPECT_TRUE(res->body.empty());
  4690. }
  4691. TEST_F(ServerTest, HeadMethod200Static) {
  4692. auto res = cli_.Head("/mount/dir/index.html");
  4693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4694. EXPECT_EQ(StatusCode::OK_200, res->status);
  4695. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4696. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4697. EXPECT_TRUE(res->body.empty());
  4698. }
  4699. TEST_F(ServerTest, HeadMethod404) {
  4700. auto res = cli_.Head("/invalid");
  4701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4702. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4703. EXPECT_TRUE(res->body.empty());
  4704. }
  4705. TEST_F(ServerTest, GetMethodPersonJohn) {
  4706. auto res = cli_.Get("/person/john");
  4707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4708. EXPECT_EQ(StatusCode::OK_200, res->status);
  4709. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4710. EXPECT_EQ("programmer", res->body);
  4711. }
  4712. TEST_F(ServerTest, PostMethod1) {
  4713. auto res = cli_.Get("/person/john1");
  4714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4715. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4716. res = cli_.Post("/person", "name=john1&note=coder",
  4717. "application/x-www-form-urlencoded");
  4718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4719. ASSERT_EQ(StatusCode::OK_200, res->status);
  4720. res = cli_.Get("/person/john1");
  4721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4722. ASSERT_EQ(StatusCode::OK_200, res->status);
  4723. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4724. ASSERT_EQ("coder", res->body);
  4725. }
  4726. TEST_F(ServerTest, PostMethod2) {
  4727. auto res = cli_.Get("/person/john2");
  4728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4729. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4730. Params params;
  4731. params.emplace("name", "john2");
  4732. params.emplace("note", "coder");
  4733. res = cli_.Post("/person", params);
  4734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4735. ASSERT_EQ(StatusCode::OK_200, res->status);
  4736. res = cli_.Get("/person/john2");
  4737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4738. ASSERT_EQ(StatusCode::OK_200, res->status);
  4739. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4740. ASSERT_EQ("coder", res->body);
  4741. }
  4742. TEST_F(ServerTest, PutMethod3) {
  4743. auto res = cli_.Get("/person/john3");
  4744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4745. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4746. Params params;
  4747. params.emplace("name", "john3");
  4748. params.emplace("note", "coder");
  4749. res = cli_.Put("/person", params);
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. ASSERT_EQ(StatusCode::OK_200, res->status);
  4752. res = cli_.Get("/person/john3");
  4753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4754. ASSERT_EQ(StatusCode::OK_200, res->status);
  4755. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4756. ASSERT_EQ("coder", res->body);
  4757. }
  4758. TEST_F(ServerTest, DeleteMethod1) {
  4759. auto res = cli_.Get("/person/john4");
  4760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4761. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4762. Params params;
  4763. params.emplace("name", "john4");
  4764. params.emplace("note", "coder");
  4765. res = cli_.Post("/person", params);
  4766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4767. ASSERT_EQ(StatusCode::OK_200, res->status);
  4768. res = cli_.Get("/person/john4");
  4769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4770. ASSERT_EQ(StatusCode::OK_200, res->status);
  4771. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4772. ASSERT_EQ("coder", res->body);
  4773. Params delete_params;
  4774. delete_params.emplace("name", "john4");
  4775. res = cli_.Delete("/person", delete_params);
  4776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4777. ASSERT_EQ(StatusCode::OK_200, res->status);
  4778. ASSERT_EQ("DELETED", res->body);
  4779. res = cli_.Get("/person/john4");
  4780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4781. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4782. }
  4783. TEST_F(ServerTest, DeleteMethod2) {
  4784. auto res = cli_.Get("/person/john5");
  4785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4786. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4787. Params params;
  4788. params.emplace("name", "john5");
  4789. params.emplace("note", "developer");
  4790. res = cli_.Post("/person", params);
  4791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4792. ASSERT_EQ(StatusCode::OK_200, res->status);
  4793. res = cli_.Get("/person/john5");
  4794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4795. ASSERT_EQ(StatusCode::OK_200, res->status);
  4796. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4797. ASSERT_EQ("developer", res->body);
  4798. Params delete_params;
  4799. delete_params.emplace("name", "john5");
  4800. Headers headers;
  4801. headers.emplace("Custom-Header", "test-value");
  4802. res = cli_.Delete("/person", headers, delete_params);
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. ASSERT_EQ(StatusCode::OK_200, res->status);
  4805. ASSERT_EQ("DELETED", res->body);
  4806. res = cli_.Get("/person/john5");
  4807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4808. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4809. }
  4810. TEST_F(ServerTest, DeleteMethod3) {
  4811. auto res = cli_.Get("/person/john6");
  4812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4813. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4814. Params params;
  4815. params.emplace("name", "john6");
  4816. params.emplace("note", "tester");
  4817. res = cli_.Post("/person", params);
  4818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4819. ASSERT_EQ(StatusCode::OK_200, res->status);
  4820. res = cli_.Get("/person/john6");
  4821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4822. ASSERT_EQ(StatusCode::OK_200, res->status);
  4823. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4824. ASSERT_EQ("tester", res->body);
  4825. Params delete_params;
  4826. delete_params.emplace("name", "john6");
  4827. Headers headers;
  4828. headers.emplace("Custom-Header", "test-value");
  4829. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4831. ASSERT_EQ(StatusCode::OK_200, res->status);
  4832. ASSERT_EQ("DELETED", res->body);
  4833. res = cli_.Get("/person/john6");
  4834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4835. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4836. }
  4837. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4838. Params params;
  4839. params.emplace("json", JSON_DATA);
  4840. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4842. ASSERT_EQ(StatusCode::OK_200, res->status);
  4843. ASSERT_EQ(JSON_DATA, res->body);
  4844. }
  4845. TEST_F(ServerTest, PostEmptyContent) {
  4846. auto res = cli_.Post("/empty", "", "text/plain");
  4847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4848. ASSERT_EQ(StatusCode::OK_200, res->status);
  4849. ASSERT_EQ("empty", res->body);
  4850. }
  4851. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4852. auto res = cli_.Post("/empty-no-content-type");
  4853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4854. ASSERT_EQ(StatusCode::OK_200, res->status);
  4855. ASSERT_EQ("empty-no-content-type", res->body);
  4856. }
  4857. TEST_F(ServerTest, PostPathOnly) {
  4858. auto res = cli_.Post("/path-only");
  4859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4860. ASSERT_EQ(StatusCode::OK_200, res->status);
  4861. ASSERT_EQ("path-only", res->body);
  4862. }
  4863. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4864. auto res = cli_.Post("/path-headers-only",
  4865. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4867. ASSERT_EQ(StatusCode::OK_200, res->status);
  4868. ASSERT_EQ("path-headers-only", res->body);
  4869. }
  4870. TEST_F(ServerTest, PostLarge) {
  4871. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4873. ASSERT_EQ(StatusCode::OK_200, res->status);
  4874. EXPECT_EQ(LARGE_DATA, res->body);
  4875. }
  4876. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4877. auto res = cli_.Put("/empty-no-content-type");
  4878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4879. ASSERT_EQ(StatusCode::OK_200, res->status);
  4880. ASSERT_EQ("empty-no-content-type", res->body);
  4881. }
  4882. TEST_F(ServerTest, GetMethodDir) {
  4883. auto res = cli_.Get("/dir/");
  4884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4885. EXPECT_EQ(StatusCode::OK_200, res->status);
  4886. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4887. auto body = R"(<html>
  4888. <head>
  4889. </head>
  4890. <body>
  4891. <a href="/dir/test.html">Test</a>
  4892. <a href="/hi">hi</a>
  4893. </body>
  4894. </html>
  4895. )";
  4896. EXPECT_EQ(body, res->body);
  4897. }
  4898. TEST_F(ServerTest, GetMethodDirTest) {
  4899. auto res = cli_.Get("/dir/test.html");
  4900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4901. EXPECT_EQ(StatusCode::OK_200, res->status);
  4902. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4903. EXPECT_EQ("test.html", res->body);
  4904. }
  4905. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4906. auto res = cli_.Get("/dir/../dir/test.html");
  4907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4908. EXPECT_EQ(StatusCode::OK_200, res->status);
  4909. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4910. EXPECT_EQ("test.html", res->body);
  4911. }
  4912. TEST_F(ServerTest, GetMethodInvalidPath) {
  4913. auto res = cli_.Get("/dir/../test.html");
  4914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4915. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4916. }
  4917. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4918. auto res = cli_.Get("/../www/dir/test.html");
  4919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4921. }
  4922. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4923. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4925. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4926. }
  4927. TEST_F(ServerTest, GetMethodDirMountTest) {
  4928. auto res = cli_.Get("/mount/dir/test.html");
  4929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4930. EXPECT_EQ(StatusCode::OK_200, res->status);
  4931. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4932. EXPECT_EQ("test.html", res->body);
  4933. }
  4934. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4935. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4937. EXPECT_EQ(StatusCode::OK_200, res->status);
  4938. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4939. EXPECT_EQ("test.html", res->body);
  4940. }
  4941. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4942. auto res = cli_.Get("/mount/dir/../test.html");
  4943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4944. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4945. }
  4946. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4947. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4949. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4950. }
  4951. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4952. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4954. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4955. }
  4956. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4957. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4959. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4960. }
  4961. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4962. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4964. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4965. }
  4966. TEST_F(ServerTest, PostMethod303) {
  4967. auto res = cli_.Post("/1", "body", "text/plain");
  4968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4969. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4970. EXPECT_EQ("/2", res->get_header_value("Location"));
  4971. }
  4972. TEST_F(ServerTest, PostMethod303Redirect) {
  4973. cli_.set_follow_location(true);
  4974. auto res = cli_.Post("/1", "body", "text/plain");
  4975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4976. EXPECT_EQ(StatusCode::OK_200, res->status);
  4977. EXPECT_EQ("redirected.", res->body);
  4978. EXPECT_EQ("/2", res->location);
  4979. }
  4980. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4981. auto res = cli_.Get("/dir/test.abcde");
  4982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4983. EXPECT_EQ(StatusCode::OK_200, res->status);
  4984. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4985. EXPECT_EQ("abcde", res->body);
  4986. }
  4987. TEST_F(ServerTest, StaticFileRange) {
  4988. auto res =
  4989. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4991. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4992. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4993. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4994. EXPECT_EQ(true, res->has_header("Content-Range"));
  4995. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4996. EXPECT_EQ(std::string("cd"), res->body);
  4997. }
  4998. TEST_F(ServerTest, StaticFileRanges) {
  4999. auto res = cli_.Get("/dir/test.abcde",
  5000. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5003. EXPECT_TRUE(
  5004. res->get_header_value("Content-Type")
  5005. .find(
  5006. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5007. 0);
  5008. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5009. }
  5010. TEST_F(ServerTest, StaticFileRangeHead) {
  5011. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5013. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5014. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5015. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5016. EXPECT_EQ(true, res->has_header("Content-Range"));
  5017. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5018. }
  5019. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5020. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5022. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5023. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5024. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5025. EXPECT_EQ(true, res->has_header("Content-Range"));
  5026. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5027. res->get_header_value("Content-Range"));
  5028. EXPECT_EQ("LAST\n", res->body);
  5029. }
  5030. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5031. auto res =
  5032. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5034. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5035. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5036. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5037. EXPECT_EQ(true, res->has_header("Content-Range"));
  5038. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5039. }
  5040. TEST_F(ServerTest, StaticFileBigFile) {
  5041. auto res = cli_.Get("/dir/1MB.txt");
  5042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5043. EXPECT_EQ(StatusCode::OK_200, res->status);
  5044. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5045. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5046. }
  5047. TEST_F(ServerTest, InvalidBaseDirMount) {
  5048. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5049. }
  5050. TEST_F(ServerTest, Binary) {
  5051. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5052. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5053. "application/octet-stream");
  5054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5055. ASSERT_EQ(StatusCode::OK_200, res->status);
  5056. ASSERT_EQ(4U, res->body.size());
  5057. res = cli_.Put("/binary", binary.data(), binary.size(),
  5058. "application/octet-stream");
  5059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5060. ASSERT_EQ(StatusCode::OK_200, res->status);
  5061. ASSERT_EQ(4U, res->body.size());
  5062. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5063. "application/octet-stream");
  5064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5065. ASSERT_EQ(StatusCode::OK_200, res->status);
  5066. ASSERT_EQ(4U, res->body.size());
  5067. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5068. "application/octet-stream");
  5069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5070. ASSERT_EQ(StatusCode::OK_200, res->status);
  5071. ASSERT_EQ(4U, res->body.size());
  5072. }
  5073. TEST_F(ServerTest, BinaryString) {
  5074. auto binary = std::string("\x00\x01\x02\x03", 4);
  5075. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5077. ASSERT_EQ(StatusCode::OK_200, res->status);
  5078. ASSERT_EQ(4U, res->body.size());
  5079. res = cli_.Put("/binary", binary, "application/octet-stream");
  5080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5081. ASSERT_EQ(StatusCode::OK_200, res->status);
  5082. ASSERT_EQ(4U, res->body.size());
  5083. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. ASSERT_EQ(StatusCode::OK_200, res->status);
  5086. ASSERT_EQ(4U, res->body.size());
  5087. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5089. ASSERT_EQ(StatusCode::OK_200, res->status);
  5090. ASSERT_EQ(4U, res->body.size());
  5091. }
  5092. TEST_F(ServerTest, EmptyRequest) {
  5093. auto res = cli_.Get("");
  5094. ASSERT_TRUE(!res);
  5095. EXPECT_EQ(Error::Connection, res.error());
  5096. }
  5097. TEST_F(ServerTest, LongRequest) {
  5098. std::string request;
  5099. for (size_t i = 0; i < 545; i++) {
  5100. request += "/TooLongRequest";
  5101. }
  5102. request += "OK";
  5103. auto res = cli_.Get(request.c_str());
  5104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5105. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5106. }
  5107. TEST_F(ServerTest, TooLongRequest) {
  5108. std::string request;
  5109. for (size_t i = 0; i < 546; i++) {
  5110. request += "/TooLongRequest";
  5111. }
  5112. request += "_NG";
  5113. auto start = std::chrono::high_resolution_clock::now();
  5114. cli_.set_keep_alive(true);
  5115. auto res = cli_.Get(request.c_str());
  5116. auto end = std::chrono::high_resolution_clock::now();
  5117. auto elapsed =
  5118. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5119. .count();
  5120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5121. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5122. EXPECT_LE(elapsed, 1000);
  5123. EXPECT_EQ("close", res->get_header_value("Connection"));
  5124. EXPECT_FALSE(cli_.is_socket_open());
  5125. }
  5126. TEST_F(ServerTest, AlmostTooLongRequest) {
  5127. // test for #2046 - URI length check shouldn't include other content on req
  5128. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5129. // leading /, space, HTTP/1.1)
  5130. std::string request =
  5131. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5132. auto res = cli_.Get(request.c_str());
  5133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5134. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5135. }
  5136. TEST_F(ServerTest, LongHeader) {
  5137. Request req;
  5138. req.method = "GET";
  5139. req.path = "/hi";
  5140. std::string host_and_port;
  5141. host_and_port += HOST;
  5142. host_and_port += ":";
  5143. host_and_port += std::to_string(PORT);
  5144. req.headers.emplace("Host", host_and_port.c_str());
  5145. req.headers.emplace("Accept", "*/*");
  5146. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5147. req.headers.emplace(
  5148. "Header-Name",
  5149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5171. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5172. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5173. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5174. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5175. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5176. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5177. "@@@@@@@@@@@@@@@@");
  5178. auto res = std::make_shared<Response>();
  5179. auto error = Error::Success;
  5180. auto ret = cli_.send(req, *res, error);
  5181. ASSERT_TRUE(ret);
  5182. EXPECT_EQ(StatusCode::OK_200, res->status);
  5183. }
  5184. TEST_F(ServerTest, LongQueryValue) {
  5185. auto start = std::chrono::high_resolution_clock::now();
  5186. cli_.set_keep_alive(true);
  5187. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5188. auto end = std::chrono::high_resolution_clock::now();
  5189. auto elapsed =
  5190. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5191. .count();
  5192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5193. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5194. EXPECT_LE(elapsed, 1000);
  5195. EXPECT_EQ("close", res->get_header_value("Connection"));
  5196. EXPECT_FALSE(cli_.is_socket_open());
  5197. }
  5198. TEST_F(ServerTest, TooLongQueryValue) {
  5199. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5200. ASSERT_FALSE(res);
  5201. EXPECT_EQ(Error::Read, res.error());
  5202. }
  5203. TEST_F(ServerTest, TooLongHeader) {
  5204. Request req;
  5205. req.method = "GET";
  5206. req.path = "/hi";
  5207. std::string host_and_port;
  5208. host_and_port += HOST;
  5209. host_and_port += ":";
  5210. host_and_port += std::to_string(PORT);
  5211. req.headers.emplace("Host", host_and_port.c_str());
  5212. req.headers.emplace("Accept", "*/*");
  5213. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5214. req.headers.emplace(
  5215. "Header-Name",
  5216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5223. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5224. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5225. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5226. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5227. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5228. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5229. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5230. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5231. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5232. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5233. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5234. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5235. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5236. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5237. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5238. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5239. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5240. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5241. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5242. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5243. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5244. "@@@@@@@@@@@@@@@@@");
  5245. auto res = std::make_shared<Response>();
  5246. auto error = Error::Success;
  5247. auto ret = cli_.send(req, *res, error);
  5248. ASSERT_TRUE(ret);
  5249. EXPECT_EQ(StatusCode::OK_200, res->status);
  5250. }
  5251. TEST_F(ServerTest, HeaderCountAtLimit) {
  5252. // Test with headers just under the 100 limit
  5253. httplib::Headers headers;
  5254. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5255. // This should keep us just under the 100 header limit
  5256. for (int i = 0; i < 95; i++) {
  5257. std::string name = "X-Test-Header-" + std::to_string(i);
  5258. std::string value = "value" + std::to_string(i);
  5259. headers.emplace(name, value);
  5260. }
  5261. // This should work fine as we're under the limit
  5262. auto res = cli_.Get("/hi", headers);
  5263. EXPECT_TRUE(res);
  5264. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5265. }
  5266. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5267. // Test with many headers to exceed the 100 limit
  5268. httplib::Headers headers;
  5269. // Add 150 headers to definitely exceed the 100 limit
  5270. for (int i = 0; i < 150; i++) {
  5271. std::string name = "X-Test-Header-" + std::to_string(i);
  5272. std::string value = "value" + std::to_string(i);
  5273. headers.emplace(name, value);
  5274. }
  5275. // This should fail due to exceeding header count limit
  5276. cli_.set_keep_alive(true);
  5277. auto res = cli_.Get("/hi", headers);
  5278. // The server should respond with 400 Bad Request
  5279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5280. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5281. EXPECT_EQ("close", res->get_header_value("Connection"));
  5282. EXPECT_FALSE(cli_.is_socket_open());
  5283. }
  5284. TEST_F(ServerTest, PercentEncoding) {
  5285. auto res = cli_.Get("/e%6edwith%");
  5286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5287. EXPECT_EQ(StatusCode::OK_200, res->status);
  5288. }
  5289. TEST_F(ServerTest, PercentEncodingUnicode) {
  5290. auto res = cli_.Get("/e%u006edwith%");
  5291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5292. EXPECT_EQ(StatusCode::OK_200, res->status);
  5293. }
  5294. TEST_F(ServerTest, InvalidPercentEncoding) {
  5295. auto res = cli_.Get("/%endwith%");
  5296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5297. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5298. }
  5299. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5300. auto res = cli_.Get("/%uendwith%");
  5301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5302. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5303. }
  5304. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5305. auto res = cli_.Get("/hello?aaa=bbb%");
  5306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5307. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5308. }
  5309. TEST_F(ServerTest, PlusSignEncoding) {
  5310. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5312. EXPECT_EQ(StatusCode::OK_200, res->status);
  5313. EXPECT_EQ("a +b", res->body);
  5314. }
  5315. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5316. // This test simulates a potential DoS attack using many headers
  5317. // to verify our security fix prevents memory exhaustion
  5318. httplib::Headers attack_headers;
  5319. // Attempt to add many headers like an attacker would (200 headers to far
  5320. // exceed limit)
  5321. for (int i = 0; i < 200; i++) {
  5322. std::string name = "X-Attack-Header-" + std::to_string(i);
  5323. std::string value = "attack_payload_" + std::to_string(i);
  5324. attack_headers.emplace(name, value);
  5325. }
  5326. // Try to POST with excessive headers
  5327. cli_.set_keep_alive(true);
  5328. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5329. // Should either fail or return 400 Bad Request due to security limit
  5330. if (res) {
  5331. // If we get a response, it should be 400 Bad Request
  5332. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5333. EXPECT_EQ("close", res->get_header_value("Connection"));
  5334. }
  5335. EXPECT_FALSE(cli_.is_socket_open());
  5336. }
  5337. TEST_F(ServerTest, MultipartFormData) {
  5338. UploadFormDataItems items = {
  5339. {"text1", "text default", "", ""},
  5340. {"text2", "aωb", "", ""},
  5341. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5342. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5343. {"file3", "", "", "application/octet-stream"},
  5344. {"file4", "", "", " application/json tmp-string "}};
  5345. auto res = cli_.Post("/multipart", items);
  5346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5347. EXPECT_EQ(StatusCode::OK_200, res->status);
  5348. }
  5349. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5350. UploadFormDataItems items = {
  5351. {"text", "default text", "", ""},
  5352. {"multi_text1", "aaaaa", "", ""},
  5353. {"multi_text1", "bbbbb", "", ""},
  5354. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5355. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5356. "application/json"},
  5357. };
  5358. auto res = cli_.Post("/multipart/multi_file_values", items);
  5359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5360. EXPECT_EQ(StatusCode::OK_200, res->status);
  5361. }
  5362. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5363. auto res = cli_.Get("/hi");
  5364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5365. EXPECT_EQ(StatusCode::OK_200, res->status);
  5366. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5367. EXPECT_EQ("Hello World!", res->body);
  5368. }
  5369. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5370. Request req;
  5371. req.method = "POST";
  5372. req.path = "/chunked";
  5373. std::string host_and_port;
  5374. host_and_port += HOST;
  5375. host_and_port += ":";
  5376. host_and_port += std::to_string(PORT);
  5377. req.headers.emplace("Host", host_and_port.c_str());
  5378. req.headers.emplace("Accept", "*/*");
  5379. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5380. req.headers.emplace("Content-Type", "text/plain");
  5381. req.headers.emplace("Content-Length", "0");
  5382. req.headers.emplace(
  5383. "Transfer-Encoding",
  5384. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5385. // Client does not chunk, so make a chunked body manually.
  5386. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5387. auto res = std::make_shared<Response>();
  5388. auto error = Error::Success;
  5389. auto ret = cli_.send(req, *res, error);
  5390. ASSERT_TRUE(ret);
  5391. EXPECT_EQ(StatusCode::OK_200, res->status);
  5392. }
  5393. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5394. // rather than treat them as valid lengths.
  5395. template <typename ClientT>
  5396. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5397. Request req;
  5398. req.method = "POST";
  5399. req.path = "/chunked";
  5400. std::string host_and_port;
  5401. host_and_port += HOST;
  5402. host_and_port += ":";
  5403. host_and_port += std::to_string(PORT);
  5404. req.headers.emplace("Host", host_and_port.c_str());
  5405. req.headers.emplace("Content-Length", "0");
  5406. req.headers.emplace("Transfer-Encoding", "chunked");
  5407. req.body = body;
  5408. auto res = std::make_shared<Response>();
  5409. auto error = Error::Success;
  5410. ASSERT_TRUE(cli.send(req, *res, error));
  5411. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5412. }
  5413. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5414. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5415. }
  5416. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5417. expect_chunked_body_rejected(
  5418. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5419. }
  5420. TEST_F(ServerTest, GetStreamed2) {
  5421. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5423. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5424. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5425. EXPECT_EQ(true, res->has_header("Content-Range"));
  5426. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5427. EXPECT_EQ(std::string("ab"), res->body);
  5428. }
  5429. TEST_F(ServerTest, GetStreamed) {
  5430. auto res = cli_.Get("/streamed");
  5431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5432. EXPECT_EQ(StatusCode::OK_200, res->status);
  5433. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5434. EXPECT_EQ(std::string("aaabbb"), res->body);
  5435. }
  5436. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5437. auto res = cli_.Get("/streamed-without-length",
  5438. Headers{make_range_header({{0, -1}})});
  5439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5440. EXPECT_EQ(StatusCode::OK_200, res->status);
  5441. EXPECT_EQ(false, res->has_header("Content-Length"));
  5442. EXPECT_EQ(false, res->has_header("Content-Range"));
  5443. EXPECT_EQ(std::string("abcdefg"), res->body);
  5444. }
  5445. TEST_F(ServerTest, GetStreamedWithRange1) {
  5446. auto res =
  5447. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5449. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5450. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5451. EXPECT_EQ(true, res->has_header("Content-Range"));
  5452. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5453. EXPECT_EQ(std::string("def"), res->body);
  5454. }
  5455. TEST_F(ServerTest, GetStreamedWithRange2) {
  5456. auto res =
  5457. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5460. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5461. EXPECT_EQ(true, res->has_header("Content-Range"));
  5462. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5463. EXPECT_EQ(std::string("bcdefg"), res->body);
  5464. }
  5465. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5466. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5469. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5470. EXPECT_EQ(true, res->has_header("Content-Range"));
  5471. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5472. EXPECT_EQ(std::string("efg"), res->body);
  5473. }
  5474. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5475. auto res =
  5476. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5479. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5480. EXPECT_EQ(false, res->has_header("Content-Range"));
  5481. EXPECT_EQ(0U, res->body.size());
  5482. }
  5483. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5484. // Only a 206 is served as a partial representation. Under any other status
  5485. // `apply_ranges()` reported the full content length, so the body must match
  5486. // that header, and the content provider must never be asked for an offset
  5487. // outside the representation.
  5488. auto check = [&](int status, const char *range) {
  5489. auto path =
  5490. std::string("/streamed-with-range?status=") + std::to_string(status);
  5491. auto ctx = path + " Range: " + range;
  5492. auto res = cli_.Get(path, Headers{{"Range", range}});
  5493. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5494. EXPECT_EQ(status, res->status) << ctx;
  5495. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5496. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5497. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5498. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5499. };
  5500. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5501. check(403, "bytes=3-5");
  5502. // The offset is far past the representation.
  5503. check(403, "bytes=100000-100200");
  5504. // `first_pos` is still -1 here, and the bounds asserts in
  5505. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5506. check(403, "bytes=-3");
  5507. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5508. // multipart branch would have written one that is empty.
  5509. check(403, "bytes=1-2, 4-5");
  5510. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5511. // covers the whole representation.
  5512. check(200, "bytes=3-5");
  5513. check(200, "bytes=1-2, 4-5");
  5514. }
  5515. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5516. auto res =
  5517. cli_.Get("/streamed-with-range",
  5518. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5519. "92233720368547758079223372036854775807"}});
  5520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5521. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5522. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5523. EXPECT_EQ(false, res->has_header("Content-Range"));
  5524. EXPECT_EQ(0U, res->body.size());
  5525. }
  5526. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5527. auto res = cli_.Get(
  5528. "/with-range",
  5529. Headers{{"Range",
  5530. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5531. {"Accept-Encoding", ""}});
  5532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5533. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5534. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5535. EXPECT_EQ(true, res->has_header("Content-Range"));
  5536. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5537. EXPECT_EQ(std::string("abcdefg"), res->body);
  5538. }
  5539. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5540. auto res = cli_.Get("/with-range", Headers{
  5541. {"Range", "bytes=0-"},
  5542. {"Accept-Encoding", ""},
  5543. });
  5544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5545. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5546. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5547. EXPECT_EQ(true, res->has_header("Content-Range"));
  5548. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5549. EXPECT_EQ(std::string("abcdefg"), res->body);
  5550. }
  5551. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5552. auto res = cli_.Get("/streamed-with-range",
  5553. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5555. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5556. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5557. EXPECT_EQ(false, res->has_header("Content-Range"));
  5558. EXPECT_EQ(267U, res->body.size());
  5559. // Check that both range contents are present
  5560. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5561. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5562. // Check that Content-Range headers are present for both ranges
  5563. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5564. std::string::npos);
  5565. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5566. std::string::npos);
  5567. }
  5568. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5569. Ranges ranges;
  5570. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5571. ranges.emplace_back(0, -1);
  5572. }
  5573. auto res = cli_.Get("/streamed-with-range?error",
  5574. Headers{{make_range_header(ranges)}});
  5575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5576. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5577. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5578. EXPECT_EQ(false, res->has_header("Content-Range"));
  5579. EXPECT_EQ(0U, res->body.size());
  5580. }
  5581. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5582. auto res = cli_.Get("/streamed-with-range",
  5583. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5585. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5586. EXPECT_EQ(5U, res->body.size());
  5587. // Check that overlapping ranges are coalesced into a single range
  5588. EXPECT_EQ("bcdef", res->body);
  5589. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5590. // Should be single range, not multipart
  5591. EXPECT_TRUE(res->has_header("Content-Range"));
  5592. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5593. }
  5594. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5595. auto res = cli_.Get("/streamed-with-range",
  5596. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5598. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5599. EXPECT_EQ(268U, res->body.size());
  5600. // Check that both range contents are present
  5601. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5602. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5603. // Check that Content-Range headers are present for both ranges
  5604. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5605. std::string::npos);
  5606. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5607. std::string::npos);
  5608. }
  5609. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5610. auto res = cli_.Get("/streamed-with-range",
  5611. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5613. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5614. EXPECT_EQ(269U, res->body.size());
  5615. // Check that both duplicate range contents are present
  5616. size_t first_abc = res->body.find("abc\r\n");
  5617. EXPECT_TRUE(first_abc != std::string::npos);
  5618. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5619. EXPECT_TRUE(second_abc != std::string::npos);
  5620. // Check that Content-Range headers are present for both ranges
  5621. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5622. EXPECT_TRUE(first_range != std::string::npos);
  5623. size_t second_range =
  5624. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5625. EXPECT_TRUE(second_range != std::string::npos);
  5626. }
  5627. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5628. auto res =
  5629. cli_.Get("/streamed-with-range?error",
  5630. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5633. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5634. EXPECT_EQ(false, res->has_header("Content-Range"));
  5635. EXPECT_EQ(0U, res->body.size());
  5636. }
  5637. TEST_F(ServerTest, GetStreamedEndless) {
  5638. uint64_t offset = 0;
  5639. auto res = cli_.Get("/streamed-cancel",
  5640. [&](const char * /*data*/, uint64_t data_length) {
  5641. if (offset < 100) {
  5642. offset += data_length;
  5643. return true;
  5644. }
  5645. return false;
  5646. });
  5647. ASSERT_TRUE(!res);
  5648. EXPECT_EQ(Error::Canceled, res.error());
  5649. }
  5650. TEST_F(ServerTest, ClientStop) {
  5651. std::atomic_size_t count{4};
  5652. std::vector<std::thread> threads;
  5653. for (auto i = count.load(); i != 0; --i) {
  5654. threads.emplace_back([&]() {
  5655. auto res = cli_.Get("/streamed-cancel",
  5656. [&](const char *, uint64_t) { return true; });
  5657. --count;
  5658. ASSERT_TRUE(!res);
  5659. EXPECT_TRUE(res.error() == Error::Canceled ||
  5660. res.error() == Error::Read || res.error() == Error::Write);
  5661. });
  5662. }
  5663. std::this_thread::sleep_for(std::chrono::seconds(2));
  5664. while (count != 0) {
  5665. cli_.stop();
  5666. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5667. }
  5668. for (auto &t : threads) {
  5669. t.join();
  5670. }
  5671. }
  5672. TEST_F(ServerTest, GetWithRange1) {
  5673. auto res = cli_.Get("/with-range", Headers{
  5674. make_range_header({{3, 5}}),
  5675. {"Accept-Encoding", ""},
  5676. });
  5677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5678. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5679. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5680. EXPECT_EQ(true, res->has_header("Content-Range"));
  5681. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5682. EXPECT_EQ(std::string("def"), res->body);
  5683. }
  5684. TEST_F(ServerTest, GetWithRange2) {
  5685. auto res = cli_.Get("/with-range", Headers{
  5686. make_range_header({{1, -1}}),
  5687. {"Accept-Encoding", ""},
  5688. });
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5691. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5692. EXPECT_EQ(true, res->has_header("Content-Range"));
  5693. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5694. EXPECT_EQ(std::string("bcdefg"), res->body);
  5695. }
  5696. TEST_F(ServerTest, GetWithRange3) {
  5697. auto res = cli_.Get("/with-range", Headers{
  5698. make_range_header({{0, 0}}),
  5699. {"Accept-Encoding", ""},
  5700. });
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5703. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5704. EXPECT_EQ(true, res->has_header("Content-Range"));
  5705. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5706. EXPECT_EQ(std::string("a"), res->body);
  5707. }
  5708. TEST_F(ServerTest, GetWithRange4) {
  5709. auto res = cli_.Get("/with-range", Headers{
  5710. make_range_header({{-1, 2}}),
  5711. {"Accept-Encoding", ""},
  5712. });
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5715. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5716. EXPECT_EQ(true, res->has_header("Content-Range"));
  5717. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5718. EXPECT_EQ(std::string("fg"), res->body);
  5719. }
  5720. TEST_F(ServerTest, GetWithRange5) {
  5721. auto res = cli_.Get("/with-range", Headers{
  5722. make_range_header({{0, 5}}),
  5723. {"Accept-Encoding", ""},
  5724. });
  5725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5726. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5727. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5728. EXPECT_EQ(true, res->has_header("Content-Range"));
  5729. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5730. EXPECT_EQ(std::string("abcdef"), res->body);
  5731. }
  5732. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5733. auto res =
  5734. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5736. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5737. }
  5738. TEST_F(ServerTest, GetWithRangeMultipart) {
  5739. auto res =
  5740. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5742. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5743. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5744. EXPECT_EQ(false, res->has_header("Content-Range"));
  5745. EXPECT_EQ(267U, res->body.size());
  5746. }
  5747. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5748. auto res = cli_.Get("/with-range",
  5749. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5751. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5752. }
  5753. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5754. auto res = cli_.Get("/with-range-customized-response",
  5755. Headers{{make_range_header({{1, 2}})}});
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5758. EXPECT_EQ(true, res->has_header("Content-Length"));
  5759. EXPECT_EQ(false, res->has_header("Content-Range"));
  5760. EXPECT_EQ(JSON_DATA, res->body);
  5761. }
  5762. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5763. auto res = cli_.Get("/with-range-customized-response",
  5764. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5766. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5767. EXPECT_EQ(true, res->has_header("Content-Length"));
  5768. EXPECT_EQ(false, res->has_header("Content-Range"));
  5769. EXPECT_EQ(JSON_DATA, res->body);
  5770. }
  5771. TEST_F(ServerTest, Issue1772) {
  5772. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5774. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5775. }
  5776. TEST_F(ServerTest, Issue609) {
  5777. auto res = cli_.Delete("/issue609");
  5778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5779. EXPECT_EQ(StatusCode::OK_200, res->status);
  5780. EXPECT_EQ(std::string("ok"), res->body);
  5781. }
  5782. TEST_F(ServerTest, GetStreamedChunked) {
  5783. auto res = cli_.Get("/streamed-chunked");
  5784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5785. EXPECT_EQ(StatusCode::OK_200, res->status);
  5786. EXPECT_EQ(std::string("123456789"), res->body);
  5787. }
  5788. TEST_F(ServerTest, GetStreamedChunked2) {
  5789. auto res = cli_.Get("/streamed-chunked2");
  5790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5791. EXPECT_EQ(StatusCode::OK_200, res->status);
  5792. EXPECT_EQ(std::string("123456789"), res->body);
  5793. }
  5794. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5795. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5797. EXPECT_EQ(StatusCode::OK_200, res->status);
  5798. EXPECT_EQ(std::string("123456789"), res->body);
  5799. EXPECT_TRUE(res->has_header("Trailer"));
  5800. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5801. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5802. // Trailers are now stored separately from headers (security fix)
  5803. EXPECT_EQ(2U, res->trailers.size());
  5804. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5805. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5806. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5807. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5808. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5809. // Verify trailers are NOT in headers (security verification)
  5810. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5811. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5812. }
  5813. TEST_F(ServerTest, LargeChunkedPost) {
  5814. Request req;
  5815. req.method = "POST";
  5816. req.path = "/large-chunked";
  5817. std::string host_and_port;
  5818. host_and_port += HOST;
  5819. host_and_port += ":";
  5820. host_and_port += std::to_string(PORT);
  5821. req.headers.emplace("Host", host_and_port.c_str());
  5822. req.headers.emplace("Accept", "*/*");
  5823. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5824. req.headers.emplace("Content-Type", "text/plain");
  5825. req.headers.emplace("Content-Length", "0");
  5826. req.headers.emplace("Transfer-Encoding", "chunked");
  5827. std::string long_string(30 * 1024u, 'a');
  5828. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5829. // Attempt to make a large enough post to exceed OS buffers, to test that
  5830. // the server handles short reads if the full chunk data isn't available.
  5831. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5832. auto res = std::make_shared<Response>();
  5833. auto error = Error::Success;
  5834. auto ret = cli_.send(req, *res, error);
  5835. ASSERT_TRUE(ret);
  5836. EXPECT_EQ(StatusCode::OK_200, res->status);
  5837. }
  5838. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5839. auto res = cli_.Get("/remote_addr");
  5840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5841. EXPECT_EQ(StatusCode::OK_200, res->status);
  5842. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5843. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5844. }
  5845. TEST_F(ServerTest, GetMethodLocalAddr) {
  5846. auto res = cli_.Get("/local_addr");
  5847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5848. EXPECT_EQ(StatusCode::OK_200, res->status);
  5849. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5850. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5851. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5852. }
  5853. TEST_F(ServerTest, HTTPResponseSplitting) {
  5854. auto res = cli_.Get("/http_response_splitting");
  5855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5856. EXPECT_EQ(StatusCode::OK_200, res->status);
  5857. }
  5858. TEST_F(ServerTest, SlowRequest) {
  5859. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5860. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5861. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5862. }
  5863. #if 0
  5864. TEST_F(ServerTest, SlowPost) {
  5865. char buffer[64 * 1024];
  5866. memset(buffer, 0x42, sizeof(buffer));
  5867. auto res = cli_.Post(
  5868. "/slowpost", 64 * 1024 * 1024,
  5869. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5870. auto ret = sink.write(buffer, sizeof(buffer));
  5871. EXPECT_TRUE(ret);
  5872. return true;
  5873. },
  5874. "text/plain");
  5875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5876. EXPECT_EQ(StatusCode::OK_200, res->status);
  5877. }
  5878. TEST_F(ServerTest, SlowPostFail) {
  5879. char buffer[64 * 1024];
  5880. memset(buffer, 0x42, sizeof(buffer));
  5881. cli_.set_write_timeout(std::chrono::seconds(0));
  5882. auto res = cli_.Post(
  5883. "/slowpost", 64 * 1024 * 1024,
  5884. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5885. sink.write(buffer, sizeof(buffer));
  5886. return true;
  5887. },
  5888. "text/plain");
  5889. ASSERT_TRUE(!res);
  5890. EXPECT_EQ(Error::Write, res.error());
  5891. }
  5892. #endif
  5893. TEST_F(ServerTest, Put) {
  5894. auto res = cli_.Put("/put", "PUT", "text/plain");
  5895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5896. EXPECT_EQ(StatusCode::OK_200, res->status);
  5897. EXPECT_EQ("PUT", res->body);
  5898. }
  5899. TEST_F(ServerTest, PutWithContentProvider) {
  5900. auto res = cli_.Put(
  5901. "/put", 3,
  5902. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5903. sink.os << "PUT";
  5904. return true;
  5905. },
  5906. "text/plain");
  5907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5908. EXPECT_EQ(StatusCode::OK_200, res->status);
  5909. EXPECT_EQ("PUT", res->body);
  5910. }
  5911. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5912. auto res = cli_.Post(
  5913. "/post", 42,
  5914. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5915. return false;
  5916. },
  5917. "text/plain");
  5918. ASSERT_TRUE(!res);
  5919. EXPECT_EQ(Error::Canceled, res.error());
  5920. }
  5921. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5922. auto res = cli_.Put(
  5923. "/put",
  5924. [](size_t /*offset*/, DataSink &sink) {
  5925. sink.os << "PUT";
  5926. sink.done();
  5927. return true;
  5928. },
  5929. "text/plain");
  5930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5931. EXPECT_EQ(StatusCode::OK_200, res->status);
  5932. EXPECT_EQ("PUT", res->body);
  5933. }
  5934. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5935. auto res = cli_.Post(
  5936. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5937. "text/plain");
  5938. ASSERT_TRUE(!res);
  5939. EXPECT_EQ(Error::Canceled, res.error());
  5940. }
  5941. TEST_F(ServerTest, PostLoopBack) {
  5942. std::string body;
  5943. auto res = cli_.Post(
  5944. "/post-loopback", 9,
  5945. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5946. EXPECT_EQ(9u, length);
  5947. sink.write("123", 3);
  5948. sink.write("456", 3);
  5949. sink.write("789", 3);
  5950. return true;
  5951. },
  5952. "text/plain",
  5953. [&body](const char *data, size_t data_length) {
  5954. body.append(data, data_length);
  5955. return true;
  5956. });
  5957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5958. EXPECT_EQ(StatusCode::OK_200, res->status);
  5959. EXPECT_EQ("123456789", body);
  5960. }
  5961. TEST_F(ServerTest, PutLoopBack) {
  5962. std::string body;
  5963. auto res = cli_.Put(
  5964. "/put-loopback", 9,
  5965. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5966. EXPECT_EQ(9u, length);
  5967. sink.write("123", 3);
  5968. sink.write("456", 3);
  5969. sink.write("789", 3);
  5970. return true;
  5971. },
  5972. "text/plain",
  5973. [&body](const char *data, size_t data_length) {
  5974. body.append(data, data_length);
  5975. return true;
  5976. });
  5977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5978. EXPECT_EQ(StatusCode::OK_200, res->status);
  5979. EXPECT_EQ("123456789", body);
  5980. }
  5981. TEST_F(ServerTest, PatchLoopBack) {
  5982. std::string body;
  5983. auto res = cli_.Patch(
  5984. "/patch-loopback", 9,
  5985. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5986. EXPECT_EQ(9u, length);
  5987. sink.write("123", 3);
  5988. sink.write("456", 3);
  5989. sink.write("789", 3);
  5990. return true;
  5991. },
  5992. "text/plain",
  5993. [&body](const char *data, size_t data_length) {
  5994. body.append(data, data_length);
  5995. return true;
  5996. });
  5997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5998. EXPECT_EQ(StatusCode::OK_200, res->status);
  5999. EXPECT_EQ("123456789", body);
  6000. }
  6001. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6002. std::string body;
  6003. auto res = cli_.Post(
  6004. "/post-loopback",
  6005. [](size_t /*offset*/, DataSink &sink) {
  6006. sink.write("123", 3);
  6007. sink.write("456", 3);
  6008. sink.write("789", 3);
  6009. sink.done();
  6010. return true;
  6011. },
  6012. "text/plain",
  6013. [&body](const char *data, size_t data_length) {
  6014. body.append(data, data_length);
  6015. return true;
  6016. });
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. EXPECT_EQ("123456789", body);
  6020. }
  6021. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6022. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6023. cli_.set_compress(true);
  6024. auto res = cli_.Put(
  6025. "/put", 3,
  6026. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6027. sink.os << "PUT";
  6028. return true;
  6029. },
  6030. "text/plain");
  6031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6032. EXPECT_EQ(StatusCode::OK_200, res->status);
  6033. EXPECT_EQ("PUT", res->body);
  6034. }
  6035. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6036. cli_.set_compress(true);
  6037. auto res = cli_.Post(
  6038. "/post", 42,
  6039. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6040. return false;
  6041. },
  6042. "text/plain");
  6043. ASSERT_TRUE(!res);
  6044. EXPECT_EQ(Error::Canceled, res.error());
  6045. }
  6046. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6047. cli_.set_compress(true);
  6048. auto res = cli_.Put(
  6049. "/put",
  6050. [](size_t /*offset*/, DataSink &sink) {
  6051. sink.os << "PUT";
  6052. sink.done();
  6053. return true;
  6054. },
  6055. "text/plain");
  6056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6057. EXPECT_EQ(StatusCode::OK_200, res->status);
  6058. EXPECT_EQ("PUT", res->body);
  6059. }
  6060. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6061. cli_.set_compress(true);
  6062. auto res = cli_.Post(
  6063. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6064. "text/plain");
  6065. ASSERT_TRUE(!res);
  6066. EXPECT_EQ(Error::Canceled, res.error());
  6067. }
  6068. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6069. cli_.set_compress(true);
  6070. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::OK_200, res->status);
  6073. EXPECT_EQ(LARGE_DATA, res->body);
  6074. }
  6075. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6076. #ifdef CPPHTTPLIB_SSL_ENABLED
  6077. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6078. Client cli(s.c_str());
  6079. cli.enable_server_certificate_verification(false);
  6080. #else
  6081. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6082. Client cli(s.c_str());
  6083. #endif
  6084. cli.set_compress(true);
  6085. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. EXPECT_EQ(StatusCode::OK_200, res->status);
  6088. EXPECT_EQ(LARGE_DATA, res->body);
  6089. // The compressed size should be less than a 10th of the original. May vary
  6090. // depending on the zlib library.
  6091. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6092. static_cast<uint64_t>(10 * 1024 * 1024));
  6093. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6094. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6095. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6096. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6097. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6098. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6099. #endif
  6100. }
  6101. TEST_F(ServerTest, PutContentWithDeflate) {
  6102. cli_.set_compress(false);
  6103. Headers headers;
  6104. headers.emplace("Content-Encoding", "deflate");
  6105. // PUT in deflate format:
  6106. auto res = cli_.Put("/put", headers,
  6107. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6109. EXPECT_EQ(StatusCode::OK_200, res->status);
  6110. EXPECT_EQ("PUT", res->body);
  6111. }
  6112. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6113. Headers headers;
  6114. headers.emplace("Accept-Encoding", "gzip, deflate");
  6115. auto res = cli_.Get("/streamed-chunked", headers);
  6116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6117. EXPECT_EQ(StatusCode::OK_200, res->status);
  6118. EXPECT_EQ(std::string("123456789"), res->body);
  6119. }
  6120. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6121. Headers headers;
  6122. headers.emplace("Accept-Encoding", "gzip, deflate");
  6123. auto res = cli_.Get("/streamed-chunked2", headers);
  6124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6125. EXPECT_EQ(StatusCode::OK_200, res->status);
  6126. EXPECT_EQ(std::string("123456789"), res->body);
  6127. }
  6128. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6129. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6131. EXPECT_EQ(StatusCode::OK_200, res->status);
  6132. }
  6133. TEST(GzipDecompressor, ChunkedDecompression) {
  6134. std::string data;
  6135. for (size_t i = 0; i < 32 * 1024; ++i) {
  6136. data.push_back(static_cast<char>('a' + i % 26));
  6137. }
  6138. std::string compressed_data;
  6139. {
  6140. httplib::detail::gzip_compressor compressor;
  6141. bool result = compressor.compress(
  6142. data.data(), data.size(),
  6143. /*last=*/true,
  6144. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6145. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6146. compressed_data_size);
  6147. return true;
  6148. });
  6149. ASSERT_TRUE(result);
  6150. }
  6151. std::string decompressed_data;
  6152. {
  6153. httplib::detail::gzip_decompressor decompressor;
  6154. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6155. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6156. size_t chunk_size = 130;
  6157. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6158. chunk_begin += chunk_size) {
  6159. size_t current_chunk_size =
  6160. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6161. bool result = decompressor.decompress(
  6162. compressed_data.data() + chunk_begin, current_chunk_size,
  6163. [&](const char *decompressed_data_chunk,
  6164. size_t decompressed_data_chunk_size) {
  6165. decompressed_data.insert(decompressed_data.size(),
  6166. decompressed_data_chunk,
  6167. decompressed_data_chunk_size);
  6168. return true;
  6169. });
  6170. ASSERT_TRUE(result);
  6171. }
  6172. }
  6173. ASSERT_EQ(data, decompressed_data);
  6174. }
  6175. TEST(GzipDecompressor, DeflateDecompression) {
  6176. std::string original_text = "Raw deflate without gzip";
  6177. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6178. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6179. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6180. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6181. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6182. std::string decompressed_data;
  6183. {
  6184. httplib::detail::gzip_decompressor decompressor;
  6185. bool result = decompressor.decompress(
  6186. compressed_data.data(), compressed_data.size(),
  6187. [&](const char *decompressed_data_chunk,
  6188. size_t decompressed_data_chunk_size) {
  6189. decompressed_data.insert(decompressed_data.size(),
  6190. decompressed_data_chunk,
  6191. decompressed_data_chunk_size);
  6192. return true;
  6193. });
  6194. ASSERT_TRUE(result);
  6195. }
  6196. ASSERT_EQ(original_text, decompressed_data);
  6197. }
  6198. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6199. std::string original_text = "Raw deflate without gzip";
  6200. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6201. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6202. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6203. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6204. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6205. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6206. std::string decompressed_data;
  6207. {
  6208. httplib::detail::gzip_decompressor decompressor;
  6209. bool result = decompressor.decompress(
  6210. compressed_data.data(), compressed_data.size(),
  6211. [&](const char *decompressed_data_chunk,
  6212. size_t decompressed_data_chunk_size) {
  6213. decompressed_data.insert(decompressed_data.size(),
  6214. decompressed_data_chunk,
  6215. decompressed_data_chunk_size);
  6216. return true;
  6217. });
  6218. ASSERT_TRUE(result);
  6219. }
  6220. ASSERT_EQ(original_text, decompressed_data);
  6221. }
  6222. #endif
  6223. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6224. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6225. Headers headers;
  6226. headers.emplace("Accept-Encoding", "br");
  6227. auto res = cli_.Get("/streamed-chunked", headers);
  6228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6229. EXPECT_EQ(StatusCode::OK_200, res->status);
  6230. EXPECT_EQ(std::string("123456789"), res->body);
  6231. }
  6232. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6233. Headers headers;
  6234. headers.emplace("Accept-Encoding", "br");
  6235. auto res = cli_.Get("/streamed-chunked2", headers);
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. EXPECT_EQ(StatusCode::OK_200, res->status);
  6238. EXPECT_EQ(std::string("123456789"), res->body);
  6239. }
  6240. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6241. cli_.set_compress(true);
  6242. auto res = cli_.Put(
  6243. "/put", 3,
  6244. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6245. sink.os << "PUT";
  6246. return true;
  6247. },
  6248. "text/plain");
  6249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6250. EXPECT_EQ(StatusCode::OK_200, res->status);
  6251. EXPECT_EQ("PUT", res->body);
  6252. }
  6253. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6254. cli_.set_compress(true);
  6255. auto res = cli_.Put(
  6256. "/put",
  6257. [](size_t /*offset*/, DataSink &sink) {
  6258. sink.os << "PUT";
  6259. sink.done();
  6260. return true;
  6261. },
  6262. "text/plain");
  6263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6264. EXPECT_EQ(StatusCode::OK_200, res->status);
  6265. EXPECT_EQ("PUT", res->body);
  6266. }
  6267. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6268. cli_.set_compress(true);
  6269. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. EXPECT_EQ(StatusCode::OK_200, res->status);
  6272. EXPECT_EQ(LARGE_DATA, res->body);
  6273. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6274. }
  6275. #endif
  6276. TEST_F(ServerTest, Patch) {
  6277. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. EXPECT_EQ(StatusCode::OK_200, res->status);
  6280. EXPECT_EQ("PATCH", res->body);
  6281. }
  6282. TEST_F(ServerTest, Delete) {
  6283. auto res = cli_.Delete("/delete");
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. EXPECT_EQ(StatusCode::OK_200, res->status);
  6286. EXPECT_EQ("DELETE", res->body);
  6287. }
  6288. TEST_F(ServerTest, DeleteContentReceiver) {
  6289. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. EXPECT_EQ(StatusCode::OK_200, res->status);
  6292. EXPECT_EQ("content", res->body);
  6293. }
  6294. TEST_F(ServerTest, Options) {
  6295. auto res = cli_.Options("*");
  6296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6297. EXPECT_EQ(StatusCode::OK_200, res->status);
  6298. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6299. EXPECT_TRUE(res->body.empty());
  6300. }
  6301. TEST_F(ServerTest, URL) {
  6302. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::OK_200, res->status);
  6305. }
  6306. TEST_F(ServerTest, ArrayParam) {
  6307. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. EXPECT_EQ(StatusCode::OK_200, res->status);
  6310. }
  6311. TEST_F(ServerTest, ArrayParamValues) {
  6312. auto res =
  6313. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6315. EXPECT_EQ(StatusCode::OK_200, res->status);
  6316. }
  6317. TEST_F(ServerTest, NoMultipleHeaders) {
  6318. Headers headers = {{"Content-Length", "5"}};
  6319. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6320. "text/plain");
  6321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6322. EXPECT_EQ(StatusCode::OK_200, res->status);
  6323. }
  6324. TEST_F(ServerTest, PostContentReceiver) {
  6325. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6327. ASSERT_EQ(StatusCode::OK_200, res->status);
  6328. ASSERT_EQ("content", res->body);
  6329. }
  6330. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6331. UploadFormDataItems items = {
  6332. {"text1", "text default", "", ""},
  6333. {"text2", "aωb", "", ""},
  6334. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6335. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6336. {"file3", "", "", "application/octet-stream"},
  6337. };
  6338. auto res = cli_.Post("/content_receiver", items);
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::OK_200, res->status);
  6341. }
  6342. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6343. UploadFormDataItems items = {
  6344. {"text1", "text default", "", ""},
  6345. {"text2", "aωb", "", ""},
  6346. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6347. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6348. {"file3", "", "", "application/octet-stream"},
  6349. };
  6350. auto boundary = std::string("+++++");
  6351. std::string body;
  6352. for (const auto &item : items) {
  6353. body += "--" + boundary + "\r\n";
  6354. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6355. if (!item.filename.empty()) {
  6356. body += "; filename=\"" + item.filename + "\"";
  6357. }
  6358. body += "\r\n";
  6359. if (!item.content_type.empty()) {
  6360. body += "Content-Type: " + item.content_type + "\r\n";
  6361. }
  6362. body += "\r\n";
  6363. body += item.content + "\r\n";
  6364. }
  6365. body += "--" + boundary + "--\r\n";
  6366. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6367. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::OK_200, res->status);
  6370. }
  6371. TEST(MultipartFormDataTest, FieldEscaping) {
  6372. Server svr;
  6373. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6374. const ContentReader &content_reader) {
  6375. ASSERT_TRUE(req.is_multipart_form_data());
  6376. std::vector<FormData> received;
  6377. content_reader(
  6378. [&](const FormData &file) {
  6379. received.push_back(file);
  6380. return true;
  6381. },
  6382. [&](const char *data, size_t data_length) {
  6383. received.back().content.append(data, data_length);
  6384. return true;
  6385. });
  6386. // '"', CR and LF in names and filenames are escaped following the
  6387. // WHATWG HTML standard, so each part still parses as a single part
  6388. // with no injected headers. Content types get CR/LF escaped too,
  6389. // while '"' (legal there, e.g. quoted charset) is preserved.
  6390. ASSERT_EQ(4U, received.size());
  6391. EXPECT_EQ("na%22me", received[0].name);
  6392. EXPECT_EQ("quoted name", received[0].content);
  6393. EXPECT_EQ("file", received[1].name);
  6394. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6395. received[1].filename);
  6396. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6397. EXPECT_EQ("injected", received[1].content);
  6398. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6399. EXPECT_EQ("my%22file.txt", received[2].filename);
  6400. EXPECT_EQ("cr lf name", received[2].content);
  6401. EXPECT_EQ("typed", received[3].name);
  6402. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6403. received[3].content_type);
  6404. EXPECT_EQ("typed content", received[3].content);
  6405. });
  6406. auto port = svr.bind_to_any_port("localhost");
  6407. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6408. auto se = detail::scope_exit([&] {
  6409. svr.stop();
  6410. t.join();
  6411. ASSERT_FALSE(svr.is_running());
  6412. });
  6413. svr.wait_until_ready();
  6414. Client cli("localhost", port);
  6415. UploadFormDataItems items = {
  6416. {"na\"me", "quoted name", "", ""},
  6417. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6418. "application/octet-stream"},
  6419. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6420. {"typed", "typed content", "",
  6421. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6422. };
  6423. auto res = cli.Post("/post", items);
  6424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6425. EXPECT_EQ(StatusCode::OK_200, res->status);
  6426. }
  6427. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6428. const UploadFormDataItems items = {
  6429. {"name1", "Content 1", "", ""},
  6430. {"name2", "Content 2", "file2.txt", "text/plain"},
  6431. };
  6432. Server svr;
  6433. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6434. const ContentReader &content_reader) {
  6435. ASSERT_TRUE(req.is_multipart_form_data());
  6436. std::vector<FormData> received;
  6437. content_reader(
  6438. [&](const FormData &file) {
  6439. received.push_back(file);
  6440. return true;
  6441. },
  6442. [&](const char *data, size_t data_length) {
  6443. received.back().content.append(data, data_length);
  6444. return true;
  6445. });
  6446. ASSERT_EQ(2U, received.size());
  6447. EXPECT_EQ("name1", received[0].name);
  6448. EXPECT_EQ("Content 1", received[0].content);
  6449. EXPECT_EQ("name2", received[1].name);
  6450. EXPECT_EQ("Content 2", received[1].content);
  6451. EXPECT_EQ("file2.txt", received[1].filename);
  6452. EXPECT_EQ("text/plain", received[1].content_type);
  6453. });
  6454. auto port = svr.bind_to_any_port("localhost");
  6455. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6456. auto se = detail::scope_exit([&] {
  6457. svr.stop();
  6458. t.join();
  6459. ASSERT_FALSE(svr.is_running());
  6460. });
  6461. svr.wait_until_ready();
  6462. Client cli("localhost", port);
  6463. // Whole-body serialization with a generated boundary
  6464. {
  6465. MultipartFormDataWriter writer;
  6466. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6467. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6468. writer.content_type());
  6469. auto body = writer.serialize(items);
  6470. EXPECT_EQ(body.size(), writer.content_length(items));
  6471. auto res = cli.Post("/post", body, writer.content_type());
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::OK_200, res->status);
  6474. }
  6475. // Per-part framing with a custom boundary via a content provider
  6476. {
  6477. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6478. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6479. MultipartFormDataWriter writer("custom-boundary_123");
  6480. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6481. std::string body;
  6482. for (const auto &item : items) {
  6483. body += writer.item_begin(item);
  6484. body += item.content;
  6485. body += MultipartFormDataWriter::item_end();
  6486. }
  6487. body += writer.finish();
  6488. EXPECT_EQ(body.size(), writer.content_length(items));
  6489. auto res = cli.Post(
  6490. "/post", body.size(),
  6491. [&](size_t offset, size_t length, DataSink &sink) {
  6492. sink.write(body.data() + offset, length);
  6493. return true;
  6494. },
  6495. writer.content_type());
  6496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6497. EXPECT_EQ(StatusCode::OK_200, res->status);
  6498. }
  6499. }
  6500. TEST_F(ServerTest, PostContentReceiverGzip) {
  6501. cli_.set_compress(true);
  6502. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6504. ASSERT_EQ(StatusCode::OK_200, res->status);
  6505. ASSERT_EQ("content", res->body);
  6506. }
  6507. TEST_F(ServerTest, PutContentReceiver) {
  6508. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6510. ASSERT_EQ(StatusCode::OK_200, res->status);
  6511. ASSERT_EQ("content", res->body);
  6512. }
  6513. TEST_F(ServerTest, PatchContentReceiver) {
  6514. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. ASSERT_EQ(StatusCode::OK_200, res->status);
  6517. ASSERT_EQ("content", res->body);
  6518. }
  6519. template <typename ClientType>
  6520. void TestWithHeadersAndContentReceiver(
  6521. ClientType &cli,
  6522. std::function<Result(ClientType &, const std::string &, const Headers &,
  6523. const std::string &, const std::string &,
  6524. ContentReceiver, DownloadProgress)>
  6525. request_func) {
  6526. Headers headers;
  6527. headers.emplace("X-Custom-Header", "test-value");
  6528. std::string received_body;
  6529. auto res = request_func(
  6530. cli, "/content_receiver", headers, "content", "application/json",
  6531. [&](const char *data, size_t data_length) {
  6532. received_body.append(data, data_length);
  6533. return true;
  6534. },
  6535. nullptr);
  6536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6537. EXPECT_EQ(StatusCode::OK_200, res->status);
  6538. EXPECT_EQ("content", received_body);
  6539. }
  6540. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6541. #ifdef CPPHTTPLIB_SSL_ENABLED
  6542. using ClientT = SSLClient;
  6543. #else
  6544. using ClientT = Client;
  6545. #endif
  6546. TestWithHeadersAndContentReceiver<ClientT>(
  6547. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6548. const std::string &body, const std::string &content_type,
  6549. ContentReceiver receiver, DownloadProgress progress) {
  6550. return cli.Post(path, headers, body, content_type, receiver, progress);
  6551. });
  6552. }
  6553. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6554. #ifdef CPPHTTPLIB_SSL_ENABLED
  6555. using ClientT = SSLClient;
  6556. #else
  6557. using ClientT = Client;
  6558. #endif
  6559. TestWithHeadersAndContentReceiver<ClientT>(
  6560. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6561. const std::string &body, const std::string &content_type,
  6562. ContentReceiver receiver, DownloadProgress progress) {
  6563. return cli.Put(path, headers, body, content_type, receiver, progress);
  6564. });
  6565. }
  6566. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6567. #ifdef CPPHTTPLIB_SSL_ENABLED
  6568. using ClientT = SSLClient;
  6569. #else
  6570. using ClientT = Client;
  6571. #endif
  6572. TestWithHeadersAndContentReceiver<ClientT>(
  6573. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6574. const std::string &body, const std::string &content_type,
  6575. ContentReceiver receiver, DownloadProgress progress) {
  6576. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6577. });
  6578. }
  6579. template <typename ClientType>
  6580. void TestWithHeadersAndContentReceiverWithProgress(
  6581. ClientType &cli,
  6582. std::function<Result(ClientType &, const std::string &, const Headers &,
  6583. const std::string &, const std::string &,
  6584. ContentReceiver, DownloadProgress)>
  6585. request_func) {
  6586. Headers headers;
  6587. headers.emplace("X-Test-Header", "progress-test");
  6588. std::string received_body;
  6589. auto progress_called = false;
  6590. auto res = request_func(
  6591. cli, "/content_receiver", headers, "content", "text/plain",
  6592. [&](const char *data, size_t data_length) {
  6593. received_body.append(data, data_length);
  6594. return true;
  6595. },
  6596. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6597. progress_called = true;
  6598. return true;
  6599. });
  6600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6601. EXPECT_EQ(StatusCode::OK_200, res->status);
  6602. EXPECT_EQ("content", received_body);
  6603. EXPECT_TRUE(progress_called);
  6604. }
  6605. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6606. #ifdef CPPHTTPLIB_SSL_ENABLED
  6607. using ClientT = SSLClient;
  6608. #else
  6609. using ClientT = Client;
  6610. #endif
  6611. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6612. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6613. const std::string &body, const std::string &content_type,
  6614. ContentReceiver receiver, DownloadProgress progress) {
  6615. return cli.Post(path, headers, body, content_type, receiver, progress);
  6616. });
  6617. }
  6618. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6619. #ifdef CPPHTTPLIB_SSL_ENABLED
  6620. using ClientT = SSLClient;
  6621. #else
  6622. using ClientT = Client;
  6623. #endif
  6624. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6625. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6626. const std::string &body, const std::string &content_type,
  6627. ContentReceiver receiver, DownloadProgress progress) {
  6628. return cli.Put(path, headers, body, content_type, receiver, progress);
  6629. });
  6630. }
  6631. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6632. #ifdef CPPHTTPLIB_SSL_ENABLED
  6633. using ClientT = SSLClient;
  6634. #else
  6635. using ClientT = Client;
  6636. #endif
  6637. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6638. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6639. const std::string &body, const std::string &content_type,
  6640. ContentReceiver receiver, DownloadProgress progress) {
  6641. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6642. });
  6643. }
  6644. template <typename ClientType>
  6645. void TestWithHeadersAndContentReceiverError(
  6646. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6647. const Headers &, const std::string &,
  6648. const std::string &, ContentReceiver)>
  6649. request_func) {
  6650. Headers headers;
  6651. headers.emplace("X-Error-Test", "true");
  6652. std::string received_body;
  6653. auto receiver_failed = false;
  6654. auto res =
  6655. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6656. [&](const char *data, size_t data_length) {
  6657. received_body.append(data, data_length);
  6658. receiver_failed = true;
  6659. return false;
  6660. });
  6661. ASSERT_FALSE(res);
  6662. EXPECT_TRUE(receiver_failed);
  6663. }
  6664. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6665. #ifdef CPPHTTPLIB_SSL_ENABLED
  6666. using ClientT = SSLClient;
  6667. #else
  6668. using ClientT = Client;
  6669. #endif
  6670. TestWithHeadersAndContentReceiverError<ClientT>(
  6671. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6672. const std::string &body, const std::string &content_type,
  6673. ContentReceiver receiver) {
  6674. return cli.Post(path, headers, body, content_type, receiver);
  6675. });
  6676. }
  6677. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6678. #ifdef CPPHTTPLIB_SSL_ENABLED
  6679. using ClientT = SSLClient;
  6680. #else
  6681. using ClientT = Client;
  6682. #endif
  6683. TestWithHeadersAndContentReceiverError<ClientT>(
  6684. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6685. const std::string &body, const std::string &content_type,
  6686. ContentReceiver receiver) {
  6687. return cli.Put(path, headers, body, content_type, receiver);
  6688. });
  6689. }
  6690. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6691. #ifdef CPPHTTPLIB_SSL_ENABLED
  6692. using ClientT = SSLClient;
  6693. #else
  6694. using ClientT = Client;
  6695. #endif
  6696. TestWithHeadersAndContentReceiverError<ClientT>(
  6697. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6698. const std::string &body, const std::string &content_type,
  6699. ContentReceiver receiver) {
  6700. return cli.Patch(path, headers, body, content_type, receiver);
  6701. });
  6702. }
  6703. TEST_F(ServerTest, PostQueryStringAndBody) {
  6704. auto res =
  6705. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. ASSERT_EQ(StatusCode::OK_200, res->status);
  6708. }
  6709. TEST_F(ServerTest, HTTP2Magic) {
  6710. Request req;
  6711. req.method = "PRI";
  6712. req.path = "*";
  6713. req.body = "SM";
  6714. auto res = std::make_shared<Response>();
  6715. auto error = Error::Success;
  6716. auto ret = cli_.send(req, *res, error);
  6717. ASSERT_TRUE(ret);
  6718. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6719. }
  6720. TEST_F(ServerTest, KeepAlive) {
  6721. auto res = cli_.Get("/hi");
  6722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6723. EXPECT_EQ(StatusCode::OK_200, res->status);
  6724. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6725. EXPECT_EQ("Hello World!", res->body);
  6726. res = cli_.Get("/hi");
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::OK_200, res->status);
  6729. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6730. EXPECT_EQ("Hello World!", res->body);
  6731. res = cli_.Get("/hi");
  6732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6733. EXPECT_EQ(StatusCode::OK_200, res->status);
  6734. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6735. EXPECT_EQ("Hello World!", res->body);
  6736. res = cli_.Get("/not-exist");
  6737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6738. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6739. res = cli_.Post("/empty", "", "text/plain");
  6740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6741. EXPECT_EQ(StatusCode::OK_200, res->status);
  6742. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6743. EXPECT_EQ("empty", res->body);
  6744. EXPECT_EQ("close", res->get_header_value("Connection"));
  6745. res = cli_.Post(
  6746. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6747. "text/plain");
  6748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6749. EXPECT_EQ(StatusCode::OK_200, res->status);
  6750. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6751. EXPECT_EQ("empty", res->body);
  6752. cli_.set_keep_alive(false);
  6753. res = cli_.Get("/last-request");
  6754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6755. EXPECT_EQ(StatusCode::OK_200, res->status);
  6756. EXPECT_EQ("close", res->get_header_value("Connection"));
  6757. }
  6758. TEST_F(ServerTest, TooManyRedirect) {
  6759. cli_.set_follow_location(true);
  6760. auto res = cli_.Get("/redirect/0");
  6761. ASSERT_TRUE(!res);
  6762. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6763. }
  6764. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6765. Request req;
  6766. req.method = "FOOBAR";
  6767. req.path = "/hi";
  6768. cli_.set_keep_alive(true);
  6769. auto res = cli_.send(req);
  6770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6771. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6772. EXPECT_EQ("close", res->get_header_value("Connection"));
  6773. EXPECT_FALSE(cli_.is_socket_open());
  6774. }
  6775. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6776. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6777. TEST_F(ServerTest, Gzip) {
  6778. Headers headers;
  6779. headers.emplace("Accept-Encoding", "gzip, deflate");
  6780. auto res = cli_.Get("/compress", headers);
  6781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6782. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6783. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6784. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6785. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6786. "7890123456789012345678901234567890",
  6787. res->body);
  6788. EXPECT_EQ(StatusCode::OK_200, res->status);
  6789. }
  6790. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6791. Headers headers;
  6792. headers.emplace("Accept-Encoding", "gzip, deflate");
  6793. auto res = cli_.Get("/compress-with-charset", headers);
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6796. EXPECT_EQ("application/json; charset=utf-8",
  6797. res->get_header_value("Content-Type"));
  6798. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6799. "7890123456789012345678901234567890",
  6800. res->body);
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. }
  6803. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6804. Headers headers;
  6805. headers.emplace("Accept-Encoding", "");
  6806. auto res = cli_.Get("/compress", headers);
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6809. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6810. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6811. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6812. "7890123456789012345678901234567890",
  6813. res->body);
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. }
  6816. TEST_F(ServerTest, GzipWithContentReceiver) {
  6817. Headers headers;
  6818. headers.emplace("Accept-Encoding", "gzip, deflate");
  6819. std::string body;
  6820. auto res = cli_.Get("/compress", headers,
  6821. [&](const char *data, uint64_t data_length) {
  6822. EXPECT_EQ(100U, data_length);
  6823. body.append(data, data_length);
  6824. return true;
  6825. });
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6828. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6829. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6830. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6831. "7890123456789012345678901234567890",
  6832. body);
  6833. EXPECT_EQ(StatusCode::OK_200, res->status);
  6834. }
  6835. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6836. Headers headers;
  6837. headers.emplace("Accept-Encoding", "gzip, deflate");
  6838. cli_.set_decompress(false);
  6839. auto res = cli_.Get("/compress", headers);
  6840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6841. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6842. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6843. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6844. EXPECT_EQ(33U, res->body.size());
  6845. EXPECT_EQ(StatusCode::OK_200, res->status);
  6846. }
  6847. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6848. Headers headers;
  6849. headers.emplace("Accept-Encoding", "");
  6850. std::string body;
  6851. auto res = cli_.Get("/compress", headers,
  6852. [&](const char *data, uint64_t data_length) {
  6853. EXPECT_EQ(100U, data_length);
  6854. body.append(data, data_length);
  6855. return true;
  6856. });
  6857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6858. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6859. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6860. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6861. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6862. "7890123456789012345678901234567890",
  6863. body);
  6864. EXPECT_EQ(StatusCode::OK_200, res->status);
  6865. }
  6866. TEST_F(ServerTest, NoGzip) {
  6867. Headers headers;
  6868. headers.emplace("Accept-Encoding", "gzip, deflate");
  6869. auto res = cli_.Get("/nocompress", headers);
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6872. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6873. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6874. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6875. "7890123456789012345678901234567890",
  6876. res->body);
  6877. EXPECT_EQ(StatusCode::OK_200, res->status);
  6878. }
  6879. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6880. Headers headers;
  6881. headers.emplace("Accept-Encoding", "gzip, deflate");
  6882. std::string body;
  6883. auto res = cli_.Get("/nocompress", headers,
  6884. [&](const char *data, uint64_t data_length) {
  6885. EXPECT_EQ(100U, data_length);
  6886. body.append(data, data_length);
  6887. return true;
  6888. });
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6891. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6892. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6893. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6894. "7890123456789012345678901234567890",
  6895. body);
  6896. EXPECT_EQ(StatusCode::OK_200, res->status);
  6897. }
  6898. TEST_F(ServerTest, MultipartFormDataGzip) {
  6899. UploadFormDataItems items = {
  6900. {"key1", "test", "", ""},
  6901. {"key2", "--abcdefg123", "", ""},
  6902. };
  6903. cli_.set_compress(true);
  6904. auto res = cli_.Post("/compress-multipart", items);
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::OK_200, res->status);
  6907. }
  6908. #endif
  6909. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6910. TEST_F(ServerTest, Brotli) {
  6911. Headers headers;
  6912. headers.emplace("Accept-Encoding", "br");
  6913. auto res = cli_.Get("/compress", headers);
  6914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6915. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6916. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6917. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6918. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6919. "7890123456789012345678901234567890",
  6920. res->body);
  6921. EXPECT_EQ(StatusCode::OK_200, res->status);
  6922. }
  6923. #endif
  6924. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6925. TEST_F(ServerTest, Zstd) {
  6926. Headers headers;
  6927. headers.emplace("Accept-Encoding", "zstd");
  6928. auto res = cli_.Get("/compress", headers);
  6929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6930. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6931. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6932. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6933. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6934. "7890123456789012345678901234567890",
  6935. res->body);
  6936. EXPECT_EQ(StatusCode::OK_200, res->status);
  6937. }
  6938. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6939. Headers headers;
  6940. headers.emplace("Accept-Encoding", "");
  6941. auto res = cli_.Get("/compress", headers);
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6944. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6945. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6946. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6947. "7890123456789012345678901234567890",
  6948. res->body);
  6949. EXPECT_EQ(StatusCode::OK_200, res->status);
  6950. }
  6951. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6952. Headers headers;
  6953. headers.emplace("Accept-Encoding", "zstd");
  6954. std::string body;
  6955. auto res = cli_.Get("/compress", headers,
  6956. [&](const char *data, uint64_t data_length) {
  6957. EXPECT_EQ(100U, data_length);
  6958. body.append(data, data_length);
  6959. return true;
  6960. });
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6963. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6964. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6965. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6966. "7890123456789012345678901234567890",
  6967. body);
  6968. EXPECT_EQ(StatusCode::OK_200, res->status);
  6969. }
  6970. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6971. Headers headers;
  6972. headers.emplace("Accept-Encoding", "zstd");
  6973. cli_.set_decompress(false);
  6974. auto res = cli_.Get("/compress", headers);
  6975. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6976. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6977. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6978. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6981. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6982. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6983. EXPECT_EQ(StatusCode::OK_200, res->status);
  6984. ASSERT_EQ(26U, res->body.size());
  6985. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6986. 0);
  6987. }
  6988. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6989. Headers headers;
  6990. headers.emplace("Accept-Encoding", "");
  6991. std::string body;
  6992. auto res = cli_.Get("/compress", headers,
  6993. [&](const char *data, uint64_t data_length) {
  6994. EXPECT_EQ(100U, data_length);
  6995. body.append(data, data_length);
  6996. return true;
  6997. });
  6998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6999. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7000. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7001. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7002. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7003. "7890123456789012345678901234567890",
  7004. body);
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. }
  7007. TEST_F(ServerTest, NoZstd) {
  7008. Headers headers;
  7009. headers.emplace("Accept-Encoding", "zstd");
  7010. auto res = cli_.Get("/nocompress", headers);
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7013. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7014. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7015. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7016. "7890123456789012345678901234567890",
  7017. res->body);
  7018. EXPECT_EQ(StatusCode::OK_200, res->status);
  7019. }
  7020. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7021. Headers headers;
  7022. headers.emplace("Accept-Encoding", "zstd");
  7023. std::string body;
  7024. auto res = cli_.Get("/nocompress", headers,
  7025. [&](const char *data, uint64_t data_length) {
  7026. EXPECT_EQ(100U, data_length);
  7027. body.append(data, data_length);
  7028. return true;
  7029. });
  7030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7031. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7032. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7033. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7034. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7035. "7890123456789012345678901234567890",
  7036. body);
  7037. EXPECT_EQ(StatusCode::OK_200, res->status);
  7038. }
  7039. // TODO: How to enable zstd ??
  7040. TEST_F(ServerTest, MultipartFormDataZstd) {
  7041. UploadFormDataItems items = {
  7042. {"key1", "test", "", ""},
  7043. {"key2", "--abcdefg123", "", ""},
  7044. };
  7045. Headers headers;
  7046. headers.emplace("Accept-Encoding", "zstd");
  7047. cli_.set_compress(true);
  7048. auto res = cli_.Post("/compress-multipart", headers, items);
  7049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7050. EXPECT_EQ(StatusCode::OK_200, res->status);
  7051. }
  7052. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7053. Headers headers;
  7054. headers.emplace("Accept-Encoding", "zstd");
  7055. cli_.set_compress(true);
  7056. auto res = cli_.Put(
  7057. "/put", headers, 3,
  7058. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7059. sink.os << "PUT";
  7060. return true;
  7061. },
  7062. "text/plain");
  7063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7064. EXPECT_EQ(StatusCode::OK_200, res->status);
  7065. EXPECT_EQ("PUT", res->body);
  7066. }
  7067. // Pre-compression logging tests
  7068. TEST_F(ServerTest, PreCompressionLogging) {
  7069. // Test data for compression (matches the actual /compress endpoint content)
  7070. const std::string test_content =
  7071. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7072. "3456789012345678901234567890";
  7073. // Variables to capture logging data
  7074. std::string pre_compression_body;
  7075. std::string pre_compression_content_type;
  7076. std::string pre_compression_content_encoding;
  7077. std::string post_compression_body;
  7078. std::string post_compression_content_type;
  7079. std::string post_compression_content_encoding;
  7080. // Set up pre-compression logger
  7081. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7082. const Response &res) {
  7083. pre_compression_body = res.body;
  7084. pre_compression_content_type = res.get_header_value("Content-Type");
  7085. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7086. });
  7087. // Set up post-compression logger
  7088. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7089. post_compression_body = res.body;
  7090. post_compression_content_type = res.get_header_value("Content-Type");
  7091. post_compression_content_encoding =
  7092. res.get_header_value("Content-Encoding");
  7093. });
  7094. // Test with gzip compression
  7095. Headers headers;
  7096. headers.emplace("Accept-Encoding", "gzip");
  7097. auto res = cli_.Get("/compress", headers);
  7098. // Verify response was compressed
  7099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7100. EXPECT_EQ(StatusCode::OK_200, res->status);
  7101. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7102. // Verify pre-compression logger captured uncompressed content
  7103. EXPECT_EQ(test_content, pre_compression_body);
  7104. EXPECT_EQ("text/plain", pre_compression_content_type);
  7105. EXPECT_TRUE(pre_compression_content_encoding
  7106. .empty()); // No encoding header before compression
  7107. // Verify post-compression logger captured compressed content
  7108. EXPECT_NE(test_content,
  7109. post_compression_body); // Should be different after compression
  7110. EXPECT_EQ("text/plain", post_compression_content_type);
  7111. EXPECT_EQ("gzip", post_compression_content_encoding);
  7112. // Verify compressed content is smaller
  7113. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7114. }
  7115. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7116. const std::string test_content =
  7117. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7118. "3456789012345678901234567890";
  7119. std::string pre_compression_body;
  7120. std::string post_compression_body;
  7121. svr_.set_pre_compression_logger(
  7122. [&](const Request & /*req*/, const Response &res) {
  7123. pre_compression_body = res.body;
  7124. });
  7125. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7126. post_compression_body = res.body;
  7127. });
  7128. Headers headers;
  7129. headers.emplace("Accept-Encoding", "br");
  7130. auto res = cli_.Get("/compress", headers);
  7131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7132. EXPECT_EQ(StatusCode::OK_200, res->status);
  7133. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7134. // Verify pre-compression content is uncompressed
  7135. EXPECT_EQ(test_content, pre_compression_body);
  7136. // Verify post-compression content is compressed
  7137. EXPECT_NE(test_content, post_compression_body);
  7138. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7139. }
  7140. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7141. const std::string test_content =
  7142. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7143. "3456789012345678901234567890";
  7144. std::string pre_compression_body;
  7145. std::string post_compression_body;
  7146. svr_.set_pre_compression_logger(
  7147. [&](const Request & /*req*/, const Response &res) {
  7148. pre_compression_body = res.body;
  7149. });
  7150. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7151. post_compression_body = res.body;
  7152. });
  7153. // Request without compression (use /nocompress endpoint)
  7154. Headers headers;
  7155. auto res = cli_.Get("/nocompress", headers);
  7156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7157. EXPECT_EQ(StatusCode::OK_200, res->status);
  7158. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7159. // Pre-compression logger should not be called when no compression is applied
  7160. EXPECT_TRUE(
  7161. pre_compression_body.empty()); // Pre-compression logger not called
  7162. EXPECT_EQ(
  7163. test_content,
  7164. post_compression_body); // Post-compression logger captures final content
  7165. }
  7166. TEST_F(ServerTest, LoggerSeesContentLength) {
  7167. size_t logged_content_length = 0;
  7168. std::string logged_content_length_header;
  7169. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7170. logged_content_length = res.content_length_;
  7171. logged_content_length_header = res.get_header_value("Content-Length");
  7172. });
  7173. auto res = cli_.Get("/nocompress");
  7174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7175. EXPECT_EQ(StatusCode::OK_200, res->status);
  7176. EXPECT_EQ(res->body.size(), logged_content_length);
  7177. EXPECT_EQ(std::to_string(logged_content_length),
  7178. logged_content_length_header);
  7179. }
  7180. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7181. const std::string test_content =
  7182. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7183. "3456789012345678901234567890";
  7184. std::string pre_compression_body;
  7185. bool pre_logger_called = false;
  7186. // Set only pre-compression logger
  7187. svr_.set_pre_compression_logger(
  7188. [&](const Request & /*req*/, const Response &res) {
  7189. pre_compression_body = res.body;
  7190. pre_logger_called = true;
  7191. });
  7192. Headers headers;
  7193. headers.emplace("Accept-Encoding", "gzip");
  7194. auto res = cli_.Get("/compress", headers);
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::OK_200, res->status);
  7197. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7198. // Verify pre-compression logger was called
  7199. EXPECT_TRUE(pre_logger_called);
  7200. EXPECT_EQ(test_content, pre_compression_body);
  7201. }
  7202. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7203. {
  7204. // Test with Expect: 100-continue header - success case
  7205. // Server returns 100 Continue, client sends body, server returns 200 OK
  7206. Request req;
  7207. req.method = "POST";
  7208. req.path = "/post-large";
  7209. req.set_header("Expect", "100-continue");
  7210. req.body = LARGE_DATA;
  7211. Response res;
  7212. auto error = Error::Success;
  7213. cli_.set_keep_alive(true);
  7214. auto ret = cli_.send(req, res, error);
  7215. EXPECT_TRUE(ret);
  7216. EXPECT_EQ(StatusCode::OK_200, res.status);
  7217. EXPECT_EQ(LARGE_DATA, res.body);
  7218. }
  7219. {
  7220. // Test with Expect: 100-continue header - error case
  7221. // Client should not send the body when server returns an error
  7222. Request req;
  7223. req.method = "POST";
  7224. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7225. req.set_header("Expect", "100-continue");
  7226. req.body = LARGE_DATA;
  7227. Response res;
  7228. auto error = Error::Success;
  7229. auto start = std::chrono::high_resolution_clock::now();
  7230. cli_.set_keep_alive(true);
  7231. auto ret = cli_.send(req, res, error);
  7232. auto end = std::chrono::high_resolution_clock::now();
  7233. auto elapsed =
  7234. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7235. .count();
  7236. // With Expect: 100-continue, request completes successfully but with error
  7237. EXPECT_TRUE(ret);
  7238. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7239. EXPECT_EQ("close", res.get_header_value("Connection"));
  7240. EXPECT_FALSE(cli_.is_socket_open());
  7241. EXPECT_LE(elapsed, 2000);
  7242. }
  7243. {
  7244. // Send an extra GET request to ensure error recovery without hanging
  7245. Request req;
  7246. req.method = "GET";
  7247. req.path = "/hi";
  7248. auto start = std::chrono::high_resolution_clock::now();
  7249. auto res = cli_.send(req);
  7250. auto end = std::chrono::high_resolution_clock::now();
  7251. auto elapsed =
  7252. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7253. .count();
  7254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7255. EXPECT_EQ(StatusCode::OK_200, res->status);
  7256. EXPECT_EQ("Hello World!", res->body);
  7257. EXPECT_LE(elapsed, 500);
  7258. }
  7259. }
  7260. TEST(ZstdDecompressor, ChunkedDecompression) {
  7261. std::string data;
  7262. for (size_t i = 0; i < 32 * 1024; ++i) {
  7263. data.push_back(static_cast<char>('a' + i % 26));
  7264. }
  7265. std::string compressed_data;
  7266. {
  7267. httplib::detail::zstd_compressor compressor;
  7268. bool result = compressor.compress(
  7269. data.data(), data.size(),
  7270. /*last=*/true,
  7271. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7272. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7273. compressed_data_size);
  7274. return true;
  7275. });
  7276. ASSERT_TRUE(result);
  7277. }
  7278. std::string decompressed_data;
  7279. {
  7280. httplib::detail::zstd_decompressor decompressor;
  7281. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7282. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7283. size_t chunk_size = 130;
  7284. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7285. chunk_begin += chunk_size) {
  7286. size_t current_chunk_size =
  7287. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7288. bool result = decompressor.decompress(
  7289. compressed_data.data() + chunk_begin, current_chunk_size,
  7290. [&](const char *decompressed_data_chunk,
  7291. size_t decompressed_data_chunk_size) {
  7292. decompressed_data.insert(decompressed_data.size(),
  7293. decompressed_data_chunk,
  7294. decompressed_data_chunk_size);
  7295. return true;
  7296. });
  7297. ASSERT_TRUE(result);
  7298. }
  7299. }
  7300. ASSERT_EQ(data, decompressed_data);
  7301. }
  7302. TEST(ZstdDecompressor, Decompress) {
  7303. std::string original_text = "Compressed with ZSTD";
  7304. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7305. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7306. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7307. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7308. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7309. std::string decompressed_data;
  7310. {
  7311. httplib::detail::zstd_decompressor decompressor;
  7312. bool result = decompressor.decompress(
  7313. compressed_data.data(), compressed_data.size(),
  7314. [&](const char *decompressed_data_chunk,
  7315. size_t decompressed_data_chunk_size) {
  7316. decompressed_data.insert(decompressed_data.size(),
  7317. decompressed_data_chunk,
  7318. decompressed_data_chunk_size);
  7319. return true;
  7320. });
  7321. ASSERT_TRUE(result);
  7322. }
  7323. ASSERT_EQ(original_text, decompressed_data);
  7324. }
  7325. #endif
  7326. // Sends a raw request to a server listening at HOST:PORT.
  7327. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7328. std::string *resp = nullptr, int port = PORT) {
  7329. auto error = Error::Success;
  7330. auto client_sock = detail::create_client_socket(
  7331. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7332. /*connection_timeout_sec=*/5, 0,
  7333. /*read_timeout_sec=*/5, 0,
  7334. /*write_timeout_sec=*/5, 0, std::string(), error);
  7335. if (client_sock == INVALID_SOCKET) { return false; }
  7336. auto ret = detail::process_client_socket(
  7337. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7338. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7339. if (req.size() !=
  7340. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7341. return false;
  7342. }
  7343. char buf[512];
  7344. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7345. while (line_reader.getline()) {
  7346. if (resp) { *resp += line_reader.ptr(); }
  7347. }
  7348. return true;
  7349. });
  7350. detail::close_socket(client_sock);
  7351. return ret;
  7352. }
  7353. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7354. Server svr;
  7355. std::string header_value;
  7356. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7357. header_value = req.get_header_value("foo");
  7358. res.set_content("ok", "text/plain");
  7359. });
  7360. thread t = thread([&] { svr.listen(HOST, PORT); });
  7361. auto se = detail::scope_exit([&] {
  7362. svr.stop();
  7363. t.join();
  7364. ASSERT_FALSE(svr.is_running());
  7365. });
  7366. svr.wait_until_ready();
  7367. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7368. // like characters are not treated the same - use vertical tab and escape.
  7369. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7370. "foo: \t \v bar \x1B\t \r\n"
  7371. "Connection: close\r\n"
  7372. "\r\n";
  7373. std::string res;
  7374. ASSERT_TRUE(send_request(5, req, &res));
  7375. EXPECT_EQ(header_value, "");
  7376. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7377. }
  7378. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7379. Server svr;
  7380. std::string received;
  7381. svr.Get("/order", [&](const Request &req, Response &res) {
  7382. received = entries_to_string(req.headers);
  7383. res.set_content("ok", "text/plain");
  7384. });
  7385. auto port = svr.bind_to_any_port(HOST);
  7386. thread t = thread([&] { svr.listen_after_bind(); });
  7387. auto se = detail::scope_exit([&] {
  7388. svr.stop();
  7389. t.join();
  7390. ASSERT_FALSE(svr.is_running());
  7391. });
  7392. svr.wait_until_ready();
  7393. const std::string req = "GET /order HTTP/1.1\r\n"
  7394. "X-First: 1\r\n"
  7395. "X-Dup: a\r\n"
  7396. "X-Second: 2\r\n"
  7397. "X-Dup: b\r\n"
  7398. "Connection: close\r\n"
  7399. "\r\n";
  7400. std::string res;
  7401. ASSERT_TRUE(send_request(5, req, &res, port));
  7402. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7403. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7404. }
  7405. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7406. Server svr;
  7407. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7408. res.set_header("Set-Cookie", "first=1");
  7409. res.set_header("X-Between", "y");
  7410. res.set_header("Set-Cookie", "second=2");
  7411. res.set_content("ok", "text/plain");
  7412. });
  7413. auto port = svr.bind_to_any_port(HOST);
  7414. thread t = thread([&] { svr.listen_after_bind(); });
  7415. auto se = detail::scope_exit([&] {
  7416. svr.stop();
  7417. t.join();
  7418. ASSERT_FALSE(svr.is_running());
  7419. });
  7420. svr.wait_until_ready();
  7421. Client cli(HOST, port);
  7422. auto res = cli.Get("/cookies");
  7423. ASSERT_TRUE(res);
  7424. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7425. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7426. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7427. }
  7428. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7429. Server svr;
  7430. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7431. auto i = new int(0);
  7432. res.set_header("Trailer", "X-Safe, X-Reflected");
  7433. res.set_chunked_content_provider(
  7434. "text/plain",
  7435. [i](size_t /*offset*/, DataSink &sink) {
  7436. if (*i == 0) {
  7437. sink.os << "body";
  7438. } else {
  7439. Headers trailer;
  7440. // A valid trailer that must survive.
  7441. trailer.emplace("X-Safe", "safe");
  7442. // Attacker-controlled value carrying CR/LF (response splitting).
  7443. trailer.emplace("X-Reflected",
  7444. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7445. // Attacker-controlled name carrying CR/LF.
  7446. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7447. sink.done_with_trailer(trailer);
  7448. }
  7449. (*i)++;
  7450. return true;
  7451. },
  7452. [i](bool /*success*/) { delete i; });
  7453. });
  7454. thread t = thread([&] { svr.listen(HOST, PORT); });
  7455. auto se = detail::scope_exit([&] {
  7456. svr.stop();
  7457. t.join();
  7458. ASSERT_FALSE(svr.is_running());
  7459. });
  7460. svr.wait_until_ready();
  7461. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7462. "Host: " + HOST +
  7463. "\r\n"
  7464. "Connection: close\r\n"
  7465. "\r\n";
  7466. std::string res;
  7467. ASSERT_TRUE(send_request(5, req, &res));
  7468. // The injected fields must not appear anywhere in the raw response.
  7469. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7470. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7471. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7472. // Invalid trailers are dropped entirely, matching set_header().
  7473. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7474. // The valid trailer still passes through.
  7475. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7476. }
  7477. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7478. Server svr;
  7479. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7480. // res.headers is a public field an application can populate directly,
  7481. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7482. // A valid header that must survive.
  7483. res.headers.emplace("X-Safe", "safe");
  7484. // Attacker-controlled value carrying CR/LF (response splitting).
  7485. res.headers.emplace("X-Reflected",
  7486. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7487. // Attacker-controlled name carrying CR/LF.
  7488. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7489. res.set_content("body", "text/plain");
  7490. });
  7491. thread t = thread([&] { svr.listen(HOST, PORT); });
  7492. auto se = detail::scope_exit([&] {
  7493. svr.stop();
  7494. t.join();
  7495. ASSERT_FALSE(svr.is_running());
  7496. });
  7497. svr.wait_until_ready();
  7498. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7499. "Host: " + HOST +
  7500. "\r\n"
  7501. "Connection: close\r\n"
  7502. "\r\n";
  7503. std::string res;
  7504. ASSERT_TRUE(send_request(5, req, &res));
  7505. // The injected fields must not appear anywhere in the raw response.
  7506. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7507. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7508. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7509. // Invalid headers are dropped entirely, matching set_header().
  7510. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7511. // The valid header still passes through.
  7512. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7513. }
  7514. // Forward declaration: in split builds split.py strips `inline` and moves the
  7515. // definition into httplib.cc, so detail::write_request_line is not visible from
  7516. // the public httplib.h. Re-declaring it here lets the tests link against the
  7517. // symbol in both header-only and split builds.
  7518. namespace httplib {
  7519. namespace detail {
  7520. ssize_t write_request_line(Stream &strm, const std::string &method,
  7521. const std::string &path);
  7522. } // namespace detail
  7523. } // namespace httplib
  7524. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7525. // A well-formed target is written verbatim.
  7526. {
  7527. detail::BufferStream strm;
  7528. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7529. EXPECT_GT(n, 0);
  7530. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7531. }
  7532. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7533. // otherwise it splits the request line and injects a header or a whole
  7534. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7535. // when path encoding is disabled.
  7536. const std::string evil_targets[] = {
  7537. "/a\r\nInjected: pwned",
  7538. "/a\rInjected",
  7539. "/a\nInjected",
  7540. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7541. };
  7542. for (const auto &evil : evil_targets) {
  7543. detail::BufferStream strm;
  7544. auto n = detail::write_request_line(strm, "GET", evil);
  7545. EXPECT_LT(n, 0);
  7546. EXPECT_TRUE(strm.get_buffer().empty());
  7547. }
  7548. }
  7549. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7550. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7551. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7552. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7553. // client must fail cleanly with Error::Write instead of putting a
  7554. // request-line-less, header-injecting request on the wire.
  7555. Server svr;
  7556. svr.Get("/a", [](const Request &, Response &res) {
  7557. res.set_content("ok", "text/plain");
  7558. });
  7559. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7560. auto se = detail::scope_exit([&] {
  7561. svr.stop();
  7562. thread.join();
  7563. ASSERT_FALSE(svr.is_running());
  7564. });
  7565. svr.wait_until_ready();
  7566. {
  7567. Client cli(HOST, PORT);
  7568. cli.set_path_encode(false);
  7569. // The request is rejected before anything is written, so the connection
  7570. // stays silent and the subsequent response read would otherwise block for
  7571. // the full default read timeout. Shorten it -- the assertion is on the
  7572. // error, not the timeout.
  7573. cli.set_read_timeout(1, 0);
  7574. auto res = cli.Get("/a\r\nInjected: pwned");
  7575. EXPECT_FALSE(res);
  7576. EXPECT_EQ(Error::Write, res.error());
  7577. }
  7578. }
  7579. // Sends a raw request and verifies that there isn't a crash or exception.
  7580. static void test_raw_request(const std::string &req,
  7581. std::string *out = nullptr) {
  7582. Server svr;
  7583. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7584. res.set_content("ok", "text/plain");
  7585. });
  7586. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7587. res.set_content("ok", "text/plain");
  7588. });
  7589. svr.Get("/header_field_value_check",
  7590. [&](const Request & /*req*/, Response &res) {
  7591. res.set_content("ok", "text/plain");
  7592. });
  7593. // Server read timeout must be longer than the client read timeout for the
  7594. // bug to reproduce, probably to force the server to process a request
  7595. // without a trailing blank line.
  7596. const time_t client_read_timeout_sec = 1;
  7597. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7598. bool listen_thread_ok = false;
  7599. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7600. auto se = detail::scope_exit([&] {
  7601. svr.stop();
  7602. t.join();
  7603. ASSERT_FALSE(svr.is_running());
  7604. EXPECT_TRUE(listen_thread_ok);
  7605. });
  7606. svr.wait_until_ready();
  7607. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7608. }
  7609. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7610. // A certain header line causes an exception if the header property is parsed
  7611. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7612. test_raw_request(
  7613. "GET /hi HTTP/1.1\r\n"
  7614. " : "
  7615. " "
  7616. " ");
  7617. }
  7618. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7619. // A certain header line causes an exception if the header property *name* is
  7620. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7621. // greedy matcher and requires backtracking when there are a lot of ":"
  7622. // characters.
  7623. // This occurs with libc++ but not libstdc++.
  7624. test_raw_request(
  7625. "GET /hi HTTP/1.1\r\n"
  7626. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7627. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7628. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7629. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7630. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7631. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7632. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7633. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7634. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7635. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7636. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7637. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7638. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7639. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7640. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7641. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7642. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7643. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7644. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7645. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7646. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7647. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7648. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7649. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7650. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7651. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7652. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7653. "&&&%%%");
  7654. }
  7655. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7656. // Make sure this doesn't crash the server.
  7657. // In a previous version of the header line regex, the "\r" rendered the line
  7658. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7659. // a new position where the leading white space ended and the field value
  7660. // began.
  7661. // The crash occurs with libc++ but not libstdc++.
  7662. test_raw_request("GET /hi HTTP/1.1\r\n"
  7663. "a:" +
  7664. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7665. "\r\n"
  7666. "\r\n");
  7667. }
  7668. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7669. std::string out;
  7670. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7671. "Content-Type: text/plain\r\n"
  7672. "Transfer-Encoding: chunked\r\n"
  7673. "\r\n"
  7674. "nothex\r\n",
  7675. &out);
  7676. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7677. }
  7678. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7679. std::string out;
  7680. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7681. "Content-Type: text/plain\r\n"
  7682. "Transfer-Encoding: chunked\r\n"
  7683. "\r\n"
  7684. "3\r\n"
  7685. "xyz\r\n"
  7686. "NaN\r\n",
  7687. &out);
  7688. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7689. }
  7690. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7691. std::string out;
  7692. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7693. "Content-Type: text/plain\r\n"
  7694. "Transfer-Encoding: chunked\r\n"
  7695. "\r\n"
  7696. // Length is too large for 64 bits.
  7697. "1ffffffffffffffff\r\n"
  7698. "xyz\r\n",
  7699. &out);
  7700. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7701. }
  7702. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7703. test_raw_request("GET /hi HTTP/1.1\r\n"
  7704. "Content-Type: text/plain\r\n\r");
  7705. }
  7706. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7707. std::string out;
  7708. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7709. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7710. }
  7711. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7712. Server svr;
  7713. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7714. EXPECT_TRUE(!req.remote_addr.empty());
  7715. });
  7716. thread t = thread([&] { svr.listen(HOST, PORT); });
  7717. auto se = detail::scope_exit([&] {
  7718. svr.stop();
  7719. t.join();
  7720. ASSERT_FALSE(svr.is_running());
  7721. });
  7722. svr.wait_until_ready();
  7723. // Send an invalid request line to trigger Bad Request
  7724. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7725. std::string out;
  7726. ASSERT_TRUE(send_request(5, bad_req, &out));
  7727. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7728. }
  7729. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7730. std::string out;
  7731. std::string request(
  7732. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7733. test_raw_request(request, &out);
  7734. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7735. }
  7736. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7737. std::string out;
  7738. std::string request(
  7739. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7740. test_raw_request(request, &out);
  7741. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7742. }
  7743. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7744. std::string out;
  7745. std::string request(
  7746. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7747. test_raw_request(request, &out);
  7748. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7749. }
  7750. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7751. std::string out;
  7752. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7753. "Test: \r\n\r\n",
  7754. &out);
  7755. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7756. }
  7757. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7758. Server svr;
  7759. std::string x_custom;
  7760. std::string cookie;
  7761. std::string xff;
  7762. std::string x_unicode;
  7763. std::string x_iis;
  7764. svr.Get("/check", [&](const Request &req, Response &res) {
  7765. x_custom = req.get_header_value("X-Custom");
  7766. cookie = req.get_header_value("Cookie");
  7767. xff = req.get_header_value("X-Forwarded-For");
  7768. x_unicode = req.get_header_value("X-Unicode");
  7769. x_iis = req.get_header_value("X-IIS");
  7770. res.set_content("ok", "text/plain");
  7771. });
  7772. thread t = thread([&] { svr.listen(HOST, PORT); });
  7773. auto se = detail::scope_exit([&] {
  7774. svr.stop();
  7775. t.join();
  7776. ASSERT_FALSE(svr.is_running());
  7777. });
  7778. svr.wait_until_ready();
  7779. const std::string req = "GET /check HTTP/1.1\r\n"
  7780. "Host: localhost\r\n"
  7781. "X-Custom: a%0D%0AInjected: b\r\n"
  7782. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7783. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7784. "X-Unicode: %E3%81%82\r\n"
  7785. "X-IIS: %u00E9\r\n"
  7786. "Connection: close\r\n"
  7787. "\r\n";
  7788. std::string res;
  7789. ASSERT_TRUE(send_request(5, req, &res));
  7790. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7791. // Every value must be returned verbatim (wire form), with no decoding.
  7792. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7793. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7794. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7795. EXPECT_EQ("%E3%81%82", x_unicode);
  7796. EXPECT_EQ("%u00E9", x_iis);
  7797. }
  7798. // Applications that previously relied on automatic percent-decoding can
  7799. // reproduce the old behavior by explicitly calling decode_path_component()
  7800. // or, for RFC 3986 conformance, decode_uri_component().
  7801. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7802. Server svr;
  7803. std::string decoded;
  7804. svr.Get("/check", [&](const Request &req, Response &res) {
  7805. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7806. res.set_content("ok", "text/plain");
  7807. });
  7808. thread t = thread([&] { svr.listen(HOST, PORT); });
  7809. auto se = detail::scope_exit([&] {
  7810. svr.stop();
  7811. t.join();
  7812. ASSERT_FALSE(svr.is_running());
  7813. });
  7814. svr.wait_until_ready();
  7815. const std::string req = "GET /check HTTP/1.1\r\n"
  7816. "Host: localhost\r\n"
  7817. "X-Custom: hello%20world\r\n"
  7818. "Connection: close\r\n"
  7819. "\r\n";
  7820. std::string res;
  7821. ASSERT_TRUE(send_request(5, req, &res));
  7822. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7823. EXPECT_EQ("hello world", decoded);
  7824. }
  7825. // Regression test for #2033. Browsers send Referer values that include
  7826. // percent-encoded characters such as %0A inside the URL. Decoding the
  7827. // header value would either trip the post-decode CR/LF/NUL guard (the
  7828. // original bug, returning 400) or, after that guard was relaxed, silently
  7829. // store a literal LF — both unacceptable. The wire form must round-trip.
  7830. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7831. Server svr;
  7832. std::string referer;
  7833. svr.Get("/check", [&](const Request &req, Response &res) {
  7834. referer = req.get_header_value("Referer");
  7835. res.set_content("ok", "text/plain");
  7836. });
  7837. thread t = thread([&] { svr.listen(HOST, PORT); });
  7838. auto se = detail::scope_exit([&] {
  7839. svr.stop();
  7840. t.join();
  7841. ASSERT_FALSE(svr.is_running());
  7842. });
  7843. svr.wait_until_ready();
  7844. const std::string req = "GET /check HTTP/1.1\r\n"
  7845. "Host: localhost\r\n"
  7846. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7847. "Connection: close\r\n"
  7848. "\r\n";
  7849. std::string res;
  7850. ASSERT_TRUE(send_request(5, req, &res));
  7851. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7852. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7853. }
  7854. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7855. Server svr;
  7856. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7857. res.set_header("Cache-Control", "no-cache");
  7858. res.set_chunked_content_provider(
  7859. "text/event-stream", [](size_t offset, DataSink &sink) {
  7860. std::string s = "data:";
  7861. s += std::to_string(offset);
  7862. s += "\n\n";
  7863. auto ret = sink.write(s.data(), s.size());
  7864. EXPECT_TRUE(ret);
  7865. std::this_thread::sleep_for(std::chrono::seconds(1));
  7866. return true;
  7867. });
  7868. });
  7869. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7870. svr.wait_until_ready();
  7871. Client client(HOST, PORT);
  7872. const Headers headers = {{"Accept", "text/event-stream"}};
  7873. auto get_thread = std::thread([&client, &headers]() {
  7874. auto res = client.Get(
  7875. "/events", headers,
  7876. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7877. });
  7878. auto se = detail::scope_exit([&] {
  7879. svr.stop();
  7880. get_thread.join();
  7881. listen_thread.join();
  7882. ASSERT_FALSE(svr.is_running());
  7883. });
  7884. // Give GET time to get a few messages.
  7885. std::this_thread::sleep_for(std::chrono::seconds(2));
  7886. }
  7887. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7888. httplib::Server svr;
  7889. svr.Post("/hi",
  7890. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7891. res.status = StatusCode::OK_200;
  7892. });
  7893. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7894. svr.wait_until_ready();
  7895. Client cli(HOST, PORT);
  7896. auto res = cli.Post("/hi", "data", "text/plain");
  7897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7898. EXPECT_EQ(StatusCode::OK_200, res->status);
  7899. svr.stop();
  7900. thread.join();
  7901. ASSERT_FALSE(svr.is_running());
  7902. res = cli.Post("/hi", "data", "text/plain");
  7903. ASSERT_FALSE(res);
  7904. }
  7905. TEST(ServerStopTest, ListenFailure) {
  7906. Server svr;
  7907. auto t = thread([&]() {
  7908. auto ret = svr.listen("????", PORT);
  7909. EXPECT_FALSE(ret);
  7910. });
  7911. svr.wait_until_ready();
  7912. svr.stop();
  7913. t.join();
  7914. }
  7915. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7916. TEST(ServerStopTest, Decommision) {
  7917. Server svr;
  7918. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7919. for (int i = 0; i < 4; i++) {
  7920. auto is_even = !(i % 2);
  7921. std::thread t{[&] {
  7922. try {
  7923. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7924. if (is_even) {
  7925. throw std::runtime_error("Some thing that happens to go wrong.");
  7926. }
  7927. svr.listen(HOST, PORT);
  7928. } catch (...) { svr.decommission(); }
  7929. }};
  7930. svr.wait_until_ready();
  7931. // Server is up
  7932. {
  7933. Client cli(HOST, PORT);
  7934. auto res = cli.Get("/hi");
  7935. if (is_even) {
  7936. EXPECT_FALSE(res);
  7937. } else {
  7938. EXPECT_TRUE(res);
  7939. EXPECT_EQ("hi...", res->body);
  7940. }
  7941. }
  7942. svr.stop();
  7943. t.join();
  7944. // Server is down...
  7945. {
  7946. Client cli(HOST, PORT);
  7947. auto res = cli.Get("/hi");
  7948. EXPECT_FALSE(res);
  7949. }
  7950. }
  7951. }
  7952. #endif
  7953. // Helper function for string body upload progress tests
  7954. template <typename SetupHandler, typename ClientCall>
  7955. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7956. ClientCall &&client_call,
  7957. const string &body) {
  7958. Server svr;
  7959. setup_handler(svr);
  7960. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7961. auto se = detail::scope_exit([&] {
  7962. svr.stop();
  7963. t.join();
  7964. });
  7965. svr.wait_until_ready();
  7966. Client cli(HOST, PORT);
  7967. vector<uint64_t> progress_values;
  7968. bool progress_called = false;
  7969. auto res =
  7970. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7971. progress_values.push_back(current);
  7972. progress_called = true;
  7973. return true;
  7974. });
  7975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7976. EXPECT_EQ(200, res->status);
  7977. EXPECT_TRUE(progress_called);
  7978. }
  7979. TEST(UploadProgressTest, PostStringBodyBasic) {
  7980. TestStringBodyUploadProgress(
  7981. [](Server &svr) {
  7982. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7983. res.set_content("received", "text/plain");
  7984. });
  7985. },
  7986. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7987. return cli.Post("/test", body, "text/plain", progress_callback);
  7988. },
  7989. "test data for upload progress");
  7990. }
  7991. TEST(UploadProgressTest, PutStringBodyBasic) {
  7992. TestStringBodyUploadProgress(
  7993. [](Server &svr) {
  7994. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7995. res.set_content("put received", "text/plain");
  7996. });
  7997. },
  7998. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7999. return cli.Put("/test", body, "text/plain", progress_callback);
  8000. },
  8001. "put test data for upload progress");
  8002. }
  8003. TEST(UploadProgressTest, PatchStringBodyBasic) {
  8004. TestStringBodyUploadProgress(
  8005. [](Server &svr) {
  8006. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  8007. res.set_content("patch received", "text/plain");
  8008. });
  8009. },
  8010. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8011. return cli.Patch("/test", body, "text/plain", progress_callback);
  8012. },
  8013. "patch test data for upload progress");
  8014. }
  8015. // Helper function for content provider upload progress tests
  8016. template <typename SetupHandler, typename ClientCall>
  8017. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  8018. ClientCall &&client_call) {
  8019. Server svr;
  8020. setup_handler(svr);
  8021. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8022. auto se = detail::scope_exit([&] {
  8023. svr.stop();
  8024. t.join();
  8025. });
  8026. svr.wait_until_ready();
  8027. Client cli(HOST, PORT);
  8028. vector<uint64_t> progress_values;
  8029. auto res =
  8030. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8031. progress_values.push_back(current);
  8032. return true;
  8033. });
  8034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8035. EXPECT_EQ(200, res->status);
  8036. EXPECT_FALSE(progress_values.empty());
  8037. }
  8038. TEST(UploadProgressTest, PostContentProviderProgress) {
  8039. TestContentProviderUploadProgress(
  8040. [](Server &svr) {
  8041. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8042. res.set_content("provider received", "text/plain");
  8043. });
  8044. },
  8045. [](Client &cli, UploadProgress progress_callback) {
  8046. return cli.Post(
  8047. "/test", 10,
  8048. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  8049. sink.os << "test data";
  8050. return true;
  8051. },
  8052. "text/plain", progress_callback);
  8053. });
  8054. }
  8055. // Helper function for multipart upload progress tests
  8056. template <typename SetupHandler, typename ClientCall>
  8057. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  8058. ClientCall &&client_call,
  8059. const string &endpoint) {
  8060. Server svr;
  8061. setup_handler(svr);
  8062. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8063. auto se = detail::scope_exit([&] {
  8064. svr.stop();
  8065. t.join();
  8066. });
  8067. svr.wait_until_ready();
  8068. Client cli(HOST, PORT);
  8069. vector<uint64_t> progress_values;
  8070. UploadFormDataItems items = {
  8071. {"field1", "value1", "", ""},
  8072. {"field2", "longer value for progress tracking test", "", ""},
  8073. {"file1", "file content data for upload progress", "test.txt",
  8074. "text/plain"}};
  8075. auto res = client_call(cli, endpoint, items,
  8076. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8077. progress_values.push_back(current);
  8078. return true;
  8079. });
  8080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8081. EXPECT_EQ(200, res->status);
  8082. EXPECT_FALSE(progress_values.empty());
  8083. }
  8084. TEST(UploadProgressTest, PostMultipartProgress) {
  8085. TestMultipartUploadProgress(
  8086. [](Server &svr) {
  8087. svr.Post("/multipart", [](const Request &req, Response &res) {
  8088. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8089. res.set_content("multipart received", "text/plain");
  8090. });
  8091. },
  8092. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8093. UploadProgress progress_callback) {
  8094. return cli.Post(endpoint, items, progress_callback);
  8095. },
  8096. "/multipart");
  8097. }
  8098. // Helper function for basic download progress tests
  8099. template <typename SetupHandler, typename ClientCall>
  8100. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8101. ClientCall &&client_call, const string &endpoint,
  8102. size_t expected_content_size) {
  8103. Server svr;
  8104. setup_handler(svr);
  8105. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8106. auto se = detail::scope_exit([&] {
  8107. svr.stop();
  8108. t.join();
  8109. });
  8110. svr.wait_until_ready();
  8111. Client cli(HOST, PORT);
  8112. vector<uint64_t> progress_values;
  8113. auto res = client_call(cli, endpoint,
  8114. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8115. progress_values.push_back(current);
  8116. return true;
  8117. });
  8118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8119. EXPECT_EQ(200, res->status);
  8120. EXPECT_FALSE(progress_values.empty());
  8121. EXPECT_EQ(expected_content_size, res->body.size());
  8122. }
  8123. TEST(DownloadProgressTest, GetBasic) {
  8124. TestBasicDownloadProgress(
  8125. [](Server &svr) {
  8126. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8127. string content(1000, 'D');
  8128. res.set_content(content, "text/plain");
  8129. });
  8130. },
  8131. [](Client &cli, const string &endpoint,
  8132. DownloadProgress progress_callback) {
  8133. return cli.Get(endpoint, progress_callback);
  8134. },
  8135. "/download", 1000u);
  8136. }
  8137. // Helper function for content receiver download progress tests
  8138. template <typename SetupHandler, typename ClientCall>
  8139. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8140. ClientCall &&client_call,
  8141. const string &endpoint,
  8142. size_t expected_content_size) {
  8143. Server svr;
  8144. setup_handler(svr);
  8145. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8146. auto se = detail::scope_exit([&] {
  8147. svr.stop();
  8148. t.join();
  8149. });
  8150. svr.wait_until_ready();
  8151. Client cli(HOST, PORT);
  8152. vector<uint64_t> progress_values;
  8153. string received_body;
  8154. auto res = client_call(
  8155. cli, endpoint,
  8156. [&](const char *data, size_t data_length) -> bool {
  8157. received_body.append(data, data_length);
  8158. return true;
  8159. },
  8160. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8161. progress_values.push_back(current);
  8162. return true;
  8163. });
  8164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8165. EXPECT_EQ(200, res->status);
  8166. EXPECT_FALSE(progress_values.empty());
  8167. EXPECT_EQ(expected_content_size, received_body.size());
  8168. EXPECT_TRUE(res->body.empty());
  8169. }
  8170. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8171. TestContentReceiverDownloadProgress(
  8172. [](Server &svr) {
  8173. svr.Get("/download-receiver",
  8174. [](const Request & /*req*/, Response &res) {
  8175. string content(2000, 'R');
  8176. res.set_content(content, "text/plain");
  8177. });
  8178. },
  8179. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8180. DownloadProgress progress_callback) {
  8181. return cli.Get(endpoint, content_receiver, progress_callback);
  8182. },
  8183. "/download-receiver", 2000u);
  8184. }
  8185. TEST(StreamingTest, NoContentLengthStreaming) {
  8186. Server svr;
  8187. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8188. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8189. if (offset < 6) {
  8190. sink.os << (offset < 3 ? "a" : "b");
  8191. } else {
  8192. sink.done();
  8193. }
  8194. return true;
  8195. });
  8196. });
  8197. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8198. auto listen_se = detail::scope_exit([&] {
  8199. svr.stop();
  8200. listen_thread.join();
  8201. ASSERT_FALSE(svr.is_running());
  8202. });
  8203. svr.wait_until_ready();
  8204. Client client(HOST, PORT);
  8205. auto get_thread = std::thread([&client]() {
  8206. std::string s;
  8207. auto res =
  8208. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8209. s += std::string(data, len);
  8210. return true;
  8211. });
  8212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8213. EXPECT_EQ(StatusCode::OK_200, res->status);
  8214. EXPECT_EQ("aaabbb", s);
  8215. });
  8216. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8217. // Give GET time to get a few messages.
  8218. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8219. }
  8220. TEST(MountTest, Unmount) {
  8221. Server svr;
  8222. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8223. auto se = detail::scope_exit([&] {
  8224. svr.stop();
  8225. listen_thread.join();
  8226. ASSERT_FALSE(svr.is_running());
  8227. });
  8228. svr.wait_until_ready();
  8229. Client cli("localhost", PORT);
  8230. svr.set_mount_point("/mount2", "./www2");
  8231. auto res = cli.Get("/");
  8232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8234. res = cli.Get("/mount2/dir/test.html");
  8235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8236. EXPECT_EQ(StatusCode::OK_200, res->status);
  8237. svr.set_mount_point("/", "./www");
  8238. res = cli.Get("/dir/");
  8239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8240. EXPECT_EQ(StatusCode::OK_200, res->status);
  8241. svr.remove_mount_point("/");
  8242. res = cli.Get("/dir/");
  8243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8245. svr.remove_mount_point("/mount2");
  8246. res = cli.Get("/mount2/dir/test.html");
  8247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8248. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8249. }
  8250. TEST(MountTest, PathSegmentBoundary) {
  8251. Server svr;
  8252. svr.set_mount_point("/mount2", "./www2");
  8253. svr.set_mount_point("/", "./www");
  8254. auto port = svr.bind_to_any_port(HOST);
  8255. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8256. auto se = detail::scope_exit([&] {
  8257. svr.stop();
  8258. listen_thread.join();
  8259. ASSERT_FALSE(svr.is_running());
  8260. });
  8261. svr.wait_until_ready();
  8262. Client cli(HOST, port);
  8263. auto res = cli.Get("/mount2/dir/test.html");
  8264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8265. EXPECT_EQ(StatusCode::OK_200, res->status);
  8266. // "/mount2" must not match part-way through a path segment.
  8267. res = cli.Get("/mount2dir/test.html");
  8268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8269. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8270. // A mount point ending in '/' keeps matching every path below it.
  8271. res = cli.Get("/dir/test.html");
  8272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8273. EXPECT_EQ(StatusCode::OK_200, res->status);
  8274. }
  8275. TEST(MountTest, Redicect) {
  8276. Server svr;
  8277. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8278. auto se = detail::scope_exit([&] {
  8279. svr.stop();
  8280. listen_thread.join();
  8281. ASSERT_FALSE(svr.is_running());
  8282. });
  8283. svr.set_mount_point("/", "./www");
  8284. svr.wait_until_ready();
  8285. Client cli("localhost", PORT);
  8286. auto res = cli.Get("/dir/");
  8287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8288. EXPECT_EQ(StatusCode::OK_200, res->status);
  8289. res = cli.Get("/dir");
  8290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8291. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8292. res = cli.Get("/file");
  8293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8294. EXPECT_EQ(StatusCode::OK_200, res->status);
  8295. res = cli.Get("/file/");
  8296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8297. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8298. cli.set_follow_location(true);
  8299. res = cli.Get("/dir");
  8300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8301. EXPECT_EQ(StatusCode::OK_200, res->status);
  8302. }
  8303. TEST(MountTest, MultibytesPathName) {
  8304. Server svr;
  8305. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8306. auto se = detail::scope_exit([&] {
  8307. svr.stop();
  8308. listen_thread.join();
  8309. ASSERT_FALSE(svr.is_running());
  8310. });
  8311. svr.set_mount_point("/", "./www");
  8312. svr.wait_until_ready();
  8313. Client cli("localhost", PORT);
  8314. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8316. EXPECT_EQ(StatusCode::OK_200, res->status);
  8317. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8318. }
  8319. #ifdef _WIN32
  8320. // Issue #2435: mmap::open() must succeed even when another handle holds
  8321. // the file open for writing (e.g. an active log file).
  8322. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8323. const char *path = "mmap_concurrent_writer_test.txt";
  8324. const char *content = "hello";
  8325. {
  8326. std::ofstream f(path, std::ios::binary);
  8327. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8328. }
  8329. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8330. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8331. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8332. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8333. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8334. detail::mmap m(path);
  8335. ASSERT_TRUE(m.is_open());
  8336. EXPECT_EQ(strlen(content), m.size());
  8337. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8338. }
  8339. #endif
  8340. #ifndef _WIN32
  8341. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8342. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8343. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8344. TEST(MmapTest, FailedMappingIsNotOpen) {
  8345. const char *path = "./mmap_failed_mapping_test_dir";
  8346. ASSERT_EQ(0, ::mkdir(path, 0755));
  8347. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8348. detail::mmap m(path);
  8349. EXPECT_FALSE(m.is_open());
  8350. EXPECT_EQ(0U, m.size());
  8351. EXPECT_NE(static_cast<const void *>(m.data()),
  8352. static_cast<const void *>(MAP_FAILED));
  8353. }
  8354. #endif
  8355. TEST(KeepAliveTest, ReadTimeout) {
  8356. Server svr;
  8357. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8358. std::this_thread::sleep_for(std::chrono::seconds(2));
  8359. res.set_content("a", "text/plain");
  8360. });
  8361. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8362. res.set_content("b", "text/plain");
  8363. });
  8364. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8365. auto se = detail::scope_exit([&] {
  8366. svr.stop();
  8367. listen_thread.join();
  8368. ASSERT_FALSE(svr.is_running());
  8369. });
  8370. svr.wait_until_ready();
  8371. Client cli("localhost", PORT);
  8372. cli.set_keep_alive(true);
  8373. cli.set_read_timeout(std::chrono::seconds(1));
  8374. auto resa = cli.Get("/a");
  8375. ASSERT_FALSE(resa);
  8376. EXPECT_EQ(Error::Read, resa.error());
  8377. auto resb = cli.Get("/b");
  8378. ASSERT_TRUE(resb);
  8379. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8380. EXPECT_EQ("b", resb->body);
  8381. }
  8382. TEST(KeepAliveTest, MaxCount) {
  8383. size_t keep_alive_max_count = 3;
  8384. Server svr;
  8385. svr.set_keep_alive_max_count(keep_alive_max_count);
  8386. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8387. res.set_content("Hello World!", "text/plain");
  8388. });
  8389. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8390. auto se = detail::scope_exit([&] {
  8391. svr.stop();
  8392. listen_thread.join();
  8393. ASSERT_FALSE(svr.is_running());
  8394. });
  8395. svr.wait_until_ready();
  8396. Client cli(HOST, PORT);
  8397. cli.set_keep_alive(true);
  8398. for (size_t i = 0; i < 5; i++) {
  8399. auto result = cli.Get("/hi");
  8400. ASSERT_TRUE(result);
  8401. EXPECT_EQ(StatusCode::OK_200, result->status);
  8402. if (i == keep_alive_max_count - 1) {
  8403. EXPECT_EQ("close", result->get_header_value("Connection"));
  8404. } else {
  8405. EXPECT_FALSE(result->has_header("Connection"));
  8406. }
  8407. }
  8408. }
  8409. TEST(KeepAliveTest, Issue1041) {
  8410. Server svr;
  8411. svr.set_keep_alive_timeout(3);
  8412. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8413. res.set_content("Hello World!", "text/plain");
  8414. });
  8415. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8416. auto se = detail::scope_exit([&] {
  8417. svr.stop();
  8418. listen_thread.join();
  8419. ASSERT_FALSE(svr.is_running());
  8420. });
  8421. svr.wait_until_ready();
  8422. Client cli(HOST, PORT);
  8423. cli.set_keep_alive(true);
  8424. auto result = cli.Get("/hi");
  8425. ASSERT_TRUE(result);
  8426. EXPECT_EQ(StatusCode::OK_200, result->status);
  8427. std::this_thread::sleep_for(std::chrono::seconds(5));
  8428. result = cli.Get("/hi");
  8429. ASSERT_TRUE(result);
  8430. EXPECT_EQ(StatusCode::OK_200, result->status);
  8431. }
  8432. TEST(KeepAliveTest, Issue1959) {
  8433. Server svr;
  8434. svr.set_keep_alive_timeout(5);
  8435. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8436. res.set_content("a", "text/plain");
  8437. });
  8438. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8439. auto se = detail::scope_exit([&] {
  8440. if (!svr.is_running()) return;
  8441. svr.stop();
  8442. listen_thread.join();
  8443. ASSERT_FALSE(svr.is_running());
  8444. });
  8445. svr.wait_until_ready();
  8446. Client cli("localhost", PORT);
  8447. cli.set_keep_alive(true);
  8448. using namespace std::chrono;
  8449. auto start = steady_clock::now();
  8450. cli.Get("/a");
  8451. svr.stop();
  8452. listen_thread.join();
  8453. auto end = steady_clock::now();
  8454. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8455. EXPECT_LT(elapsed, 5000);
  8456. }
  8457. #ifdef CPPHTTPLIB_SSL_ENABLED
  8458. TEST(KeepAliveTest, SSLClientReconnection) {
  8459. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8460. ASSERT_TRUE(svr.is_valid());
  8461. svr.set_keep_alive_timeout(1);
  8462. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8463. res.set_content("Hello World!", "text/plain");
  8464. });
  8465. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8466. auto se = detail::scope_exit([&] {
  8467. svr.stop();
  8468. listen_thread.join();
  8469. ASSERT_FALSE(svr.is_running());
  8470. });
  8471. svr.wait_until_ready();
  8472. SSLClient cli(HOST, PORT);
  8473. cli.enable_server_certificate_verification(false);
  8474. cli.set_keep_alive(true);
  8475. auto result = cli.Get("/hi");
  8476. ASSERT_TRUE(result);
  8477. EXPECT_EQ(StatusCode::OK_200, result->status);
  8478. result = cli.Get("/hi");
  8479. ASSERT_TRUE(result);
  8480. EXPECT_EQ(StatusCode::OK_200, result->status);
  8481. std::this_thread::sleep_for(std::chrono::seconds(2));
  8482. // Recoonect
  8483. result = cli.Get("/hi");
  8484. ASSERT_TRUE(result);
  8485. EXPECT_EQ(StatusCode::OK_200, result->status);
  8486. result = cli.Get("/hi");
  8487. ASSERT_TRUE(result);
  8488. EXPECT_EQ(StatusCode::OK_200, result->status);
  8489. }
  8490. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8491. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8492. ASSERT_TRUE(svr.is_valid());
  8493. svr.set_keep_alive_timeout(1);
  8494. std::string content = "reconnect";
  8495. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8496. res.set_content("Hello World!", "text/plain");
  8497. });
  8498. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8499. auto se = detail::scope_exit([&] {
  8500. svr.stop();
  8501. listen_thread.join();
  8502. ASSERT_FALSE(svr.is_running());
  8503. });
  8504. svr.wait_until_ready();
  8505. SSLClient cli(HOST, PORT);
  8506. cli.enable_server_certificate_verification(false);
  8507. cli.set_keep_alive(true);
  8508. auto result = cli.Post(
  8509. "/hi", content.size(),
  8510. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8511. sink.write(content.c_str(), content.size());
  8512. return true;
  8513. },
  8514. "text/plain");
  8515. ASSERT_TRUE(result);
  8516. EXPECT_EQ(200, result->status);
  8517. std::this_thread::sleep_for(std::chrono::seconds(2));
  8518. // Recoonect
  8519. result = cli.Post(
  8520. "/hi", content.size(),
  8521. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8522. sink.write(content.c_str(), content.size());
  8523. return true;
  8524. },
  8525. "text/plain");
  8526. ASSERT_TRUE(result);
  8527. EXPECT_EQ(200, result->status);
  8528. result = cli.Post(
  8529. "/hi", content.size(),
  8530. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8531. sink.write(content.c_str(), content.size());
  8532. return true;
  8533. },
  8534. "text/plain");
  8535. ASSERT_TRUE(result);
  8536. EXPECT_EQ(200, result->status);
  8537. }
  8538. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8539. using namespace httplib::tls;
  8540. {
  8541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8542. ASSERT_TRUE(svr.is_valid());
  8543. svr.Get("/sni", [&](const Request &req, Response &res) {
  8544. std::string expected = req.sni();
  8545. EXPECT_EQ(expected, req.get_param_value("expected"));
  8546. res.set_content("ok", "text/plain");
  8547. });
  8548. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8549. auto se = detail::scope_exit([&] {
  8550. svr.stop();
  8551. listen_thread.join();
  8552. ASSERT_FALSE(svr.is_running());
  8553. });
  8554. svr.wait_until_ready();
  8555. {
  8556. SSLClient cli("localhost", PORT);
  8557. cli.enable_server_certificate_verification(false);
  8558. auto res = cli.Get("/sni?expected=localhost");
  8559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8560. }
  8561. {
  8562. SSLClient cli("::1", PORT);
  8563. cli.enable_server_certificate_verification(false);
  8564. auto res = cli.Get("/sni?expected=");
  8565. // NOTE: This may fail if the server is listening on IPv4 only
  8566. // (e.g., when localhost resolves to 127.0.0.1 only)
  8567. if (res) {
  8568. EXPECT_EQ(StatusCode::OK_200, res->status);
  8569. } else {
  8570. EXPECT_EQ(Error::Connection, res.error());
  8571. }
  8572. }
  8573. }
  8574. }
  8575. #endif
  8576. TEST(ClientProblemDetectionTest, ContentProvider) {
  8577. Server svr;
  8578. size_t content_length = 1024 * 1024;
  8579. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8580. res.set_content_provider(
  8581. content_length, "text/plain",
  8582. [&](size_t offset, size_t length, DataSink &sink) {
  8583. auto out_len = std::min(length, static_cast<size_t>(1024));
  8584. std::string out(out_len, '@');
  8585. sink.write(out.data(), out_len);
  8586. return offset < 4096;
  8587. },
  8588. [](bool success) { ASSERT_FALSE(success); });
  8589. });
  8590. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8591. res.set_content_provider(
  8592. 0, "text/plain",
  8593. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8594. EXPECT_TRUE(false);
  8595. return true;
  8596. },
  8597. [](bool success) { ASSERT_FALSE(success); });
  8598. });
  8599. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8600. auto se = detail::scope_exit([&] {
  8601. svr.stop();
  8602. listen_thread.join();
  8603. ASSERT_FALSE(svr.is_running());
  8604. });
  8605. svr.wait_until_ready();
  8606. Client cli("localhost", PORT);
  8607. {
  8608. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8609. size_t /*data_length*/) { return false; });
  8610. ASSERT_FALSE(res);
  8611. }
  8612. {
  8613. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8614. size_t /*data_length*/) { return false; });
  8615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8616. }
  8617. }
  8618. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8619. Server svr;
  8620. svr.set_error_handler([](Request const &, Response &res) -> void {
  8621. res.set_chunked_content_provider(
  8622. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8623. sink.os << "hello";
  8624. sink.os << "world";
  8625. sink.done();
  8626. return true;
  8627. });
  8628. });
  8629. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8630. auto se = detail::scope_exit([&] {
  8631. svr.stop();
  8632. listen_thread.join();
  8633. ASSERT_FALSE(svr.is_running());
  8634. });
  8635. svr.wait_until_ready();
  8636. Client cli("localhost", PORT);
  8637. auto res = cli.Get("/");
  8638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8639. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8640. EXPECT_EQ("helloworld", res->body);
  8641. }
  8642. TEST(LongPollingTest, ClientCloseDetection) {
  8643. Server svr;
  8644. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8645. res.set_chunked_content_provider(
  8646. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8647. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8648. sink.os << "hello";
  8649. auto count = 10;
  8650. while (count > 0 && sink.is_writable()) {
  8651. this_thread::sleep_for(chrono::milliseconds(10));
  8652. count--;
  8653. }
  8654. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8655. return true;
  8656. });
  8657. });
  8658. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8659. auto se = detail::scope_exit([&] {
  8660. svr.stop();
  8661. listen_thread.join();
  8662. ASSERT_FALSE(svr.is_running());
  8663. });
  8664. svr.wait_until_ready();
  8665. Client cli("localhost", PORT);
  8666. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8667. EXPECT_EQ("hello", string(data, data_length));
  8668. return false; // close the socket immediately.
  8669. });
  8670. ASSERT_FALSE(res);
  8671. }
  8672. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8673. Server svr;
  8674. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8675. res.set_chunked_content_provider(
  8676. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8677. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8678. sink.os << "hello";
  8679. EXPECT_TRUE(sink.os.good());
  8680. // Wait for the client to close the connection
  8681. auto count = 10;
  8682. while (count > 0 && sink.is_writable()) {
  8683. this_thread::sleep_for(chrono::milliseconds(10));
  8684. count--;
  8685. }
  8686. // After client disconnect, write repeatedly until the socket
  8687. // write actually fails (small writes may be absorbed by the
  8688. // kernel buffer)
  8689. std::string chunk(1024, 'x');
  8690. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8691. sink.os << chunk;
  8692. }
  8693. EXPECT_TRUE(sink.os.fail());
  8694. return true;
  8695. });
  8696. });
  8697. auto port = svr.bind_to_any_port("localhost");
  8698. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8699. auto se = detail::scope_exit([&] {
  8700. svr.stop();
  8701. listen_thread.join();
  8702. ASSERT_FALSE(svr.is_running());
  8703. });
  8704. svr.wait_until_ready();
  8705. Client cli("localhost", port);
  8706. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8707. EXPECT_EQ("hello", string(data, data_length));
  8708. return false; // close the socket immediately.
  8709. });
  8710. ASSERT_FALSE(res);
  8711. }
  8712. TEST(GetWithParametersTest, GetWithParameters) {
  8713. Server svr;
  8714. svr.Get("/", [&](const Request &req, Response &) {
  8715. EXPECT_EQ("world", req.get_param_value("hello"));
  8716. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8717. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8718. });
  8719. svr.Get("/params", [&](const Request &req, Response &) {
  8720. EXPECT_EQ("world", req.get_param_value("hello"));
  8721. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8722. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8723. });
  8724. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8725. EXPECT_EQ("resource-id", req.matches[1]);
  8726. EXPECT_EQ("foo", req.get_param_value("param1"));
  8727. EXPECT_EQ("bar", req.get_param_value("param2"));
  8728. });
  8729. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8730. EXPECT_EQ("user-id", req.path_params.at("id"));
  8731. EXPECT_EQ("foo", req.get_param_value("param1"));
  8732. EXPECT_EQ("bar", req.get_param_value("param2"));
  8733. });
  8734. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8735. auto se = detail::scope_exit([&] {
  8736. svr.stop();
  8737. listen_thread.join();
  8738. ASSERT_FALSE(svr.is_running());
  8739. });
  8740. svr.wait_until_ready();
  8741. {
  8742. Client cli(HOST, PORT);
  8743. Params params;
  8744. params.emplace("hello", "world");
  8745. params.emplace("hello2", "world2");
  8746. params.emplace("hello3", "world3");
  8747. auto res = cli.Get("/", params, Headers{});
  8748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8749. EXPECT_EQ(StatusCode::OK_200, res->status);
  8750. }
  8751. {
  8752. Client cli(HOST, PORT);
  8753. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8755. EXPECT_EQ(StatusCode::OK_200, res->status);
  8756. }
  8757. {
  8758. Client cli(HOST, PORT);
  8759. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8761. EXPECT_EQ(StatusCode::OK_200, res->status);
  8762. }
  8763. {
  8764. Client cli(HOST, PORT);
  8765. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8767. EXPECT_EQ(StatusCode::OK_200, res->status);
  8768. }
  8769. }
  8770. TEST(GetWithParametersTest, GetWithParameters2) {
  8771. Server svr;
  8772. svr.Get("/", [&](const Request &req, Response &res) {
  8773. auto text = req.get_param_value("hello");
  8774. res.set_content(text, "text/plain");
  8775. });
  8776. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8777. auto se = detail::scope_exit([&] {
  8778. svr.stop();
  8779. listen_thread.join();
  8780. ASSERT_FALSE(svr.is_running());
  8781. });
  8782. svr.wait_until_ready();
  8783. Client cli("localhost", PORT);
  8784. Params params;
  8785. params.emplace("hello", "world");
  8786. std::string body;
  8787. auto res = cli.Get("/", params, Headers{},
  8788. [&](const char *data, size_t data_length) {
  8789. body.append(data, data_length);
  8790. return true;
  8791. });
  8792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8793. EXPECT_EQ(StatusCode::OK_200, res->status);
  8794. EXPECT_EQ("world", body);
  8795. }
  8796. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8797. Server svr;
  8798. svr.Get("/search", [&](const Request &req, Response &res) {
  8799. auto q = req.get_param_value("q");
  8800. res.set_content(q, "text/plain");
  8801. });
  8802. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8803. auto se = detail::scope_exit([&] {
  8804. svr.stop();
  8805. listen_thread.join();
  8806. ASSERT_FALSE(svr.is_running());
  8807. });
  8808. svr.wait_until_ready();
  8809. Client cli("localhost", PORT);
  8810. // Verify that Get(path, params) works without requiring Headers argument
  8811. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8813. EXPECT_EQ(StatusCode::OK_200, res->status);
  8814. EXPECT_EQ("cpp-httplib", res->body);
  8815. }
  8816. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8817. auto host = "httpbingo.org";
  8818. auto path = std::string{"/range/32"};
  8819. #ifdef CPPHTTPLIB_SSL_ENABLED
  8820. SSLClient cli(host);
  8821. #else
  8822. Client cli(host);
  8823. #endif
  8824. cli.set_default_headers({make_range_header({{1, 10}})});
  8825. cli.set_connection_timeout(5);
  8826. {
  8827. auto res = cli.Get(path);
  8828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8829. EXPECT_EQ("bcdefghijk", res->body);
  8830. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8831. }
  8832. {
  8833. auto res = cli.Get(path);
  8834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8835. EXPECT_EQ("bcdefghijk", res->body);
  8836. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8837. }
  8838. }
  8839. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8840. Server svr;
  8841. svr.set_default_headers({{"Hello", "World"}});
  8842. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8843. res.set_content("ok", "text/plain");
  8844. });
  8845. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8846. auto se = detail::scope_exit([&] {
  8847. svr.stop();
  8848. listen_thread.join();
  8849. ASSERT_FALSE(svr.is_running());
  8850. });
  8851. svr.wait_until_ready();
  8852. Client cli("localhost", PORT);
  8853. auto res = cli.Get("/");
  8854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8855. EXPECT_EQ(StatusCode::OK_200, res->status);
  8856. EXPECT_EQ("ok", res->body);
  8857. EXPECT_EQ("World", res->get_header_value("Hello"));
  8858. }
  8859. #ifdef CPPHTTPLIB_SSL_ENABLED
  8860. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8862. ASSERT_TRUE(svr.is_valid());
  8863. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8864. std::this_thread::sleep_for(std::chrono::seconds(2));
  8865. res.set_content("a", "text/plain");
  8866. });
  8867. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8868. res.set_content("b", "text/plain");
  8869. });
  8870. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8871. auto se = detail::scope_exit([&] {
  8872. svr.stop();
  8873. listen_thread.join();
  8874. ASSERT_FALSE(svr.is_running());
  8875. });
  8876. svr.wait_until_ready();
  8877. SSLClient cli("localhost", PORT);
  8878. cli.enable_server_certificate_verification(false);
  8879. cli.set_keep_alive(true);
  8880. cli.set_read_timeout(std::chrono::seconds(1));
  8881. auto resa = cli.Get("/a");
  8882. ASSERT_TRUE(!resa);
  8883. EXPECT_EQ(Error::Read, resa.error());
  8884. auto resb = cli.Get("/b");
  8885. ASSERT_TRUE(resb);
  8886. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8887. EXPECT_EQ("b", resb->body);
  8888. }
  8889. #endif
  8890. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8891. protected:
  8892. ServerTestWithAI_PASSIVE()
  8893. : cli_(HOST, PORT)
  8894. #ifdef CPPHTTPLIB_SSL_ENABLED
  8895. ,
  8896. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8897. #endif
  8898. {
  8899. #ifdef CPPHTTPLIB_SSL_ENABLED
  8900. cli_.enable_server_certificate_verification(false);
  8901. #endif
  8902. }
  8903. virtual void SetUp() {
  8904. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8905. res.set_content("Hello World!", "text/plain");
  8906. });
  8907. t_ = thread(
  8908. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8909. svr_.wait_until_ready();
  8910. }
  8911. virtual void TearDown() {
  8912. svr_.stop();
  8913. t_.join();
  8914. }
  8915. #ifdef CPPHTTPLIB_SSL_ENABLED
  8916. SSLClient cli_;
  8917. SSLServer svr_;
  8918. #else
  8919. Client cli_;
  8920. Server svr_;
  8921. #endif
  8922. thread t_;
  8923. };
  8924. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8925. auto res = cli_.Get("/hi");
  8926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8927. EXPECT_EQ(StatusCode::OK_200, res->status);
  8928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8929. EXPECT_EQ("Hello World!", res->body);
  8930. }
  8931. class ServerUpDownTest : public ::testing::Test {
  8932. protected:
  8933. ServerUpDownTest() : cli_(HOST, PORT) {}
  8934. virtual void SetUp() {
  8935. t_ = thread([&]() {
  8936. svr_.bind_to_any_port(HOST);
  8937. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8938. ASSERT_TRUE(svr_.listen_after_bind());
  8939. });
  8940. svr_.wait_until_ready();
  8941. }
  8942. virtual void TearDown() {
  8943. svr_.stop();
  8944. t_.join();
  8945. }
  8946. Client cli_;
  8947. Server svr_;
  8948. thread t_;
  8949. };
  8950. TEST_F(ServerUpDownTest, QuickStartStop) {
  8951. // Should not crash, especially when run with
  8952. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8953. }
  8954. class PayloadMaxLengthTest : public ::testing::Test {
  8955. protected:
  8956. PayloadMaxLengthTest()
  8957. : cli_(HOST, PORT)
  8958. #ifdef CPPHTTPLIB_SSL_ENABLED
  8959. ,
  8960. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8961. #endif
  8962. {
  8963. #ifdef CPPHTTPLIB_SSL_ENABLED
  8964. cli_.enable_server_certificate_verification(false);
  8965. #endif
  8966. }
  8967. virtual void SetUp() {
  8968. svr_.set_payload_max_length(8);
  8969. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8970. res.set_content("test", "text/plain");
  8971. });
  8972. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8973. svr_.wait_until_ready();
  8974. }
  8975. virtual void TearDown() {
  8976. svr_.stop();
  8977. t_.join();
  8978. }
  8979. #ifdef CPPHTTPLIB_SSL_ENABLED
  8980. SSLClient cli_;
  8981. SSLServer svr_;
  8982. #else
  8983. Client cli_;
  8984. Server svr_;
  8985. #endif
  8986. thread t_;
  8987. };
  8988. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8989. auto res = cli_.Post("/test", "123456789", "text/plain");
  8990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8991. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8992. res = cli_.Post("/test", "12345678", "text/plain");
  8993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8994. EXPECT_EQ(StatusCode::OK_200, res->status);
  8995. }
  8996. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8997. // Test chunked encoding with payload exceeding the 8-byte limit
  8998. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8999. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  9000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9001. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9002. }
  9003. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  9004. // Test chunked encoding with payload within the 8-byte limit
  9005. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  9006. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  9007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9008. EXPECT_EQ(StatusCode::OK_200, res->status);
  9009. }
  9010. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  9011. // Test using send_request to send chunked data exceeding payload limit
  9012. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  9013. "Host: " +
  9014. std::string(HOST) + ":" + std::to_string(PORT) +
  9015. "\r\n"
  9016. "Transfer-Encoding: chunked\r\n"
  9017. "Connection: close\r\n"
  9018. "\r\n"
  9019. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  9020. "0123456789\r\n"
  9021. "0\r\n" // End chunk
  9022. "\r\n";
  9023. std::string response;
  9024. bool result = send_request(1, chunked_request, &response);
  9025. if (!result) {
  9026. // If send_request fails, it might be because the server closed the
  9027. // connection due to payload limit enforcement, which is acceptable
  9028. SUCCEED()
  9029. << "Server rejected oversized chunked request (connection closed)";
  9030. } else {
  9031. // If we got a response, check if it's an error response or connection was
  9032. // closed early Short response length indicates connection was closed due to
  9033. // payload limit
  9034. if (response.length() <= 10) {
  9035. SUCCEED() << "Server closed connection for oversized chunked request";
  9036. } else {
  9037. // Check for error status codes
  9038. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9039. response.find("Payload Too Large") != std::string::npos ||
  9040. response.find("400") != std::string::npos);
  9041. }
  9042. }
  9043. }
  9044. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  9045. // Test request without Content-Length header exceeding payload limit
  9046. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9047. "Host: " +
  9048. std::string(HOST) + ":" +
  9049. std::to_string(PORT) +
  9050. "\r\n"
  9051. "Connection: close\r\n"
  9052. "\r\n";
  9053. // Add payload exceeding the 8-byte limit
  9054. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  9055. request_without_content_length += large_payload;
  9056. std::string response;
  9057. bool result = send_request(1, request_without_content_length, &response);
  9058. if (!result) {
  9059. // If send_request fails, server likely closed connection due to payload
  9060. // limit
  9061. SUCCEED() << "Server rejected oversized request without Content-Length "
  9062. "(connection closed)";
  9063. } else {
  9064. // Check if server responded with error or closed connection early
  9065. if (response.length() <= 10) {
  9066. SUCCEED() << "Server closed connection for oversized request without "
  9067. "Content-Length";
  9068. } else {
  9069. // Check for error status codes
  9070. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9071. response.find("Payload Too Large") != std::string::npos ||
  9072. response.find("400") != std::string::npos);
  9073. }
  9074. }
  9075. }
  9076. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  9077. // Test request without Content-Length header within payload limit
  9078. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9079. "Host: " +
  9080. std::string(HOST) + ":" +
  9081. std::to_string(PORT) +
  9082. "\r\n"
  9083. "Connection: close\r\n"
  9084. "\r\n";
  9085. // Add payload within the 8-byte limit
  9086. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9087. request_without_content_length += small_payload;
  9088. std::string response;
  9089. bool result = send_request(1, request_without_content_length, &response);
  9090. // For requests without Content-Length, the server may have different behavior
  9091. // The key is that it should not reject due to payload limit for small
  9092. // payloads
  9093. if (result) {
  9094. // Check for any HTTP response (success or error, but not connection closed)
  9095. if (response.length() > 10) {
  9096. SUCCEED()
  9097. << "Server processed request without Content-Length within limit";
  9098. } else {
  9099. // Short response might indicate connection closed, which is acceptable
  9100. SUCCEED() << "Server closed connection for request without "
  9101. "Content-Length (acceptable behavior)";
  9102. }
  9103. } else {
  9104. // Connection failure might be due to protocol requirements
  9105. SUCCEED() << "Connection issue with request without Content-Length "
  9106. "(environment-specific)";
  9107. }
  9108. }
  9109. class LargePayloadMaxLengthTest : public ::testing::Test {
  9110. protected:
  9111. LargePayloadMaxLengthTest()
  9112. : cli_(HOST, PORT)
  9113. #ifdef CPPHTTPLIB_SSL_ENABLED
  9114. ,
  9115. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9116. #endif
  9117. {
  9118. #ifdef CPPHTTPLIB_SSL_ENABLED
  9119. cli_.enable_server_certificate_verification(false);
  9120. #endif
  9121. }
  9122. virtual void SetUp() {
  9123. // Set 10MB payload limit
  9124. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9125. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9126. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9127. res.set_content("Large payload test", "text/plain");
  9128. });
  9129. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9130. svr_.wait_until_ready();
  9131. }
  9132. virtual void TearDown() {
  9133. svr_.stop();
  9134. t_.join();
  9135. }
  9136. #ifdef CPPHTTPLIB_SSL_ENABLED
  9137. SSLClient cli_;
  9138. SSLServer svr_;
  9139. #else
  9140. Client cli_;
  9141. Server svr_;
  9142. #endif
  9143. thread t_;
  9144. };
  9145. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9146. // Test chunked encoding with payload within 10MB limit
  9147. std::string medium_payload(5 * 1024 * 1024,
  9148. 'A'); // 5MB payload, within 10MB limit
  9149. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9151. EXPECT_EQ(StatusCode::OK_200, res->status);
  9152. }
  9153. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9154. // Test chunked encoding with payload exceeding 10MB limit
  9155. std::string large_payload(12 * 1024 * 1024,
  9156. 'B'); // 12MB payload, exceeds 10MB limit
  9157. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9158. // Server may either return 413 or close the connection
  9159. if (res) {
  9160. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9161. } else {
  9162. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9163. }
  9164. }
  9165. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9166. // Test request without Content-Length header within 10MB limit
  9167. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9168. "Host: " +
  9169. std::string(HOST) + ":" +
  9170. std::to_string(PORT) +
  9171. "\r\n"
  9172. "Connection: close\r\n"
  9173. "\r\n";
  9174. // Add 1MB payload (within 10MB limit)
  9175. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9176. request_without_content_length += medium_payload;
  9177. std::string response;
  9178. bool result = send_request(5, request_without_content_length, &response);
  9179. if (result) {
  9180. // Should get a proper HTTP response for payloads within limit
  9181. if (response.length() > 10) {
  9182. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9183. "10MB limit";
  9184. } else {
  9185. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9186. "Content-Length)";
  9187. }
  9188. } else {
  9189. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9190. }
  9191. }
  9192. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9193. // Test request without Content-Length header exceeding 10MB limit
  9194. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9195. "Host: " +
  9196. std::string(HOST) + ":" +
  9197. std::to_string(PORT) +
  9198. "\r\n"
  9199. "Connection: close\r\n"
  9200. "\r\n";
  9201. // Add 12MB payload (exceeds 10MB limit)
  9202. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9203. request_without_content_length += large_payload;
  9204. std::string response;
  9205. bool result = send_request(10, request_without_content_length, &response);
  9206. if (!result) {
  9207. // Server should close connection due to payload limit
  9208. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9209. "(connection closed)";
  9210. } else {
  9211. // Check for error response
  9212. if (response.length() <= 10) {
  9213. SUCCEED()
  9214. << "Server closed connection for 12MB request exceeding 10MB limit";
  9215. } else {
  9216. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9217. response.find("Payload Too Large") != std::string::npos ||
  9218. response.find("400") != std::string::npos);
  9219. }
  9220. }
  9221. }
  9222. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9223. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9224. // path.
  9225. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9226. Server svr;
  9227. const size_t LIMIT = 64 * 1024; // 64KB
  9228. svr.set_payload_max_length(LIMIT);
  9229. size_t total = 0;
  9230. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9231. const ContentReader &content_reader) {
  9232. content_reader([&](const char * /*data*/, size_t len) {
  9233. total += len;
  9234. return true;
  9235. });
  9236. res.status = 200;
  9237. res.set_content("stream_ok", "text/plain");
  9238. });
  9239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9240. auto se = detail::scope_exit([&] {
  9241. svr.stop();
  9242. thread.join();
  9243. ASSERT_FALSE(svr.is_running());
  9244. });
  9245. svr.wait_until_ready();
  9246. // Prepare 256KB raw data and gzip-compress it
  9247. std::string raw(256 * 1024, 'A');
  9248. std::string gz;
  9249. {
  9250. z_stream zs{};
  9251. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9252. Z_DEFAULT_STRATEGY);
  9253. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9254. zs.avail_in = static_cast<uInt>(raw.size());
  9255. char outbuf[4096];
  9256. int ret;
  9257. do {
  9258. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9259. zs.avail_out = sizeof(outbuf);
  9260. ret = deflate(&zs, Z_FINISH);
  9261. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9262. } while (ret != Z_STREAM_END);
  9263. deflateEnd(&zs);
  9264. }
  9265. Client cli(HOST, PORT);
  9266. cli.set_connection_timeout(std::chrono::seconds(5));
  9267. Headers headers = {{"Content-Encoding", "gzip"}};
  9268. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9269. "application/octet-stream");
  9270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9271. // Server must reject oversized decompressed payloads with 413.
  9272. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9273. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9274. EXPECT_LE(total, LIMIT);
  9275. }
  9276. #ifndef CPPHTTPLIB_SSL_ENABLED
  9277. // For a request with neither Content-Length nor Transfer-Encoding, the
  9278. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9279. // compressed wire bytes straight to the ContentReader without ever routing
  9280. // them through the decompressor, so payload_max_length_ only bounded the
  9281. // compressed size on the wire, not the decompressed size.
  9282. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9283. Server svr;
  9284. const size_t LIMIT = 64 * 1024; // 64KB
  9285. svr.set_payload_max_length(LIMIT);
  9286. size_t total = 0;
  9287. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9288. const ContentReader &content_reader) {
  9289. content_reader([&](const char * /*data*/, size_t len) {
  9290. total += len;
  9291. return true;
  9292. });
  9293. res.status = 200;
  9294. res.set_content("stream_ok", "text/plain");
  9295. });
  9296. auto port = svr.bind_to_any_port(HOST);
  9297. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9298. auto se = detail::scope_exit([&] {
  9299. svr.stop();
  9300. thread.join();
  9301. ASSERT_FALSE(svr.is_running());
  9302. });
  9303. svr.wait_until_ready();
  9304. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9305. // StreamingGzipDecompression test above.
  9306. std::string raw(256 * 1024, 'A');
  9307. std::string gz;
  9308. {
  9309. httplib::detail::gzip_compressor compressor;
  9310. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9311. [&](const char *chunk, size_t len) {
  9312. gz.append(chunk, len);
  9313. return true;
  9314. });
  9315. ASSERT_TRUE(result);
  9316. }
  9317. // Send the gzip body over raw TCP with neither Content-Length nor
  9318. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  9319. // kicks in.
  9320. std::string req = "POST /stream HTTP/1.1\r\n"
  9321. "Host: " +
  9322. std::string(HOST) + ":" + std::to_string(port) +
  9323. "\r\n"
  9324. "Content-Encoding: gzip\r\n"
  9325. "Connection: close\r\n"
  9326. "\r\n" +
  9327. gz;
  9328. std::string response;
  9329. ASSERT_TRUE(send_request(5, req, &response, port));
  9330. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9331. EXPECT_LE(total, LIMIT);
  9332. }
  9333. #endif
  9334. #endif
  9335. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9336. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9337. // the payload must be passed through untouched instead of being rejected.
  9338. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9339. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9340. Server svr;
  9341. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9342. res.set_content(body, "image/jpeg");
  9343. res.set_header("Content-Encoding", "UTF-8");
  9344. });
  9345. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9346. res.set_content(body, "image/jpeg");
  9347. res.set_header("Content-Encoding", "identity");
  9348. });
  9349. svr.Post("/echo", [](const Request &req, Response &res) {
  9350. res.set_content(req.body, "image/jpeg");
  9351. });
  9352. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9353. auto se = detail::scope_exit([&] {
  9354. svr.stop();
  9355. t.join();
  9356. ASSERT_FALSE(svr.is_running());
  9357. });
  9358. svr.wait_until_ready();
  9359. Client cli(HOST, PORT);
  9360. {
  9361. auto res = cli.Get("/image");
  9362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9363. EXPECT_EQ(StatusCode::OK_200, res->status);
  9364. EXPECT_EQ(body, res->body);
  9365. }
  9366. {
  9367. auto res = cli.Get("/identity");
  9368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9369. EXPECT_EQ(StatusCode::OK_200, res->status);
  9370. EXPECT_EQ(body, res->body);
  9371. }
  9372. {
  9373. // The same applies to a request body reaching the server.
  9374. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9375. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9377. EXPECT_EQ(StatusCode::OK_200, res->status);
  9378. EXPECT_EQ(body, res->body);
  9379. }
  9380. }
  9381. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9382. // gzip-encoded response even when the build has no zlib support.
  9383. static const char GZIPPED_HELLO_WORLD[] = {
  9384. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9385. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9386. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9387. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9388. // A content coding is a whole token, not something the field value merely
  9389. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  9390. // as "fibre" look like Brotli, and turned a multi-coding value like
  9391. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  9392. // it was never meant to see.
  9393. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  9394. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9395. Server svr;
  9396. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  9397. res.set_content(body, "image/jpeg");
  9398. res.set_header("Content-Encoding", "fibre");
  9399. });
  9400. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  9401. res.set_content(body, "image/jpeg");
  9402. res.set_header("Content-Encoding", "gzip, br");
  9403. });
  9404. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  9405. res.set_content(body, "image/jpeg");
  9406. res.set_header("Content-Encoding", "x-zstd-ish");
  9407. });
  9408. auto port = svr.bind_to_any_port(HOST);
  9409. thread t = thread([&]() { svr.listen_after_bind(); });
  9410. auto se = detail::scope_exit([&] {
  9411. svr.stop();
  9412. t.join();
  9413. ASSERT_FALSE(svr.is_running());
  9414. });
  9415. svr.wait_until_ready();
  9416. Client cli(HOST, port);
  9417. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  9418. auto res = cli.Get(path);
  9419. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9420. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9421. // Not a coding we recognize, so the payload comes back untouched
  9422. EXPECT_EQ(body, res->body) << path;
  9423. }
  9424. }
  9425. // A content coding cpp-httplib recognizes but was not built with must be
  9426. // reported as such. Handing the still-compressed payload back to the caller
  9427. // would silently corrupt it.
  9428. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9429. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9430. Server svr;
  9431. // "image/jpeg" keeps the server from applying a content coding of its own,
  9432. // so the hand-crafted Content-Encoding below survives.
  9433. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9434. res.set_content(gzipped, "image/jpeg");
  9435. res.set_header("Content-Encoding", "gzip");
  9436. });
  9437. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9438. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9439. res.set_content(gzipped, "image/jpeg");
  9440. res.set_header("Content-Encoding", "GZIP");
  9441. });
  9442. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9443. auto se = detail::scope_exit([&] {
  9444. svr.stop();
  9445. t.join();
  9446. ASSERT_FALSE(svr.is_running());
  9447. });
  9448. svr.wait_until_ready();
  9449. Client cli(HOST, PORT);
  9450. {
  9451. auto res = cli.Get("/gzipped");
  9452. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9454. EXPECT_EQ("Hello World!", res->body);
  9455. #else
  9456. ASSERT_FALSE(res);
  9457. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9458. #endif
  9459. }
  9460. {
  9461. // open_stream() must behave the same way.
  9462. auto handle = cli.open_stream("GET", "/gzipped");
  9463. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9464. ASSERT_TRUE(handle.is_valid());
  9465. std::string received;
  9466. char buf[256];
  9467. ssize_t n;
  9468. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9469. received.append(buf, static_cast<size_t>(n));
  9470. }
  9471. EXPECT_EQ("Hello World!", received);
  9472. #else
  9473. EXPECT_FALSE(handle.is_valid());
  9474. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9475. #endif
  9476. }
  9477. {
  9478. // A differently-cased coding must not be mistaken for an unknown one, or
  9479. // the body would be handed back still compressed.
  9480. auto res = cli.Get("/gzipped-uppercase");
  9481. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9483. EXPECT_EQ("Hello World!", res->body);
  9484. #else
  9485. ASSERT_FALSE(res);
  9486. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9487. #endif
  9488. }
  9489. }
  9490. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  9491. // the same message as the comma-joined one, so both have to be read the same
  9492. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  9493. // single gzip coding, and a body the sender says was encoded twice was handed
  9494. // back after one pass, still compressed but presented as decoded.
  9495. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  9496. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9497. Server svr;
  9498. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  9499. res.set_content(body, "image/jpeg");
  9500. res.headers.emplace("Content-Encoding", "gzip");
  9501. res.headers.emplace("Content-Encoding", "gzip");
  9502. });
  9503. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  9504. res.set_content(body, "image/jpeg");
  9505. res.set_header("Content-Encoding", "gzip, gzip");
  9506. });
  9507. auto port = svr.bind_to_any_port(HOST);
  9508. thread t = thread([&]() { svr.listen_after_bind(); });
  9509. auto se = detail::scope_exit([&] {
  9510. svr.stop();
  9511. t.join();
  9512. ASSERT_FALSE(svr.is_running());
  9513. });
  9514. svr.wait_until_ready();
  9515. Client cli(HOST, port);
  9516. // Two codings is not something cpp-httplib decodes, so both representations
  9517. // take the pass-through path rather than one of them being gunzipped once.
  9518. for (const char *path : {"/split", "/joined"}) {
  9519. auto res = cli.Get(path);
  9520. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  9521. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  9522. EXPECT_EQ(body, res->body) << path;
  9523. }
  9524. }
  9525. // Regression test for DoS vulnerability: a malicious server sending a response
  9526. // without Content-Length header must not cause unbounded memory consumption on
  9527. // the client side. The client should stop reading after a reasonable limit,
  9528. // similar to the server-side set_payload_max_length protection.
  9529. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9530. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9531. #ifndef _WIN32
  9532. signal(SIGPIPE, SIG_IGN);
  9533. #endif
  9534. auto server_thread = std::thread([] {
  9535. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9536. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9537. default_socket_options(srv);
  9538. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9539. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9540. sockaddr_in addr{};
  9541. addr.sin_family = AF_INET;
  9542. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9543. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9544. int opt = 1;
  9545. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9546. #ifdef _WIN32
  9547. reinterpret_cast<const char *>(&opt),
  9548. #else
  9549. &opt,
  9550. #endif
  9551. sizeof(opt));
  9552. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9553. ::listen(srv, 1);
  9554. sockaddr_in cli_addr{};
  9555. socklen_t cli_len = sizeof(cli_addr);
  9556. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9557. if (cli != INVALID_SOCKET) {
  9558. char buf[4096];
  9559. ::recv(cli, buf, sizeof(buf), 0);
  9560. // Malicious response: no Content-Length, no chunked encoding
  9561. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9562. "Connection: close\r\n"
  9563. "\r\n";
  9564. ::send(cli,
  9565. #ifdef _WIN32
  9566. static_cast<const char *>(response_header.c_str()),
  9567. static_cast<int>(response_header.size()),
  9568. #else
  9569. response_header.c_str(), response_header.size(),
  9570. #endif
  9571. 0);
  9572. // Send 10MB of data
  9573. std::string chunk(64 * 1024, 'A');
  9574. size_t total_sent = 0;
  9575. while (total_sent < MALICIOUS_DATA_SIZE) {
  9576. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9577. auto sent = ::send(cli,
  9578. #ifdef _WIN32
  9579. static_cast<const char *>(chunk.c_str()),
  9580. static_cast<int>(to_send),
  9581. #else
  9582. chunk.c_str(), to_send,
  9583. #endif
  9584. 0);
  9585. if (sent <= 0) break;
  9586. total_sent += static_cast<size_t>(sent);
  9587. }
  9588. detail::close_socket(cli);
  9589. }
  9590. detail::close_socket(srv);
  9591. });
  9592. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9593. size_t total_read = 0;
  9594. {
  9595. Client cli("127.0.0.1", PORT + 2);
  9596. cli.set_read_timeout(5, 0);
  9597. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9598. auto stream = cli.open_stream("GET", "/malicious");
  9599. ASSERT_TRUE(stream.is_valid());
  9600. char buffer[64 * 1024];
  9601. ssize_t n;
  9602. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9603. total_read += static_cast<size_t>(n);
  9604. }
  9605. } // StreamHandle and Client destroyed here, closing the socket
  9606. server_thread.join();
  9607. // With set_payload_max_length, the client must stop reading before consuming
  9608. // all 10MB. The read loop should be cut off at or near the configured limit.
  9609. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9610. << "Client read " << total_read << " bytes, exceeding the configured "
  9611. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9612. }
  9613. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9614. // the entire response body without truncation.
  9615. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9616. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9617. #ifndef _WIN32
  9618. signal(SIGPIPE, SIG_IGN);
  9619. #endif
  9620. auto server_thread = std::thread([] {
  9621. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9622. default_socket_options(srv);
  9623. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9624. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9625. sockaddr_in addr{};
  9626. addr.sin_family = AF_INET;
  9627. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9628. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9629. int opt = 1;
  9630. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9631. #ifdef _WIN32
  9632. reinterpret_cast<const char *>(&opt),
  9633. #else
  9634. &opt,
  9635. #endif
  9636. sizeof(opt));
  9637. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9638. ::listen(srv, 1);
  9639. sockaddr_in cli_addr{};
  9640. socklen_t cli_len = sizeof(cli_addr);
  9641. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9642. if (cli != INVALID_SOCKET) {
  9643. char buf[4096];
  9644. ::recv(cli, buf, sizeof(buf), 0);
  9645. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9646. "Connection: close\r\n"
  9647. "\r\n";
  9648. ::send(cli,
  9649. #ifdef _WIN32
  9650. static_cast<const char *>(response_header.c_str()),
  9651. static_cast<int>(response_header.size()),
  9652. #else
  9653. response_header.c_str(), response_header.size(),
  9654. #endif
  9655. 0);
  9656. std::string chunk(64 * 1024, 'A');
  9657. size_t total_sent = 0;
  9658. while (total_sent < DATA_SIZE) {
  9659. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9660. auto sent = ::send(cli,
  9661. #ifdef _WIN32
  9662. static_cast<const char *>(chunk.c_str()),
  9663. static_cast<int>(to_send),
  9664. #else
  9665. chunk.c_str(), to_send,
  9666. #endif
  9667. 0);
  9668. if (sent <= 0) break;
  9669. total_sent += static_cast<size_t>(sent);
  9670. }
  9671. #ifdef _WIN32
  9672. ::shutdown(cli, SD_SEND);
  9673. #else
  9674. ::shutdown(cli, SHUT_WR);
  9675. #endif
  9676. // Drain until the client closes its end, ensuring all data is delivered
  9677. char drain[1024];
  9678. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9679. detail::close_socket(cli);
  9680. }
  9681. detail::close_socket(srv);
  9682. });
  9683. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9684. size_t total_read = 0;
  9685. {
  9686. Client cli("127.0.0.1", PORT + 2);
  9687. cli.set_read_timeout(5, 0);
  9688. cli.set_payload_max_length(0); // 0 means no limit
  9689. auto stream = cli.open_stream("GET", "/data");
  9690. ASSERT_TRUE(stream.is_valid());
  9691. char buffer[64 * 1024];
  9692. ssize_t n;
  9693. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9694. total_read += static_cast<size_t>(n);
  9695. }
  9696. }
  9697. server_thread.join();
  9698. EXPECT_EQ(total_read, DATA_SIZE)
  9699. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9700. << " bytes without truncation, but only read " << total_read << " bytes.";
  9701. }
  9702. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9703. // enormous Content-Length must not cause the client to pre-allocate a huge
  9704. // response body buffer. The reservation is capped at payload_max_length_, and
  9705. // the read itself fails when the body exceeds the limit.
  9706. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9707. #ifndef _WIN32
  9708. signal(SIGPIPE, SIG_IGN);
  9709. #endif
  9710. auto server_thread = std::thread([] {
  9711. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9712. default_socket_options(srv);
  9713. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9714. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9715. sockaddr_in addr{};
  9716. addr.sin_family = AF_INET;
  9717. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9718. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9719. int opt = 1;
  9720. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9721. #ifdef _WIN32
  9722. reinterpret_cast<const char *>(&opt),
  9723. #else
  9724. &opt,
  9725. #endif
  9726. sizeof(opt));
  9727. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9728. ::listen(srv, 1);
  9729. sockaddr_in cli_addr{};
  9730. socklen_t cli_len = sizeof(cli_addr);
  9731. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9732. if (cli != INVALID_SOCKET) {
  9733. char buf[4096];
  9734. ::recv(cli, buf, sizeof(buf), 0);
  9735. // Malicious response: claim a 20GB body but send only a tiny payload.
  9736. std::string response = "HTTP/1.1 200 OK\r\n"
  9737. "Content-Length: 20000000000\r\n"
  9738. "\r\n"
  9739. "abc";
  9740. ::send(cli,
  9741. #ifdef _WIN32
  9742. static_cast<const char *>(response.c_str()),
  9743. static_cast<int>(response.size()),
  9744. #else
  9745. response.c_str(), response.size(),
  9746. #endif
  9747. 0);
  9748. detail::close_socket(cli);
  9749. }
  9750. detail::close_socket(srv);
  9751. });
  9752. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9753. {
  9754. Client cli("127.0.0.1", PORT + 2);
  9755. cli.set_read_timeout(5, 0);
  9756. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9757. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9758. // (server claims more bytes than payload_max_length permits), but it must
  9759. // not exhaust memory before getting there.
  9760. auto res = cli.Get("/malicious");
  9761. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9762. }
  9763. server_thread.join();
  9764. }
  9765. // Verify that content_receiver bypasses the default payload_max_length,
  9766. // allowing streaming downloads larger than 100MB without requiring an explicit
  9767. // set_payload_max_length call.
  9768. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9769. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9770. #ifndef _WIN32
  9771. signal(SIGPIPE, SIG_IGN);
  9772. #endif
  9773. auto server_thread = std::thread([] {
  9774. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9775. default_socket_options(srv);
  9776. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9777. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9778. sockaddr_in addr{};
  9779. addr.sin_family = AF_INET;
  9780. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9781. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9782. int opt = 1;
  9783. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9784. #ifdef _WIN32
  9785. reinterpret_cast<const char *>(&opt),
  9786. #else
  9787. &opt,
  9788. #endif
  9789. sizeof(opt));
  9790. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9791. ::listen(srv, 1);
  9792. sockaddr_in cli_addr{};
  9793. socklen_t cli_len = sizeof(cli_addr);
  9794. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9795. if (cli != INVALID_SOCKET) {
  9796. char buf[4096];
  9797. ::recv(cli, buf, sizeof(buf), 0);
  9798. // Response with Content-Length larger than default 100MB limit
  9799. auto content_length = std::to_string(DATA_SIZE);
  9800. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9801. "Content-Length: " +
  9802. content_length +
  9803. "\r\n"
  9804. "Connection: close\r\n"
  9805. "\r\n";
  9806. ::send(cli,
  9807. #ifdef _WIN32
  9808. static_cast<const char *>(response_header.c_str()),
  9809. static_cast<int>(response_header.size()),
  9810. #else
  9811. response_header.c_str(), response_header.size(),
  9812. #endif
  9813. 0);
  9814. std::string chunk(64 * 1024, 'A');
  9815. size_t total_sent = 0;
  9816. while (total_sent < DATA_SIZE) {
  9817. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9818. auto sent = ::send(cli,
  9819. #ifdef _WIN32
  9820. static_cast<const char *>(chunk.c_str()),
  9821. static_cast<int>(to_send),
  9822. #else
  9823. chunk.c_str(), to_send,
  9824. #endif
  9825. 0);
  9826. if (sent <= 0) break;
  9827. total_sent += static_cast<size_t>(sent);
  9828. }
  9829. detail::close_socket(cli);
  9830. }
  9831. detail::close_socket(srv);
  9832. });
  9833. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9834. size_t total_received = 0;
  9835. {
  9836. Client cli("127.0.0.1", PORT + 2);
  9837. cli.set_read_timeout(10, 0);
  9838. // Do NOT call set_payload_max_length — use the default 100MB limit
  9839. auto res =
  9840. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9841. total_received += data_length;
  9842. return true;
  9843. });
  9844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9845. EXPECT_EQ(StatusCode::OK_200, res->status);
  9846. }
  9847. server_thread.join();
  9848. EXPECT_EQ(total_received, DATA_SIZE)
  9849. << "With content_receiver, the client should read all " << DATA_SIZE
  9850. << " bytes despite the default 100MB payload_max_length, but only read "
  9851. << total_received << " bytes.";
  9852. }
  9853. // Verify that an explicit set_payload_max_length smaller than the response is
  9854. // enforced even when a content_receiver is used.
  9855. TEST(ClientVulnerabilityTest,
  9856. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9857. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9858. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9859. #ifndef _WIN32
  9860. signal(SIGPIPE, SIG_IGN);
  9861. #endif
  9862. auto server_thread = std::thread([] {
  9863. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9864. default_socket_options(srv);
  9865. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9866. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9867. sockaddr_in addr{};
  9868. addr.sin_family = AF_INET;
  9869. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9870. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9871. int opt = 1;
  9872. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9873. #ifdef _WIN32
  9874. reinterpret_cast<const char *>(&opt),
  9875. #else
  9876. &opt,
  9877. #endif
  9878. sizeof(opt));
  9879. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9880. ::listen(srv, 1);
  9881. sockaddr_in cli_addr{};
  9882. socklen_t cli_len = sizeof(cli_addr);
  9883. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9884. if (cli != INVALID_SOCKET) {
  9885. char buf[4096];
  9886. ::recv(cli, buf, sizeof(buf), 0);
  9887. auto content_length = std::to_string(DATA_SIZE);
  9888. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9889. "Content-Length: " +
  9890. content_length +
  9891. "\r\n"
  9892. "Connection: close\r\n"
  9893. "\r\n";
  9894. ::send(cli,
  9895. #ifdef _WIN32
  9896. static_cast<const char *>(response_header.c_str()),
  9897. static_cast<int>(response_header.size()),
  9898. #else
  9899. response_header.c_str(), response_header.size(),
  9900. #endif
  9901. 0);
  9902. std::string chunk(64 * 1024, 'A');
  9903. size_t total_sent = 0;
  9904. while (total_sent < DATA_SIZE) {
  9905. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9906. auto sent = ::send(cli,
  9907. #ifdef _WIN32
  9908. static_cast<const char *>(chunk.c_str()),
  9909. static_cast<int>(to_send),
  9910. #else
  9911. chunk.c_str(), to_send,
  9912. #endif
  9913. 0);
  9914. if (sent <= 0) break;
  9915. total_sent += static_cast<size_t>(sent);
  9916. }
  9917. detail::close_socket(cli);
  9918. }
  9919. detail::close_socket(srv);
  9920. });
  9921. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9922. size_t total_received = 0;
  9923. {
  9924. Client cli("127.0.0.1", PORT + 2);
  9925. cli.set_read_timeout(10, 0);
  9926. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9927. auto res =
  9928. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9929. total_received += data_length;
  9930. return true;
  9931. });
  9932. // Should fail because 200MB exceeds the explicit 150MB limit
  9933. EXPECT_FALSE(res);
  9934. }
  9935. server_thread.join();
  9936. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9937. << "Client with content_receiver should respect the explicit "
  9938. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9939. << total_received << " bytes.";
  9940. }
  9941. // Verify that an explicit set_payload_max_length larger than the response
  9942. // allows the content_receiver to read all data successfully.
  9943. TEST(ClientVulnerabilityTest,
  9944. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9945. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9946. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9947. #ifndef _WIN32
  9948. signal(SIGPIPE, SIG_IGN);
  9949. #endif
  9950. auto server_thread = std::thread([] {
  9951. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9952. default_socket_options(srv);
  9953. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9954. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9955. sockaddr_in addr{};
  9956. addr.sin_family = AF_INET;
  9957. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9958. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9959. int opt = 1;
  9960. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9961. #ifdef _WIN32
  9962. reinterpret_cast<const char *>(&opt),
  9963. #else
  9964. &opt,
  9965. #endif
  9966. sizeof(opt));
  9967. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9968. ::listen(srv, 1);
  9969. sockaddr_in cli_addr{};
  9970. socklen_t cli_len = sizeof(cli_addr);
  9971. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9972. if (cli != INVALID_SOCKET) {
  9973. char buf[4096];
  9974. ::recv(cli, buf, sizeof(buf), 0);
  9975. auto content_length = std::to_string(DATA_SIZE);
  9976. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9977. "Content-Length: " +
  9978. content_length +
  9979. "\r\n"
  9980. "Connection: close\r\n"
  9981. "\r\n";
  9982. ::send(cli,
  9983. #ifdef _WIN32
  9984. static_cast<const char *>(response_header.c_str()),
  9985. static_cast<int>(response_header.size()),
  9986. #else
  9987. response_header.c_str(), response_header.size(),
  9988. #endif
  9989. 0);
  9990. std::string chunk(64 * 1024, 'A');
  9991. size_t total_sent = 0;
  9992. while (total_sent < DATA_SIZE) {
  9993. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9994. auto sent = ::send(cli,
  9995. #ifdef _WIN32
  9996. static_cast<const char *>(chunk.c_str()),
  9997. static_cast<int>(to_send),
  9998. #else
  9999. chunk.c_str(), to_send,
  10000. #endif
  10001. 0);
  10002. if (sent <= 0) break;
  10003. total_sent += static_cast<size_t>(sent);
  10004. }
  10005. #ifdef _WIN32
  10006. ::shutdown(cli, SD_SEND);
  10007. #else
  10008. ::shutdown(cli, SHUT_WR);
  10009. #endif
  10010. char drain[1024];
  10011. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10012. detail::close_socket(cli);
  10013. }
  10014. detail::close_socket(srv);
  10015. });
  10016. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10017. size_t total_received = 0;
  10018. {
  10019. Client cli("127.0.0.1", PORT + 2);
  10020. cli.set_read_timeout(10, 0);
  10021. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  10022. auto res =
  10023. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  10024. total_received += data_length;
  10025. return true;
  10026. });
  10027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10028. EXPECT_EQ(StatusCode::OK_200, res->status);
  10029. }
  10030. server_thread.join();
  10031. EXPECT_EQ(total_received, DATA_SIZE)
  10032. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  10033. << " bytes (larger than " << DATA_SIZE
  10034. << " bytes response), content_receiver should read all data, but only "
  10035. "read "
  10036. << total_received << " bytes.";
  10037. }
  10038. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  10039. // Regression test for "zip bomb" attack on the client side: a malicious server
  10040. // sends a small gzip-compressed response that decompresses to a huge payload.
  10041. // The client must enforce payload_max_length on the decompressed size.
  10042. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  10043. constexpr size_t DECOMPRESSED_SIZE =
  10044. 10 * 1024 * 1024; // 10MB after decompression
  10045. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10046. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  10047. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  10048. std::string compressed;
  10049. {
  10050. httplib::detail::gzip_compressor compressor;
  10051. bool ok =
  10052. compressor.compress(uncompressed.data(), uncompressed.size(),
  10053. /*last=*/true, [&](const char *buf, size_t len) {
  10054. compressed.append(buf, len);
  10055. return true;
  10056. });
  10057. ASSERT_TRUE(ok);
  10058. }
  10059. // Sanity: compressed data should be much smaller than the decompressed size
  10060. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  10061. #ifndef _WIN32
  10062. signal(SIGPIPE, SIG_IGN);
  10063. #endif
  10064. // Set up the listening socket in the main thread so the server is guaranteed
  10065. // to be ready before the client connects (eliminates race condition).
  10066. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10067. default_socket_options(srv);
  10068. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10069. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10070. sockaddr_in addr{};
  10071. addr.sin_family = AF_INET;
  10072. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  10073. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10074. int opt = 1;
  10075. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10076. #ifdef _WIN32
  10077. reinterpret_cast<const char *>(&opt),
  10078. #else
  10079. &opt,
  10080. #endif
  10081. sizeof(opt));
  10082. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  10083. ASSERT_EQ(0, ::listen(srv, 1));
  10084. auto server_thread = std::thread([&compressed, srv] {
  10085. sockaddr_in cli_addr{};
  10086. socklen_t cli_len = sizeof(cli_addr);
  10087. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10088. if (cli != INVALID_SOCKET) {
  10089. // Read the full HTTP request (until \r\n\r\n)
  10090. char buf[4096];
  10091. size_t total = 0;
  10092. while (total < sizeof(buf)) {
  10093. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  10094. if (n <= 0) break;
  10095. total += static_cast<size_t>(n);
  10096. // Check for end of headers
  10097. if (total >= 4) {
  10098. std::string req(buf, total);
  10099. if (req.find("\r\n\r\n") != std::string::npos) break;
  10100. }
  10101. }
  10102. // Malicious response: gzip-compressed body, no Content-Length
  10103. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10104. "Content-Encoding: gzip\r\n"
  10105. "Connection: close\r\n"
  10106. "\r\n";
  10107. ::send(cli,
  10108. #ifdef _WIN32
  10109. static_cast<const char *>(response_header.c_str()),
  10110. static_cast<int>(response_header.size()),
  10111. #else
  10112. response_header.c_str(), response_header.size(),
  10113. #endif
  10114. 0);
  10115. // Send the compressed payload (small on the wire, huge when decompressed)
  10116. size_t total_sent = 0;
  10117. while (total_sent < compressed.size()) {
  10118. auto to_send = std::min(compressed.size() - total_sent,
  10119. static_cast<size_t>(64 * 1024));
  10120. auto sent =
  10121. ::send(cli,
  10122. #ifdef _WIN32
  10123. static_cast<const char *>(compressed.c_str() + total_sent),
  10124. static_cast<int>(to_send),
  10125. #else
  10126. compressed.c_str() + total_sent, to_send,
  10127. #endif
  10128. 0);
  10129. if (sent <= 0) break;
  10130. total_sent += static_cast<size_t>(sent);
  10131. }
  10132. detail::close_socket(cli);
  10133. }
  10134. });
  10135. auto se = detail::scope_exit([&] {
  10136. detail::close_socket(srv);
  10137. server_thread.join();
  10138. });
  10139. size_t total_decompressed = 0;
  10140. {
  10141. Client cli("127.0.0.1", PORT + 3);
  10142. cli.set_read_timeout(5, 0);
  10143. cli.set_decompress(true);
  10144. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10145. auto stream = cli.open_stream("GET", "/zipbomb");
  10146. ASSERT_TRUE(stream.is_valid());
  10147. char buffer[64 * 1024];
  10148. ssize_t n;
  10149. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10150. total_decompressed += static_cast<size_t>(n);
  10151. }
  10152. }
  10153. // The decompressed size must be capped by payload_max_length. Without
  10154. // protection, the client would decompress the full 10MB from a tiny
  10155. // compressed payload, enabling a zip bomb DoS attack.
  10156. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10157. << "Client decompressed " << total_decompressed
  10158. << " bytes from a gzip response. The decompressed size should be "
  10159. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10160. }
  10161. #endif
  10162. TEST(HostAndPortPropertiesTest, NoSSL) {
  10163. httplib::Client cli("www.google.com", 1234);
  10164. ASSERT_EQ("www.google.com", cli.host());
  10165. ASSERT_EQ(1234, cli.port());
  10166. }
  10167. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10168. httplib::Client cli("www.google.com:1234");
  10169. ASSERT_EQ("www.google.com", cli.host());
  10170. ASSERT_EQ(1234, cli.port());
  10171. }
  10172. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10173. // Port number that overflows int — should not crash, client becomes invalid
  10174. httplib::Client cli("http://www.google.com:99999999999999999999");
  10175. ASSERT_FALSE(cli.is_valid());
  10176. }
  10177. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10178. // Port 99999 exceeds valid range (1-65535) — should not crash
  10179. httplib::Client cli("http://www.google.com:99999");
  10180. ASSERT_FALSE(cli.is_valid());
  10181. }
  10182. #ifdef CPPHTTPLIB_SSL_ENABLED
  10183. TEST(HostAndPortPropertiesTest, SSL) {
  10184. httplib::SSLClient cli("www.google.com");
  10185. ASSERT_EQ("www.google.com", cli.host());
  10186. ASSERT_EQ(443, cli.port());
  10187. }
  10188. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10189. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10190. std::string cert;
  10191. read_file(CA_CERT_FILE, cert);
  10192. httplib::SSLClient httplib_client("www.google.com");
  10193. // Load CA store first time
  10194. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10195. // Load CA store second time (update)
  10196. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10197. // Verify client is still valid and can make connections
  10198. httplib_client.enable_server_certificate_verification(true);
  10199. auto res = httplib_client.Get("/");
  10200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10201. // Google may return 200 or 301 depending on various factors
  10202. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10203. res->status == StatusCode::MovedPermanently_301);
  10204. }
  10205. TEST(SSLClientTest, ServerNameIndication_Online) {
  10206. auto host = "httpbingo.org";
  10207. auto path = std::string{"/get"};
  10208. SSLClient cli(host, 443);
  10209. auto res = cli.Get(path);
  10210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10211. ASSERT_EQ(StatusCode::OK_200, res->status);
  10212. }
  10213. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10214. // Use a site that will cause SSL verification failure due to self-signed cert
  10215. SSLClient cli("self-signed.badssl.com", 443);
  10216. cli.enable_server_certificate_verification(true);
  10217. auto res = cli.Get("/");
  10218. ASSERT_TRUE(!res);
  10219. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10220. // Verify backend error is captured for SSLServerVerification
  10221. // This occurs when certificate verification fails
  10222. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10223. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10224. EXPECT_NE(0UL, res.ssl_backend_error());
  10225. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10226. // For OpenSSL, ssl_error is 0 for verification errors
  10227. EXPECT_EQ(0, res.ssl_error());
  10228. #if !defined(_WIN32) || \
  10229. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10230. // On non-Windows or when Windows Schannel is disabled, the error comes
  10231. // from OpenSSL's verification
  10232. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10233. res.ssl_backend_error());
  10234. #endif
  10235. #endif
  10236. }
  10237. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10238. // Use a site where hostname doesn't match the certificate
  10239. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10240. SSLClient cli("wrong.host.badssl.com", 443);
  10241. cli.enable_server_certificate_verification(true);
  10242. cli.enable_server_hostname_verification(true);
  10243. auto res = cli.Get("/");
  10244. ASSERT_TRUE(!res);
  10245. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10246. // Verify backend error is captured for hostname verification failure
  10247. EXPECT_NE(0UL, res.ssl_backend_error());
  10248. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10249. // For OpenSSL, ssl_error is 0 for verification errors
  10250. EXPECT_EQ(0, res.ssl_error());
  10251. #if !defined(_WIN32) || \
  10252. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10253. // On non-Windows or when Windows Schannel is disabled, the error comes
  10254. // from OpenSSL's hostname verification
  10255. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10256. res.ssl_backend_error());
  10257. #endif
  10258. #endif
  10259. }
  10260. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10261. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10262. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10263. SSLClient cli("www.google.com", 443);
  10264. cli.enable_server_certificate_verification(true);
  10265. auto res = cli.Get("/");
  10266. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10267. }
  10268. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10269. SSLClient cli("www.google.com", 443);
  10270. cli.enable_server_certificate_verification(true);
  10271. cli.enable_windows_certificate_verification(false);
  10272. auto res = cli.Get("/");
  10273. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10274. }
  10275. #endif
  10276. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10277. Client cli("https://google.com");
  10278. auto res = cli.Get("/");
  10279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10280. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10281. }
  10282. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10283. SSLClient cli("google.com");
  10284. cli.set_ca_cert_path(CA_CERT_FILE);
  10285. auto res = cli.Get("/");
  10286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10287. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10288. }
  10289. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10290. SSLClient cli("google.com");
  10291. cli.enable_server_certificate_verification(true);
  10292. cli.set_ca_cert_path("hello");
  10293. auto res = cli.Get("/");
  10294. ASSERT_TRUE(!res);
  10295. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10296. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10297. // should be set
  10298. EXPECT_EQ(0, res.ssl_error());
  10299. // Verify backend error is captured for SSLLoadingCerts
  10300. // This error occurs when loading CA certificates fails
  10301. EXPECT_NE(0UL, res.ssl_backend_error());
  10302. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10303. // OpenSSL specific error codes:
  10304. // > openssl errstr 0x80000002
  10305. // error:80000002:system library::No such file or directory
  10306. // > openssl errstr 0xA000126
  10307. // error:0A000126:SSL routines::unexpected eof while reading
  10308. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10309. res.ssl_backend_error() == 0xA000126);
  10310. #endif
  10311. }
  10312. TEST(SSLClientTest, ServerCertificateVerification4) {
  10313. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10314. ASSERT_TRUE(svr.is_valid());
  10315. svr.Get("/test", [&](const Request &, Response &res) {
  10316. res.set_content("test", "text/plain");
  10317. svr.stop();
  10318. ASSERT_TRUE(true);
  10319. });
  10320. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10321. auto se = detail::scope_exit([&] {
  10322. t.join();
  10323. ASSERT_FALSE(svr.is_running());
  10324. });
  10325. svr.wait_until_ready();
  10326. SSLClient cli("127.0.0.1", PORT);
  10327. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10328. cli.enable_server_certificate_verification(true);
  10329. cli.set_connection_timeout(30);
  10330. auto res = cli.Get("/test");
  10331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10332. ASSERT_EQ(StatusCode::OK_200, res->status);
  10333. }
  10334. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10335. std::string cert;
  10336. read_file(CA_CERT_FILE, cert);
  10337. SSLClient cli("google.com");
  10338. cli.load_ca_cert_store(cert.data(), cert.size());
  10339. const auto res = cli.Get("/");
  10340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10341. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10342. }
  10343. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10344. // clang-format off
  10345. static constexpr char cert[] =
  10346. "GlobalSign Root CA\n"
  10347. "==================\n"
  10348. "-----BEGIN CERTIFICATE-----\n"
  10349. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10350. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10351. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10352. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10353. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10354. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10355. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10356. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10357. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10358. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10359. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10360. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10361. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10362. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10363. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10364. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10365. "-----END CERTIFICATE-----\n";
  10366. // clang-format on
  10367. SSLClient cli("google.com");
  10368. cli.load_ca_cert_store(cert, sizeof(cert));
  10369. const auto res = cli.Get("/");
  10370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10371. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10372. }
  10373. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10374. SSLClient cli("www.youtube.com");
  10375. cli.set_ca_cert_path(CA_CERT_FILE);
  10376. cli.enable_server_certificate_verification(true);
  10377. cli.set_follow_location(true);
  10378. auto res = cli.Get("/");
  10379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10380. ASSERT_EQ(StatusCode::OK_200, res->status);
  10381. }
  10382. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10383. SSLClient cli("wWw.YouTube.Com");
  10384. cli.set_ca_cert_path(CA_CERT_FILE);
  10385. cli.enable_server_certificate_verification(true);
  10386. cli.enable_server_hostname_verification(true);
  10387. cli.set_follow_location(true);
  10388. auto res = cli.Get("/");
  10389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10390. ASSERT_EQ(StatusCode::OK_200, res->status);
  10391. }
  10392. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10393. SSLClient cli("gOoGlE.COm");
  10394. cli.enable_server_certificate_verification(true);
  10395. cli.enable_server_hostname_verification(true);
  10396. cli.set_follow_location(true);
  10397. auto res = cli.Get("/");
  10398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10399. ASSERT_EQ(StatusCode::OK_200, res->status);
  10400. }
  10401. TEST(SSLClientTest, Issue2004_Online) {
  10402. Client client("https://google.com");
  10403. client.set_follow_location(true);
  10404. auto res = client.Get("/");
  10405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10406. ASSERT_EQ(StatusCode::OK_200, res->status);
  10407. auto body = res->body;
  10408. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10409. }
  10410. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10411. // Create SSLClient with invalid cert/key to make is_valid() return false
  10412. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10413. "nonexistent_key.pem");
  10414. // is_valid() should be false due to cert loading failure
  10415. ASSERT_FALSE(cli.is_valid());
  10416. auto res = cli.Get("/");
  10417. ASSERT_FALSE(res);
  10418. EXPECT_EQ(Error::SSLConnection, res.error());
  10419. }
  10420. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10421. // Test for Issue #2251: SSL error not properly reported when client cert
  10422. // and key paths are swapped or mismatched
  10423. // This simulates the scenario where user accidentally swaps the cert and key
  10424. // files
  10425. // Using client cert file as private key and vice versa (completely wrong)
  10426. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10427. // Should fail validation due to cert/key mismatch
  10428. ASSERT_FALSE(cli.is_valid());
  10429. // Attempt to make a request should fail with proper error
  10430. auto res = cli.Get("/");
  10431. ASSERT_FALSE(res);
  10432. EXPECT_EQ(Error::SSLConnection, res.error());
  10433. // SSL error should be recorded in the Result object (this is the key fix for
  10434. // Issue #2251)
  10435. auto backend_error = res.ssl_backend_error();
  10436. EXPECT_NE(0u, backend_error);
  10437. }
  10438. // Tests cert/key mismatch detection at the TLS context level
  10439. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10440. // Test that using mismatched cert/key causes connection failure.
  10441. // We verify this at the SSLClient level rather than through internal
  10442. // TLS API functions.
  10443. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10444. cli.enable_server_certificate_verification(false);
  10445. cli.set_connection_timeout(2);
  10446. // The mismatch should cause a connection or handshake error
  10447. auto res = cli.Get("/test");
  10448. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10449. // Either way, the request should fail
  10450. EXPECT_FALSE(res);
  10451. }
  10452. #endif
  10453. #if 0
  10454. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10455. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10456. ASSERT_TRUE(cli != nullptr);
  10457. cli->set_address_family(AF_INET6);
  10458. cli->set_interface("en0");
  10459. auto res = cli->Get("/get");
  10460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10461. ASSERT_EQ(StatusCode::OK_200, res->status);
  10462. }
  10463. #endif
  10464. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10465. #ifdef CPPHTTPLIB_SSL_ENABLED
  10466. void ClientCertPresent(
  10467. const std::string &client_cert_file,
  10468. const std::string &client_private_key_file,
  10469. const std::string &client_encrypted_private_key_pass = std::string()) {
  10470. using namespace httplib::tls;
  10471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10472. CLIENT_CA_CERT_DIR);
  10473. ASSERT_TRUE(svr.is_valid());
  10474. svr.Get("/test", [&](const Request &req, Response &res) {
  10475. res.set_content("test", "text/plain");
  10476. auto cert = req.peer_cert();
  10477. ASSERT_TRUE(static_cast<bool>(cert));
  10478. std::string common_name = cert.subject_cn();
  10479. EXPECT_EQ("Common Name", common_name);
  10480. });
  10481. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10482. auto se = detail::scope_exit([&] {
  10483. svr.stop();
  10484. t.join();
  10485. ASSERT_FALSE(svr.is_running());
  10486. });
  10487. svr.wait_until_ready();
  10488. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10489. client_encrypted_private_key_pass);
  10490. cli.enable_server_certificate_verification(false);
  10491. cli.set_connection_timeout(30);
  10492. auto res = cli.Get("/test");
  10493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10494. ASSERT_EQ(StatusCode::OK_200, res->status);
  10495. }
  10496. TEST(SSLClientServerTest, ClientCertPresent) {
  10497. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10498. }
  10499. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10500. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10501. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10502. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10503. }
  10504. // PEM memory-based constructor tests (works with all TLS backends)
  10505. void PemMemoryClientCertPresent(
  10506. const std::string &client_cert_file,
  10507. const std::string &client_private_key_file,
  10508. const std::string &client_encrypted_private_key_pass = std::string()) {
  10509. // Read PEM files into memory
  10510. std::string server_cert_pem, server_key_pem;
  10511. std::string client_ca_pem;
  10512. std::string client_cert_pem, client_key_pem;
  10513. read_file(SERVER_CERT_FILE, server_cert_pem);
  10514. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10515. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10516. read_file(client_cert_file, client_cert_pem);
  10517. read_file(client_private_key_file, client_key_pem);
  10518. // Create server with PEM memory
  10519. SSLServer::PemMemory server_pem = {
  10520. server_cert_pem.c_str(),
  10521. server_cert_pem.size(),
  10522. server_key_pem.c_str(),
  10523. server_key_pem.size(),
  10524. client_ca_pem.c_str(),
  10525. client_ca_pem.size(),
  10526. nullptr // no password for server key
  10527. };
  10528. SSLServer svr(server_pem);
  10529. ASSERT_TRUE(svr.is_valid());
  10530. svr.Get("/test", [&](const Request &, Response &res) {
  10531. res.set_content("test", "text/plain");
  10532. });
  10533. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10534. auto se = detail::scope_exit([&] {
  10535. svr.stop();
  10536. t.join();
  10537. ASSERT_FALSE(svr.is_running());
  10538. });
  10539. svr.wait_until_ready();
  10540. // Create client with PEM memory
  10541. const char *password = client_encrypted_private_key_pass.empty()
  10542. ? nullptr
  10543. : client_encrypted_private_key_pass.c_str();
  10544. SSLClient::PemMemory client_pem = {
  10545. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10546. client_key_pem.size(), password};
  10547. SSLClient cli(HOST, PORT, client_pem);
  10548. cli.enable_server_certificate_verification(false);
  10549. cli.set_connection_timeout(30);
  10550. auto res = cli.Get("/test");
  10551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10552. ASSERT_EQ(StatusCode::OK_200, res->status);
  10553. }
  10554. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10555. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10556. }
  10557. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10558. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10559. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10560. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10561. }
  10562. TEST(SSLClientServerTest, ClientCertMissing) {
  10563. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10564. CLIENT_CA_CERT_DIR);
  10565. ASSERT_TRUE(svr.is_valid());
  10566. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10567. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10568. auto se = detail::scope_exit([&] {
  10569. svr.stop();
  10570. t.join();
  10571. ASSERT_FALSE(svr.is_running());
  10572. });
  10573. svr.wait_until_ready();
  10574. SSLClient cli(HOST, PORT);
  10575. cli.set_connection_timeout(30);
  10576. auto res = cli.Get("/test");
  10577. ASSERT_TRUE(!res);
  10578. // When client cert is missing and server requires it, connection fails
  10579. // Error type depends on backend implementation
  10580. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10581. res.error() == Error::SSLConnection);
  10582. // Verify backend error is captured
  10583. // Note: This test may have different error codes depending on the exact
  10584. // verification failure
  10585. EXPECT_NE(0UL, res.ssl_backend_error());
  10586. }
  10587. TEST(SSLClientServerTest, TrustDirOptional) {
  10588. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10589. ASSERT_TRUE(svr.is_valid());
  10590. svr.Get("/test", [&](const Request &, Response &res) {
  10591. res.set_content("test", "text/plain");
  10592. });
  10593. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10594. auto se = detail::scope_exit([&] {
  10595. svr.stop();
  10596. t.join();
  10597. ASSERT_FALSE(svr.is_running());
  10598. });
  10599. svr.wait_until_ready();
  10600. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10601. cli.enable_server_certificate_verification(false);
  10602. cli.set_connection_timeout(30);
  10603. auto res = cli.Get("/test");
  10604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10605. ASSERT_EQ(StatusCode::OK_200, res->status);
  10606. }
  10607. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10608. class NoListenSSLServer : public SSLServer {
  10609. public:
  10610. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10611. const char *client_ca_cert_file_path,
  10612. const char *client_ca_cert_dir_path = nullptr)
  10613. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10614. client_ca_cert_dir_path),
  10615. stop_(false) {}
  10616. std::atomic_bool stop_;
  10617. private:
  10618. bool process_and_close_socket(socket_t /*sock*/) override {
  10619. // Don't create SSL context
  10620. while (!stop_.load()) {
  10621. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10622. }
  10623. return true;
  10624. }
  10625. };
  10626. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10627. CLIENT_CA_CERT_FILE);
  10628. ASSERT_TRUE(svr.is_valid());
  10629. svr.Get("/test", [&](const Request &, Response &res) {
  10630. res.set_content("test", "text/plain");
  10631. });
  10632. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10633. auto se = detail::scope_exit([&] {
  10634. svr.stop_ = true;
  10635. svr.stop();
  10636. t.join();
  10637. ASSERT_FALSE(svr.is_running());
  10638. });
  10639. svr.wait_until_ready();
  10640. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10641. cli.enable_server_certificate_verification(false);
  10642. cli.set_connection_timeout(1);
  10643. auto res = cli.Get("/test");
  10644. ASSERT_TRUE(!res);
  10645. EXPECT_EQ(Error::SSLConnection, res.error());
  10646. // Timeout results in WantRead error code (maps to backend-specific value)
  10647. EXPECT_NE(0, res.ssl_error());
  10648. }
  10649. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10650. // Test SSLServer with client certificate verification using the standard
  10651. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10652. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10653. CLIENT_CA_CERT_DIR);
  10654. ASSERT_TRUE(svr.is_valid());
  10655. svr.Get("/test", [&](const Request &req, Response &res) {
  10656. res.set_content("test", "text/plain");
  10657. auto cert = req.peer_cert();
  10658. ASSERT_TRUE(static_cast<bool>(cert));
  10659. auto common_name = cert.subject_cn();
  10660. EXPECT_EQ("Common Name", common_name);
  10661. });
  10662. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10663. auto se = detail::scope_exit([&] {
  10664. svr.stop();
  10665. t.join();
  10666. ASSERT_FALSE(svr.is_running());
  10667. });
  10668. svr.wait_until_ready();
  10669. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10670. cli.enable_server_certificate_verification(false);
  10671. cli.set_connection_timeout(30);
  10672. auto res = cli.Get("/test");
  10673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10674. ASSERT_EQ(StatusCode::OK_200, res->status);
  10675. }
  10676. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10677. // Verifies that wildcard matching and exact matching work consistently
  10678. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10679. using namespace httplib::tls;
  10680. // We need a running server to test against
  10681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10682. ASSERT_TRUE(svr.is_valid());
  10683. svr.Get("/test", [](const Request &, Response &res) {
  10684. res.set_content("ok", "text/plain");
  10685. });
  10686. thread t([&]() { svr.listen(HOST, PORT); });
  10687. auto se = detail::scope_exit([&] {
  10688. svr.stop();
  10689. t.join();
  10690. });
  10691. svr.wait_until_ready();
  10692. bool verify_callback_called = false;
  10693. bool verify_result_wrong = false;
  10694. SSLClient cli(HOST, PORT);
  10695. cli.enable_server_certificate_verification(true);
  10696. cli.set_ca_cert_path(CA_CERT_FILE);
  10697. cli.set_connection_timeout(5);
  10698. // Note: Test certificate has CN="Common Name", not "localhost"
  10699. bool verify_result_cn = false;
  10700. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10701. verify_callback_called = true;
  10702. if (!ctx.cert) return false;
  10703. // Test 1: "Common Name" should match (our test server cert CN)
  10704. verify_result_cn = ctx.check_hostname("Common Name");
  10705. // Test 2: wrong hostname should not match
  10706. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10707. return true; // Accept for the purpose of this test
  10708. });
  10709. auto res = cli.Get("/test");
  10710. // The request may succeed or fail depending on cert configuration
  10711. // but the callback should have been called
  10712. ASSERT_TRUE(verify_callback_called)
  10713. << "Verify callback should have been called";
  10714. // CN="Common Name" should match our test certificate
  10715. //
  10716. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10717. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10718. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10719. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10720. // <openssl/base.h>, which is included transitively when
  10721. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10722. #if defined(OPENSSL_IS_BORINGSSL)
  10723. EXPECT_FALSE(verify_result_cn)
  10724. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10725. #else
  10726. EXPECT_TRUE(verify_result_cn)
  10727. << "verify_hostname should match 'Common Name' (certificate CN)";
  10728. #endif
  10729. // Wrong hostname should not match
  10730. EXPECT_FALSE(verify_result_wrong)
  10731. << "verify_hostname should not match 'wronghost.example.com'";
  10732. }
  10733. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10734. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10735. // X509_check_ip behavior and must hold for every backend.
  10736. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10737. using namespace httplib::tls;
  10738. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10739. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10740. ASSERT_TRUE(svr.is_valid());
  10741. svr.Get("/test", [](const Request &, Response &res) {
  10742. res.set_content("ok", "text/plain");
  10743. });
  10744. thread t([&]() { svr.listen(HOST, PORT); });
  10745. auto se = detail::scope_exit([&] {
  10746. svr.stop();
  10747. t.join();
  10748. });
  10749. svr.wait_until_ready();
  10750. bool verify_callback_called = false;
  10751. bool ip_matched_via_cn = true;
  10752. SSLClient cli(HOST, PORT);
  10753. cli.enable_server_certificate_verification(true);
  10754. cli.set_ca_cert_path(CA_CERT_FILE);
  10755. cli.set_connection_timeout(5);
  10756. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10757. verify_callback_called = true;
  10758. if (!ctx.cert) return false;
  10759. // The IP appears only in the CN, so it must NOT be accepted.
  10760. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10761. return true; // Accept for the purpose of this test
  10762. });
  10763. cli.Get("/test");
  10764. ASSERT_TRUE(verify_callback_called)
  10765. << "Verify callback should have been called";
  10766. EXPECT_FALSE(ip_matched_via_cn)
  10767. << "An IP host must not be authenticated via the certificate CN";
  10768. }
  10769. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10770. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10771. using namespace httplib::tls;
  10772. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10773. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10774. ASSERT_TRUE(svr.is_valid());
  10775. svr.Get("/test", [](const Request &, Response &res) {
  10776. res.set_content("ok", "text/plain");
  10777. });
  10778. thread t([&]() { svr.listen(HOST, PORT); });
  10779. auto se = detail::scope_exit([&] {
  10780. svr.stop();
  10781. t.join();
  10782. });
  10783. svr.wait_until_ready();
  10784. bool verify_callback_called = false;
  10785. bool san_matched = false;
  10786. bool wrong_ipv6_matched = true;
  10787. bool cn_ipv6_matched = true;
  10788. SSLClient cli(HOST, PORT);
  10789. cli.enable_server_certificate_verification(true);
  10790. cli.set_ca_cert_path(CA_CERT_FILE);
  10791. cli.set_connection_timeout(5);
  10792. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10793. verify_callback_called = true;
  10794. if (!ctx.cert) return false;
  10795. // Matches the IPv6 iPAddress SAN.
  10796. san_matched = ctx.check_hostname("2001:db8::1");
  10797. // A different IPv6 address must not match.
  10798. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10799. // "::1" lives only in the CN, so it must not be accepted.
  10800. cn_ipv6_matched = ctx.check_hostname("::1");
  10801. return true; // Accept for the purpose of this test
  10802. });
  10803. cli.Get("/test");
  10804. ASSERT_TRUE(verify_callback_called)
  10805. << "Verify callback should have been called";
  10806. EXPECT_TRUE(san_matched)
  10807. << "verify_hostname should match an IPv6 iPAddress SAN";
  10808. EXPECT_FALSE(wrong_ipv6_matched)
  10809. << "verify_hostname should not match a non-matching IPv6 address";
  10810. EXPECT_FALSE(cn_ipv6_matched)
  10811. << "An IPv6 host must not be authenticated via the certificate CN";
  10812. }
  10813. #endif
  10814. // mbedTLS-specific callback constructor test
  10815. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10816. #ifdef CPPHTTPLIB_SSL_ENABLED
  10817. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10819. ASSERT_TRUE(svr.is_valid());
  10820. // Set up a handler to verify client certificate is present
  10821. bool client_cert_verified = false;
  10822. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10823. // Verify that client certificate was provided
  10824. client_cert_verified = true;
  10825. res.set_content("success", "text/plain");
  10826. });
  10827. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10828. auto se = detail::scope_exit([&] {
  10829. svr.stop();
  10830. t.join();
  10831. ASSERT_FALSE(svr.is_running());
  10832. });
  10833. svr.wait_until_ready();
  10834. // Client with certificate
  10835. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10836. cli.enable_server_certificate_verification(false);
  10837. cli.set_connection_timeout(30);
  10838. auto res = cli.Get("/test");
  10839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10840. ASSERT_EQ(StatusCode::OK_200, res->status);
  10841. ASSERT_TRUE(client_cert_verified);
  10842. EXPECT_EQ("success", res->body);
  10843. }
  10844. #endif
  10845. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10846. // backends
  10847. #ifdef CPPHTTPLIB_SSL_ENABLED
  10848. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10849. using namespace httplib::tls;
  10850. // Test that when client CA cert file is provided,
  10851. // the server properly requests and validates client certificates
  10852. // Create a server with client authentication
  10853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10854. ASSERT_TRUE(svr.is_valid());
  10855. bool handler_called = false;
  10856. svr.Get("/test", [&](const Request &req, Response &res) {
  10857. handler_called = true;
  10858. // Verify that a client certificate was provided
  10859. auto cert = req.peer_cert();
  10860. ASSERT_TRUE(static_cast<bool>(cert));
  10861. // Get the issuer name
  10862. std::string issuer_str = cert.issuer_name();
  10863. ASSERT_FALSE(issuer_str.empty());
  10864. // The client certificate should be issued by our test CA
  10865. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10866. res.set_content("authenticated", "text/plain");
  10867. });
  10868. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10869. auto se = detail::scope_exit([&] {
  10870. svr.stop();
  10871. t.join();
  10872. ASSERT_FALSE(svr.is_running());
  10873. });
  10874. svr.wait_until_ready();
  10875. // Connect with a client certificate issued by the CA
  10876. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10877. cli.enable_server_certificate_verification(false);
  10878. cli.set_connection_timeout(30);
  10879. auto res = cli.Get("/test");
  10880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10881. ASSERT_EQ(StatusCode::OK_200, res->status);
  10882. ASSERT_TRUE(handler_called);
  10883. EXPECT_EQ("authenticated", res->body);
  10884. }
  10885. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10886. using namespace httplib::tls;
  10887. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10888. ASSERT_TRUE(svr.is_valid());
  10889. svr.Get("/test", [](const Request &, Response &res) {
  10890. res.set_content("ok", "text/plain");
  10891. });
  10892. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10893. auto se = detail::scope_exit([&] {
  10894. svr.stop();
  10895. t.join();
  10896. });
  10897. svr.wait_until_ready();
  10898. SSLClient cli(HOST, PORT);
  10899. cli.enable_server_certificate_verification(false);
  10900. cli.set_connection_timeout(30);
  10901. bool cert_checked = false;
  10902. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10903. if (ctx.cert) {
  10904. auto sans = ctx.sans();
  10905. // Test certificate may or may not have SANs - just verify the API
  10906. // works If SANs exist, verify the types are valid
  10907. for (const auto &san : sans) {
  10908. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10909. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10910. san.type == SanType::OTHER);
  10911. EXPECT_FALSE(san.value.empty());
  10912. }
  10913. cert_checked = true;
  10914. }
  10915. return true;
  10916. });
  10917. auto res = cli.Get("/test");
  10918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10919. EXPECT_TRUE(cert_checked);
  10920. }
  10921. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10922. using namespace httplib::tls;
  10923. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10924. ASSERT_TRUE(svr.is_valid());
  10925. svr.Get("/test", [](const Request &, Response &res) {
  10926. res.set_content("ok", "text/plain");
  10927. });
  10928. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10929. auto se = detail::scope_exit([&] {
  10930. svr.stop();
  10931. t.join();
  10932. });
  10933. svr.wait_until_ready();
  10934. SSLClient cli(HOST, PORT);
  10935. cli.enable_server_certificate_verification(false);
  10936. cli.set_connection_timeout(30);
  10937. bool validity_checked = false;
  10938. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10939. if (ctx.cert) {
  10940. time_t not_before = 0, not_after = 0;
  10941. bool result = ctx.validity(not_before, not_after);
  10942. EXPECT_TRUE(result);
  10943. // Verify that not_before < now < not_after for a valid cert
  10944. time_t now = time(nullptr);
  10945. EXPECT_LT(not_before, now);
  10946. EXPECT_GT(not_after, now);
  10947. validity_checked = true;
  10948. }
  10949. return true;
  10950. });
  10951. auto res = cli.Get("/test");
  10952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10953. EXPECT_TRUE(validity_checked);
  10954. }
  10955. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10956. using namespace httplib::tls;
  10957. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10958. ASSERT_TRUE(svr.is_valid());
  10959. svr.Get("/test", [](const Request &, Response &res) {
  10960. res.set_content("ok", "text/plain");
  10961. });
  10962. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10963. auto se = detail::scope_exit([&] {
  10964. svr.stop();
  10965. t.join();
  10966. });
  10967. svr.wait_until_ready();
  10968. SSLClient cli(HOST, PORT);
  10969. cli.enable_server_certificate_verification(false);
  10970. cli.set_connection_timeout(30);
  10971. bool serial_checked = false;
  10972. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10973. if (ctx.cert) {
  10974. std::string serial = ctx.serial();
  10975. EXPECT_FALSE(serial.empty());
  10976. // Serial should be a hex string
  10977. for (char c : serial) {
  10978. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10979. (c >= 'a' && c <= 'f'));
  10980. }
  10981. serial_checked = true;
  10982. }
  10983. return true;
  10984. });
  10985. auto res = cli.Get("/test");
  10986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10987. EXPECT_TRUE(serial_checked);
  10988. }
  10989. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10990. // Test 1: Valid CA file - no error should be recorded
  10991. {
  10992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10993. CLIENT_CA_CERT_FILE);
  10994. ASSERT_TRUE(svr.is_valid());
  10995. // With valid setup, last_ssl_error should be 0
  10996. EXPECT_EQ(0, svr.ssl_last_error());
  10997. }
  10998. // Test 2: Invalid CA file content
  10999. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  11000. {
  11001. // Create a temporary file with completely invalid content
  11002. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  11003. {
  11004. std::ofstream ofs(temp_invalid_ca);
  11005. ofs << "This is not a certificate file at all\n";
  11006. ofs << "Just plain text content\n";
  11007. }
  11008. // Create server with invalid CA file
  11009. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  11010. // Clean up temporary file
  11011. std::remove(temp_invalid_ca);
  11012. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  11013. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  11014. // Note: SSL_CTX_load_verify_locations typically fails first,
  11015. // but our error handling code path is still exercised
  11016. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  11017. }
  11018. }
  11019. TEST(VerifyCallbackTest, VerifyContextFields) {
  11020. using namespace httplib::tls;
  11021. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11022. ASSERT_TRUE(svr.is_valid());
  11023. svr.Get("/test", [](const Request &, Response &res) {
  11024. res.set_content("ok", "text/plain");
  11025. });
  11026. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11027. auto se = detail::scope_exit([&] {
  11028. svr.stop();
  11029. t.join();
  11030. });
  11031. svr.wait_until_ready();
  11032. SSLClient cli(HOST, PORT);
  11033. cli.enable_server_certificate_verification(false);
  11034. cli.set_connection_timeout(30);
  11035. int callback_count = 0;
  11036. bool saw_leaf_cert = false;
  11037. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11038. if (ctx.cert) {
  11039. callback_count++;
  11040. // We should see at least one certificate (the leaf)
  11041. std::string cn = ctx.subject_cn();
  11042. if (!cn.empty()) { saw_leaf_cert = true; }
  11043. // Verify context fields are populated
  11044. EXPECT_NE(ctx.session, nullptr);
  11045. EXPECT_GE(ctx.depth, 0);
  11046. }
  11047. return true;
  11048. });
  11049. auto res = cli.Get("/test");
  11050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11051. EXPECT_GT(callback_count, 0);
  11052. EXPECT_TRUE(saw_leaf_cert);
  11053. }
  11054. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  11055. using httplib::tls::TlsError;
  11056. // Test that verify_error_to_string returns empty for success
  11057. std::string success_str = TlsError::verify_error_to_string(0);
  11058. EXPECT_TRUE(success_str.empty());
  11059. // Test that verify_error_to_string returns non-empty for error codes
  11060. // Using a common error code (certificate expired)
  11061. std::string error_str =
  11062. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  11063. EXPECT_FALSE(error_str.empty());
  11064. }
  11065. TEST(SessionVerifierTest, CertificateAccepted) {
  11066. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11067. ASSERT_TRUE(svr.is_valid());
  11068. svr.Get("/test", [](const Request &, Response &res) {
  11069. res.set_content("ok", "text/plain");
  11070. });
  11071. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11072. auto se = detail::scope_exit([&] {
  11073. svr.stop();
  11074. t.join();
  11075. });
  11076. svr.wait_until_ready();
  11077. SSLClient cli(HOST, PORT);
  11078. cli.enable_server_certificate_verification(false);
  11079. cli.set_connection_timeout(30);
  11080. bool callback_called = false;
  11081. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11082. EXPECT_NE(session, nullptr);
  11083. callback_called = true;
  11084. return SSLVerifierResponse::CertificateAccepted;
  11085. });
  11086. auto res = cli.Get("/test");
  11087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11088. EXPECT_EQ(200, res->status);
  11089. EXPECT_TRUE(callback_called);
  11090. }
  11091. TEST(SessionVerifierTest, CertificateRejected) {
  11092. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11093. ASSERT_TRUE(svr.is_valid());
  11094. svr.Get("/test", [](const Request &, Response &res) {
  11095. res.set_content("ok", "text/plain");
  11096. });
  11097. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11098. auto se = detail::scope_exit([&] {
  11099. svr.stop();
  11100. t.join();
  11101. });
  11102. svr.wait_until_ready();
  11103. SSLClient cli(HOST, PORT);
  11104. cli.enable_server_certificate_verification(false);
  11105. cli.set_connection_timeout(30);
  11106. bool callback_called = false;
  11107. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11108. EXPECT_NE(session, nullptr);
  11109. callback_called = true;
  11110. return SSLVerifierResponse::CertificateRejected;
  11111. });
  11112. auto res = cli.Get("/test");
  11113. EXPECT_FALSE(res);
  11114. EXPECT_TRUE(callback_called);
  11115. }
  11116. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  11117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11118. ASSERT_TRUE(svr.is_valid());
  11119. svr.Get("/test", [](const Request &, Response &res) {
  11120. res.set_content("ok", "text/plain");
  11121. });
  11122. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11123. auto se = detail::scope_exit([&] {
  11124. svr.stop();
  11125. t.join();
  11126. });
  11127. svr.wait_until_ready();
  11128. // NoDecisionMade with verification disabled should succeed (no default check)
  11129. SSLClient cli(HOST, PORT);
  11130. cli.enable_server_certificate_verification(false);
  11131. cli.set_connection_timeout(30);
  11132. bool callback_called = false;
  11133. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11134. EXPECT_NE(session, nullptr);
  11135. callback_called = true;
  11136. return SSLVerifierResponse::NoDecisionMade;
  11137. });
  11138. auto res = cli.Get("/test");
  11139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11140. EXPECT_EQ(200, res->status);
  11141. EXPECT_TRUE(callback_called);
  11142. }
  11143. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  11144. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11145. ASSERT_TRUE(svr.is_valid());
  11146. svr.Get("/test", [](const Request &, Response &res) {
  11147. res.set_content("ok", "text/plain");
  11148. });
  11149. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11150. auto se = detail::scope_exit([&] {
  11151. svr.stop();
  11152. t.join();
  11153. });
  11154. svr.wait_until_ready();
  11155. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11156. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11157. // so we only check that the request fails, not whether the callback was
  11158. // called.
  11159. SSLClient cli(HOST, PORT);
  11160. cli.enable_server_certificate_verification(true);
  11161. cli.set_connection_timeout(30);
  11162. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11163. EXPECT_NE(session, nullptr);
  11164. return SSLVerifierResponse::NoDecisionMade;
  11165. });
  11166. auto res = cli.Get("/test");
  11167. EXPECT_FALSE(res);
  11168. }
  11169. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11170. // Test SSL server using PemMemory constructor with client CA certificates
  11171. // Read PEM files
  11172. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11173. read_file(SERVER_CERT_FILE, server_cert_pem);
  11174. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11175. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11176. // Create SSLServer with PemMemory constructor including client CA
  11177. SSLServer::PemMemory server_pem = {
  11178. server_cert_pem.c_str(),
  11179. server_cert_pem.size(),
  11180. server_key_pem.c_str(),
  11181. server_key_pem.size(),
  11182. client_ca_pem.c_str(),
  11183. client_ca_pem.size(),
  11184. nullptr // no password for server key
  11185. };
  11186. SSLServer svr(server_pem);
  11187. ASSERT_TRUE(svr.is_valid());
  11188. // No SSL error should be recorded for valid setup
  11189. EXPECT_EQ(0, svr.ssl_last_error());
  11190. // Set up server endpoints
  11191. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11192. res.set_content("ok", "text/plain");
  11193. });
  11194. // Start server in a thread
  11195. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11196. svr.wait_until_ready();
  11197. // Connect with client certificate (using constructor with paths)
  11198. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11199. cli.enable_server_certificate_verification(false);
  11200. auto res = cli.Get("/test-pem-ca");
  11201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11202. EXPECT_EQ(200, res->status);
  11203. EXPECT_EQ("ok", res->body);
  11204. svr.stop();
  11205. server_thread.join();
  11206. }
  11207. #endif
  11208. #ifdef _WIN32
  11209. TEST(CleanupTest, WSACleanup) {
  11210. int ret = WSACleanup();
  11211. ASSERT_EQ(0, ret);
  11212. }
  11213. #endif
  11214. #ifndef CPPHTTPLIB_SSL_ENABLED
  11215. TEST(NoSSLSupport, SimpleInterface) {
  11216. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11217. }
  11218. #endif
  11219. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11220. TEST(InvalidScheme, SimpleInterface) {
  11221. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11222. }
  11223. #endif
  11224. TEST(NoScheme, SimpleInterface) {
  11225. Client cli("yahoo.com:80");
  11226. ASSERT_TRUE(cli.is_valid());
  11227. }
  11228. TEST(SendAPI, SimpleInterface_Online) {
  11229. Client cli("http://yahoo.com");
  11230. Request req;
  11231. req.method = "GET";
  11232. req.path = "/";
  11233. auto res = cli.send(req);
  11234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11235. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11236. }
  11237. TEST(SendAPI, WithParamsInRequest) {
  11238. Server svr;
  11239. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11240. EXPECT_TRUE(req.has_param("test"));
  11241. EXPECT_EQ("test_value", req.get_param_value("test"));
  11242. });
  11243. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11244. auto se = detail::scope_exit([&] {
  11245. svr.stop();
  11246. t.join();
  11247. ASSERT_FALSE(svr.is_running());
  11248. });
  11249. svr.wait_until_ready();
  11250. Client cli(HOST, PORT);
  11251. {
  11252. Request req;
  11253. req.method = "GET";
  11254. req.path = "/";
  11255. req.params.emplace("test", "test_value");
  11256. auto res = cli.send(req);
  11257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11258. }
  11259. {
  11260. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11262. }
  11263. }
  11264. TEST(ClientImplMethods, GetSocketTest) {
  11265. httplib::Server svr;
  11266. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11267. res.status = StatusCode::OK_200;
  11268. });
  11269. auto port = svr.bind_to_any_port("127.0.0.1");
  11270. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11271. auto se = detail::scope_exit([&] {
  11272. svr.stop();
  11273. thread.join();
  11274. ASSERT_FALSE(svr.is_running());
  11275. });
  11276. svr.wait_until_ready();
  11277. {
  11278. httplib::Client cli("127.0.0.1", port);
  11279. cli.set_keep_alive(true);
  11280. // Use the behavior of cpp-httplib of opening the connection
  11281. // only when the first request happens. If that changes,
  11282. // this test would be obsolete.
  11283. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11284. // This also implicitly tests the server. But other tests would fail much
  11285. // earlier than this one to be considered.
  11286. auto res = cli.Get("/");
  11287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11288. EXPECT_EQ(StatusCode::OK_200, res->status);
  11289. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11290. }
  11291. }
  11292. #ifdef CPPHTTPLIB_SSL_ENABLED
  11293. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11294. Client cli("http://yahoo.com");
  11295. auto res = cli.Get("/");
  11296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11297. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11298. cli.set_follow_location(true);
  11299. res = cli.Get("/");
  11300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11301. EXPECT_EQ(StatusCode::OK_200, res->status);
  11302. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11303. }
  11304. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11305. Client cli("https://yahoo.com");
  11306. auto res = cli.Get("/");
  11307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11308. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11309. cli.set_follow_location(true);
  11310. res = cli.Get("/");
  11311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11312. EXPECT_EQ(StatusCode::OK_200, res->status);
  11313. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11314. }
  11315. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11316. Client cli("https://yahoo.com");
  11317. auto res = cli.Get("/");
  11318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11319. ASSERT_FALSE(!res);
  11320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11321. ASSERT_FALSE(res == nullptr);
  11322. ASSERT_TRUE(res != nullptr);
  11323. EXPECT_EQ(Error::Success, res.error());
  11324. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11325. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11326. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11327. cli.set_follow_location(true);
  11328. res = cli.Get("/");
  11329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11330. EXPECT_EQ(Error::Success, res.error());
  11331. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11332. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11333. EXPECT_EQ(StatusCode::OK_200, res->status);
  11334. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11335. }
  11336. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11337. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11338. Client cli("https://cdnjs.cloudflare.com");
  11339. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11340. Headers{{"Accept-Encoding", "br"}});
  11341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11342. EXPECT_EQ(StatusCode::OK_200, res->status);
  11343. EXPECT_EQ(287630U, res->body.size());
  11344. EXPECT_EQ("application/javascript; charset=utf-8",
  11345. res->get_header_value("Content-Type"));
  11346. }
  11347. #endif
  11348. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11349. #undef REDIR_HOST // Silence compiler warning
  11350. #define REDIR_HOST "https://httpbingo.org"
  11351. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11352. Client cli(REDIR_HOST);
  11353. cli.set_follow_location(true);
  11354. auto res =
  11355. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11357. EXPECT_EQ(StatusCode::OK_200, res->status);
  11358. }
  11359. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11360. Client cli(REDIR_HOST);
  11361. cli.set_follow_location(true);
  11362. Params params;
  11363. params.emplace("url", "http://example.com");
  11364. params.emplace("status_code", "302");
  11365. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11367. EXPECT_EQ(StatusCode::OK_200, res->status);
  11368. }
  11369. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11370. Client cli(REDIR_HOST);
  11371. cli.set_follow_location(true);
  11372. Params params;
  11373. params.emplace("url", "http://example.com");
  11374. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11376. EXPECT_EQ(StatusCode::OK_200, res->status);
  11377. }
  11378. TEST(HttpToHttpsRedirectTest, CertFile) {
  11379. auto ssl_port = PORT + 1;
  11380. Server svr;
  11381. ASSERT_TRUE(svr.is_valid());
  11382. svr.Get("/index", [&](const Request &, Response &res) {
  11383. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11384. "/index");
  11385. svr.stop();
  11386. });
  11387. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11388. ASSERT_TRUE(ssl_svr.is_valid());
  11389. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11390. res.set_content("test", "text/plain");
  11391. ssl_svr.stop();
  11392. });
  11393. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11394. thread t2 =
  11395. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11396. auto se = detail::scope_exit([&] {
  11397. t2.join();
  11398. t.join();
  11399. ASSERT_FALSE(svr.is_running());
  11400. });
  11401. svr.wait_until_ready();
  11402. ssl_svr.wait_until_ready();
  11403. Client cli("127.0.0.1", PORT);
  11404. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11405. cli.enable_server_certificate_verification(true);
  11406. cli.set_follow_location(true);
  11407. cli.set_connection_timeout(30);
  11408. auto res = cli.Get("/index");
  11409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11410. ASSERT_EQ(StatusCode::OK_200, res->status);
  11411. }
  11412. TEST(SSLClientRedirectTest, CertFile) {
  11413. auto ssl_port = PORT + 1;
  11414. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11415. ASSERT_TRUE(ssl_svr1.is_valid());
  11416. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11417. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11418. "/index");
  11419. ssl_svr1.stop();
  11420. });
  11421. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11422. ASSERT_TRUE(ssl_svr2.is_valid());
  11423. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11424. res.set_content("test", "text/plain");
  11425. ssl_svr2.stop();
  11426. });
  11427. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11428. thread t2 =
  11429. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11430. auto se = detail::scope_exit([&] {
  11431. t2.join();
  11432. t.join();
  11433. ASSERT_FALSE(ssl_svr1.is_running());
  11434. });
  11435. ssl_svr1.wait_until_ready();
  11436. ssl_svr2.wait_until_ready();
  11437. SSLClient cli("127.0.0.1", PORT);
  11438. std::string cert;
  11439. read_file(SERVER_CERT2_FILE, cert);
  11440. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11441. cli.enable_server_certificate_verification(true);
  11442. cli.set_follow_location(true);
  11443. cli.set_connection_timeout(30);
  11444. auto res = cli.Get("/index");
  11445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11446. ASSERT_EQ(StatusCode::OK_200, res->status);
  11447. }
  11448. #endif
  11449. #ifdef CPPHTTPLIB_SSL_ENABLED
  11450. // Test that set_ca_cert_store() skips system certs (consistent with
  11451. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11452. // should be trusted - system certs should NOT be loaded.
  11453. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11454. // Load a specific cert that is NOT a system CA cert
  11455. std::string cert;
  11456. read_file(SERVER_CERT2_FILE, cert);
  11457. SSLClient cli("google.com");
  11458. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11459. cli.enable_server_certificate_verification(true);
  11460. // This should FAIL because:
  11461. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11462. // 2. System certs should NOT be loaded when custom store is set
  11463. // If system certs WERE loaded, this would succeed
  11464. auto res = cli.Get("/");
  11465. ASSERT_FALSE(res);
  11466. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11467. }
  11468. // Same as above, but through the native store handle path. Regression test:
  11469. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11470. // merged system certs into the user-provided store.
  11471. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11472. std::string cert;
  11473. read_file(SERVER_CERT2_FILE, cert);
  11474. SSLClient cli("google.com");
  11475. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11476. cli.enable_server_certificate_verification(true);
  11477. auto res = cli.Get("/");
  11478. ASSERT_FALSE(res);
  11479. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11480. }
  11481. // A custom store set via the native handle must still verify a server whose
  11482. // cert it does contain.
  11483. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11484. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11485. ASSERT_TRUE(svr.is_valid());
  11486. svr.Get("/test", [&](const Request &, Response &res) {
  11487. res.set_content("test", "text/plain");
  11488. });
  11489. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11490. auto se = detail::scope_exit([&] {
  11491. svr.stop();
  11492. t.join();
  11493. ASSERT_FALSE(svr.is_running());
  11494. });
  11495. svr.wait_until_ready();
  11496. SSLClient cli("127.0.0.1", PORT);
  11497. std::string cert;
  11498. read_file(SERVER_CERT2_FILE, cert);
  11499. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11500. cli.enable_server_certificate_verification(true);
  11501. cli.set_connection_timeout(30);
  11502. auto res = cli.Get("/test");
  11503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11504. ASSERT_EQ(StatusCode::OK_200, res->status);
  11505. }
  11506. // CA certs loaded through the universal Client must be transferred to the
  11507. // client created internally for following an HTTPS redirect. Regression test:
  11508. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11509. // the CA data for redirect transfer.
  11510. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11511. auto ssl_port = PORT + 1;
  11512. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11513. ASSERT_TRUE(ssl_svr1.is_valid());
  11514. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11515. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11516. "/index");
  11517. });
  11518. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11519. ASSERT_TRUE(ssl_svr2.is_valid());
  11520. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11521. res.set_content("test", "text/plain");
  11522. });
  11523. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11524. thread t2 =
  11525. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11526. auto se = detail::scope_exit([&] {
  11527. ssl_svr2.stop();
  11528. ssl_svr1.stop();
  11529. t2.join();
  11530. t.join();
  11531. ASSERT_FALSE(ssl_svr1.is_running());
  11532. });
  11533. ssl_svr1.wait_until_ready();
  11534. ssl_svr2.wait_until_ready();
  11535. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11536. std::string cert;
  11537. read_file(SERVER_CERT2_FILE, cert);
  11538. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11539. cli.enable_server_certificate_verification(true);
  11540. cli.set_follow_location(true);
  11541. cli.set_connection_timeout(30);
  11542. auto res = cli.Get("/index");
  11543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11544. ASSERT_EQ(StatusCode::OK_200, res->status);
  11545. }
  11546. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11547. // so a host signed by a system CA verifies even though a custom CA is set
  11548. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11549. std::string cert;
  11550. read_file(SERVER_CERT2_FILE, cert);
  11551. SSLClient cli("google.com");
  11552. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11553. cli.enable_system_ca(true);
  11554. cli.enable_server_certificate_verification(true);
  11555. auto res = cli.Get("/");
  11556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11557. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11558. }
  11559. // The custom CA remains effective when combined with the system CA
  11560. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11561. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11562. ASSERT_TRUE(svr.is_valid());
  11563. svr.Get("/test", [&](const Request &, Response &res) {
  11564. res.set_content("test", "text/plain");
  11565. });
  11566. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11567. auto se = detail::scope_exit([&] {
  11568. svr.stop();
  11569. t.join();
  11570. ASSERT_FALSE(svr.is_running());
  11571. });
  11572. svr.wait_until_ready();
  11573. SSLClient cli("127.0.0.1", PORT);
  11574. std::string cert;
  11575. read_file(SERVER_CERT2_FILE, cert);
  11576. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11577. cli.enable_system_ca(true);
  11578. cli.enable_server_certificate_verification(true);
  11579. cli.set_connection_timeout(30);
  11580. auto res = cli.Get("/test");
  11581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11582. ASSERT_EQ(StatusCode::OK_200, res->status);
  11583. }
  11584. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11585. // skip chain verification entirely (only the certificate identity was
  11586. // checked), so a server presenting an untrusted certificate with a matching
  11587. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11588. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11589. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11590. ASSERT_TRUE(svr.is_valid());
  11591. svr.Get("/test", [&](const Request &, Response &res) {
  11592. res.set_content("test", "text/plain");
  11593. });
  11594. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11595. auto se = detail::scope_exit([&] {
  11596. svr.stop();
  11597. t.join();
  11598. ASSERT_FALSE(svr.is_running());
  11599. });
  11600. svr.wait_until_ready();
  11601. SSLClient cli("127.0.0.1", PORT);
  11602. std::string cert;
  11603. // A trusted CA that did not sign the server certificate. The server cert
  11604. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11605. // this connection.
  11606. read_file(CLIENT_CA_CERT_FILE, cert);
  11607. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11608. cli.enable_server_certificate_verification(true);
  11609. cli.set_connection_timeout(30);
  11610. auto res = cli.Get("/test");
  11611. ASSERT_FALSE(res);
  11612. }
  11613. // enable_system_ca(false) prevents system CA loading entirely
  11614. TEST(SSLClientTest, DisableSystemCa_Online) {
  11615. SSLClient cli("google.com");
  11616. cli.enable_system_ca(false);
  11617. cli.enable_server_certificate_verification(true);
  11618. auto res = cli.Get("/");
  11619. ASSERT_FALSE(res);
  11620. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11621. // itself when the CA chain is empty
  11622. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11623. res.error() == Error::SSLConnection);
  11624. }
  11625. // The universal Client forwards enable_system_ca()
  11626. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11627. std::string cert;
  11628. read_file(SERVER_CERT2_FILE, cert);
  11629. Client cli("https://google.com");
  11630. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11631. cli.enable_system_ca(true);
  11632. cli.enable_server_certificate_verification(true);
  11633. auto res = cli.Get("/");
  11634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11635. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11636. }
  11637. // The system CA policy must carry over to the client created internally for
  11638. // following a cross-host HTTPS redirect
  11639. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11640. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11641. ASSERT_TRUE(svr.is_valid());
  11642. svr.Get("/index", [&](const Request &, Response &res) {
  11643. res.set_redirect("https://www.google.com/");
  11644. });
  11645. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11646. auto se = detail::scope_exit([&] {
  11647. svr.stop();
  11648. t.join();
  11649. ASSERT_FALSE(svr.is_running());
  11650. });
  11651. svr.wait_until_ready();
  11652. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11653. std::string cert;
  11654. read_file(SERVER_CERT2_FILE, cert);
  11655. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11656. cli.enable_system_ca(true);
  11657. cli.enable_server_certificate_verification(true);
  11658. cli.set_follow_location(true);
  11659. cli.set_connection_timeout(30);
  11660. // Receiving any response proves the redirect client completed the TLS
  11661. // handshake with a system-CA-signed host
  11662. auto res = cli.Get("/index");
  11663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11664. }
  11665. TEST(MultipartFormDataTest, LargeData) {
  11666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11667. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11668. const ContentReader &content_reader) {
  11669. if (req.is_multipart_form_data()) {
  11670. std::vector<FormData> items;
  11671. content_reader(
  11672. [&](const FormData &file) {
  11673. items.push_back(file);
  11674. return true;
  11675. },
  11676. [&](const char *data, size_t data_length) {
  11677. items.back().content.append(data, data_length);
  11678. return true;
  11679. });
  11680. EXPECT_TRUE(std::string(items[0].name) == "document");
  11681. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11682. EXPECT_TRUE(items[0].filename == "2MB_data");
  11683. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11684. EXPECT_TRUE(items[1].name == "hello");
  11685. EXPECT_TRUE(items[1].content == "world");
  11686. EXPECT_TRUE(items[1].filename == "");
  11687. EXPECT_TRUE(items[1].content_type == "");
  11688. } else {
  11689. std::string body;
  11690. content_reader([&](const char *data, size_t data_length) {
  11691. body.append(data, data_length);
  11692. return true;
  11693. });
  11694. }
  11695. });
  11696. auto port = svr.bind_to_any_port(HOST);
  11697. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11698. auto se = detail::scope_exit([&] {
  11699. svr.stop();
  11700. t.join();
  11701. ASSERT_FALSE(svr.is_running());
  11702. });
  11703. svr.wait_until_ready();
  11704. {
  11705. std::string data(1024 * 1024 * 2, '.');
  11706. std::stringstream buffer;
  11707. buffer << data;
  11708. SSLClient cli(HOST, port);
  11709. cli.enable_server_certificate_verification(false);
  11710. UploadFormDataItems items{
  11711. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11712. {"hello", "world", "", ""},
  11713. };
  11714. auto res = cli.Post("/post", items);
  11715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11716. ASSERT_EQ(StatusCode::OK_200, res->status);
  11717. }
  11718. }
  11719. TEST(MultipartFormDataTest, DataProviderItems) {
  11720. std::random_device seed_gen;
  11721. std::mt19937 random(seed_gen());
  11722. std::string rand1;
  11723. rand1.resize(1000);
  11724. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11725. std::string rand2;
  11726. rand2.resize(3000);
  11727. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11728. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11729. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11730. const ContentReader &content_reader) {
  11731. ASSERT_FALSE(req.is_multipart_form_data());
  11732. std::string body;
  11733. content_reader([&](const char *data, size_t data_length) {
  11734. body.append(data, data_length);
  11735. return true;
  11736. });
  11737. EXPECT_EQ(body, "");
  11738. });
  11739. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11740. const ContentReader &content_reader) {
  11741. ASSERT_TRUE(req.is_multipart_form_data());
  11742. std::vector<FormData> items;
  11743. content_reader(
  11744. [&](const FormData &file) {
  11745. items.push_back(file);
  11746. return true;
  11747. },
  11748. [&](const char *data, size_t data_length) {
  11749. items.back().content.append(data, data_length);
  11750. return true;
  11751. });
  11752. ASSERT_TRUE(items.size() == 2);
  11753. EXPECT_EQ(std::string(items[0].name), "name1");
  11754. EXPECT_EQ(items[0].content, "Testing123");
  11755. EXPECT_EQ(items[0].filename, "filename1");
  11756. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11757. EXPECT_EQ(items[1].name, "name2");
  11758. EXPECT_EQ(items[1].content, "Testing456");
  11759. EXPECT_EQ(items[1].filename, "");
  11760. EXPECT_EQ(items[1].content_type, "");
  11761. });
  11762. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11763. const ContentReader &content_reader) {
  11764. ASSERT_TRUE(req.is_multipart_form_data());
  11765. std::vector<FormData> items;
  11766. content_reader(
  11767. [&](const FormData &file) {
  11768. items.push_back(file);
  11769. return true;
  11770. },
  11771. [&](const char *data, size_t data_length) {
  11772. items.back().content.append(data, data_length);
  11773. return true;
  11774. });
  11775. ASSERT_TRUE(items.size() == 2);
  11776. EXPECT_EQ(items[0].name, "name3");
  11777. EXPECT_EQ(items[0].content, rand1);
  11778. EXPECT_EQ(items[0].filename, "filename3");
  11779. EXPECT_EQ(items[0].content_type, "");
  11780. EXPECT_EQ(items[1].name, "name4");
  11781. EXPECT_EQ(items[1].content, rand2);
  11782. EXPECT_EQ(items[1].filename, "filename4");
  11783. EXPECT_EQ(items[1].content_type, "");
  11784. });
  11785. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11786. const ContentReader &content_reader) {
  11787. ASSERT_TRUE(req.is_multipart_form_data());
  11788. std::vector<FormData> items;
  11789. content_reader(
  11790. [&](const FormData &file) {
  11791. items.push_back(file);
  11792. return true;
  11793. },
  11794. [&](const char *data, size_t data_length) {
  11795. items.back().content.append(data, data_length);
  11796. return true;
  11797. });
  11798. ASSERT_TRUE(items.size() == 4);
  11799. EXPECT_EQ(std::string(items[0].name), "name1");
  11800. EXPECT_EQ(items[0].content, "Testing123");
  11801. EXPECT_EQ(items[0].filename, "filename1");
  11802. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11803. EXPECT_EQ(items[1].name, "name2");
  11804. EXPECT_EQ(items[1].content, "Testing456");
  11805. EXPECT_EQ(items[1].filename, "");
  11806. EXPECT_EQ(items[1].content_type, "");
  11807. EXPECT_EQ(items[2].name, "name3");
  11808. EXPECT_EQ(items[2].content, rand1);
  11809. EXPECT_EQ(items[2].filename, "filename3");
  11810. EXPECT_EQ(items[2].content_type, "");
  11811. EXPECT_EQ(items[3].name, "name4");
  11812. EXPECT_EQ(items[3].content, rand2);
  11813. EXPECT_EQ(items[3].filename, "filename4");
  11814. EXPECT_EQ(items[3].content_type, "");
  11815. });
  11816. auto port = svr.bind_to_any_port("localhost");
  11817. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11818. auto se = detail::scope_exit([&] {
  11819. svr.stop();
  11820. t.join();
  11821. ASSERT_FALSE(svr.is_running());
  11822. });
  11823. svr.wait_until_ready();
  11824. {
  11825. SSLClient cli("localhost", port);
  11826. cli.enable_server_certificate_verification(false);
  11827. UploadFormDataItems items{
  11828. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11829. {"name2", "Testing456", "", ""}, // not a file
  11830. };
  11831. {
  11832. auto res = cli.Post("/post-none", {}, {}, {});
  11833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11834. ASSERT_EQ(StatusCode::OK_200, res->status);
  11835. }
  11836. FormDataProviderItems providers;
  11837. {
  11838. auto res =
  11839. cli.Post("/post-items", {}, items, providers); // empty providers
  11840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11841. ASSERT_EQ(StatusCode::OK_200, res->status);
  11842. }
  11843. providers.push_back({"name3",
  11844. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11845. // test the offset is given correctly at each step
  11846. if (!offset)
  11847. sink.os.write(rand1.data(), 30);
  11848. else if (offset == 30)
  11849. sink.os.write(rand1.data() + 30, 300);
  11850. else if (offset == 330)
  11851. sink.os.write(rand1.data() + 330, 670);
  11852. else if (offset == rand1.size())
  11853. sink.done();
  11854. return true;
  11855. },
  11856. "filename3",
  11857. {}});
  11858. providers.push_back({"name4",
  11859. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11860. // test the offset is given correctly at each step
  11861. if (!offset)
  11862. sink.os.write(rand2.data(), 2000);
  11863. else if (offset == 2000)
  11864. sink.os.write(rand2.data() + 2000, 1);
  11865. else if (offset == 2001)
  11866. sink.os.write(rand2.data() + 2001, 999);
  11867. else if (offset == rand2.size())
  11868. sink.done();
  11869. return true;
  11870. },
  11871. "filename4",
  11872. {}});
  11873. {
  11874. auto res = cli.Post("/post-providers", {}, {}, providers);
  11875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11876. ASSERT_EQ(StatusCode::OK_200, res->status);
  11877. }
  11878. {
  11879. auto res = cli.Post("/post-both", {}, items, providers);
  11880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11881. ASSERT_EQ(StatusCode::OK_200, res->status);
  11882. }
  11883. }
  11884. }
  11885. TEST(MultipartFormDataTest, BadHeader) {
  11886. Server svr;
  11887. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11888. res.set_content("ok", "text/plain");
  11889. });
  11890. thread t = thread([&] { svr.listen(HOST, PORT); });
  11891. auto se = detail::scope_exit([&] {
  11892. svr.stop();
  11893. t.join();
  11894. ASSERT_FALSE(svr.is_running());
  11895. });
  11896. svr.wait_until_ready();
  11897. const std::string body =
  11898. "This is the preamble. It is to be ignored, though it\r\n"
  11899. "is a handy place for composition agents to include an\r\n"
  11900. "explanatory note to non-MIME conformant readers.\r\n"
  11901. "\r\n"
  11902. "\r\n"
  11903. "--simple boundary\r\n"
  11904. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11905. ": BAD...\r\n"
  11906. "\r\n"
  11907. "value1\r\n"
  11908. "--simple boundary\r\n"
  11909. "Content-Disposition: form-data; name=\"field2\"; "
  11910. "filename=\"example.txt\"\r\n"
  11911. "\r\n"
  11912. "value2\r\n"
  11913. "--simple boundary--\r\n"
  11914. "This is the epilogue. It is also to be ignored.\r\n";
  11915. std::string content_type =
  11916. R"(multipart/form-data; boundary="simple boundary")";
  11917. Client cli(HOST, PORT);
  11918. auto res = cli.Post("/post", body, content_type.c_str());
  11919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11920. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11921. }
  11922. TEST(MultipartFormDataTest, WithPreamble) {
  11923. Server svr;
  11924. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11925. res.set_content("ok", "text/plain");
  11926. });
  11927. thread t = thread([&] { svr.listen(HOST, PORT); });
  11928. auto se = detail::scope_exit([&] {
  11929. svr.stop();
  11930. t.join();
  11931. ASSERT_FALSE(svr.is_running());
  11932. });
  11933. svr.wait_until_ready();
  11934. const std::string body =
  11935. "This is the preamble. It is to be ignored, though it\r\n"
  11936. "is a handy place for composition agents to include an\r\n"
  11937. "explanatory note to non-MIME conformant readers.\r\n"
  11938. "\r\n"
  11939. "\r\n"
  11940. "--simple boundary\r\n"
  11941. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11942. "\r\n"
  11943. "value1\r\n"
  11944. "--simple boundary\r\n"
  11945. "Content-Disposition: form-data; name=\"field2\"; "
  11946. "filename=\"example.txt\"\r\n"
  11947. "\r\n"
  11948. "value2\r\n"
  11949. "--simple boundary--\r\n"
  11950. "This is the epilogue. It is also to be ignored.\r\n";
  11951. std::string content_type =
  11952. R"(multipart/form-data; boundary="simple boundary")";
  11953. Client cli(HOST, PORT);
  11954. auto res = cli.Post("/post", body, content_type.c_str());
  11955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11956. EXPECT_EQ(StatusCode::OK_200, res->status);
  11957. }
  11958. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11959. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11960. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11961. const ContentReader &content_reader) {
  11962. if (req.is_multipart_form_data()) {
  11963. std::vector<FormData> items;
  11964. content_reader(
  11965. [&](const FormData &file) {
  11966. items.push_back(file);
  11967. return true;
  11968. },
  11969. [&](const char *data, size_t data_length) {
  11970. items.back().content.append(data, data_length);
  11971. return true;
  11972. });
  11973. EXPECT_TRUE(std::string(items[0].name) == "document");
  11974. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11975. EXPECT_TRUE(items[0].filename == "2MB_data");
  11976. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11977. EXPECT_TRUE(items[1].name == "hello");
  11978. EXPECT_TRUE(items[1].content == "world");
  11979. EXPECT_TRUE(items[1].filename == "");
  11980. EXPECT_TRUE(items[1].content_type == "");
  11981. } else {
  11982. std::string body;
  11983. content_reader([&](const char *data, size_t data_length) {
  11984. body.append(data, data_length);
  11985. return true;
  11986. });
  11987. }
  11988. });
  11989. auto port = svr.bind_to_any_port("localhost");
  11990. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11991. auto se = detail::scope_exit([&] {
  11992. svr.stop();
  11993. t.join();
  11994. ASSERT_FALSE(svr.is_running());
  11995. });
  11996. svr.wait_until_ready();
  11997. {
  11998. std::string data(1024 * 1024 * 2, '.');
  11999. std::stringstream buffer;
  12000. buffer << data;
  12001. SSLClient cli("localhost", port);
  12002. cli.enable_server_certificate_verification(false);
  12003. UploadFormDataItems items{
  12004. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12005. {"hello", "world", "", ""},
  12006. };
  12007. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  12008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12009. ASSERT_EQ(StatusCode::OK_200, res->status);
  12010. }
  12011. }
  12012. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  12013. std::string data(1024 * 1024 * 2, '&');
  12014. std::stringstream buffer;
  12015. buffer << data;
  12016. Client cli("https://localhost:8080");
  12017. UploadFormDataItems items{
  12018. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12019. {"hello", "world", "", ""},
  12020. };
  12021. for (const char &c : " \t\r\n") {
  12022. auto res =
  12023. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  12024. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12025. ASSERT_FALSE(res);
  12026. }
  12027. }
  12028. TEST(MultipartFormDataTest, PutFormData) {
  12029. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12030. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  12031. const ContentReader &content_reader) {
  12032. if (req.is_multipart_form_data()) {
  12033. std::vector<FormData> items;
  12034. content_reader(
  12035. [&](const FormData &file) {
  12036. items.push_back(file);
  12037. return true;
  12038. },
  12039. [&](const char *data, size_t data_length) {
  12040. items.back().content.append(data, data_length);
  12041. return true;
  12042. });
  12043. EXPECT_TRUE(std::string(items[0].name) == "document");
  12044. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12045. EXPECT_TRUE(items[0].filename == "2MB_data");
  12046. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12047. EXPECT_TRUE(items[1].name == "hello");
  12048. EXPECT_TRUE(items[1].content == "world");
  12049. EXPECT_TRUE(items[1].filename == "");
  12050. EXPECT_TRUE(items[1].content_type == "");
  12051. } else {
  12052. std::string body;
  12053. content_reader([&](const char *data, size_t data_length) {
  12054. body.append(data, data_length);
  12055. return true;
  12056. });
  12057. }
  12058. });
  12059. auto port = svr.bind_to_any_port("localhost");
  12060. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12061. auto se = detail::scope_exit([&] {
  12062. svr.stop();
  12063. t.join();
  12064. ASSERT_FALSE(svr.is_running());
  12065. });
  12066. svr.wait_until_ready();
  12067. {
  12068. std::string data(1024 * 1024 * 2, '&');
  12069. std::stringstream buffer;
  12070. buffer << data;
  12071. SSLClient cli("localhost", port);
  12072. cli.enable_server_certificate_verification(false);
  12073. UploadFormDataItems items{
  12074. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12075. {"hello", "world", "", ""},
  12076. };
  12077. auto res = cli.Put("/put", items);
  12078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12079. ASSERT_EQ(StatusCode::OK_200, res->status);
  12080. }
  12081. }
  12082. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  12083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12084. svr.Put("/put_customboundary",
  12085. [&](const Request &req, const Response & /*res*/,
  12086. const ContentReader &content_reader) {
  12087. if (req.is_multipart_form_data()) {
  12088. std::vector<FormData> items;
  12089. content_reader(
  12090. [&](const FormData &file) {
  12091. items.push_back(file);
  12092. return true;
  12093. },
  12094. [&](const char *data, size_t data_length) {
  12095. items.back().content.append(data, data_length);
  12096. return true;
  12097. });
  12098. EXPECT_TRUE(std::string(items[0].name) == "document");
  12099. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12100. EXPECT_TRUE(items[0].filename == "2MB_data");
  12101. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12102. EXPECT_TRUE(items[1].name == "hello");
  12103. EXPECT_TRUE(items[1].content == "world");
  12104. EXPECT_TRUE(items[1].filename == "");
  12105. EXPECT_TRUE(items[1].content_type == "");
  12106. } else {
  12107. std::string body;
  12108. content_reader([&](const char *data, size_t data_length) {
  12109. body.append(data, data_length);
  12110. return true;
  12111. });
  12112. }
  12113. });
  12114. auto port = svr.bind_to_any_port("localhost");
  12115. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12116. auto se = detail::scope_exit([&] {
  12117. svr.stop();
  12118. t.join();
  12119. ASSERT_FALSE(svr.is_running());
  12120. });
  12121. svr.wait_until_ready();
  12122. {
  12123. std::string data(1024 * 1024 * 2, '&');
  12124. std::stringstream buffer;
  12125. buffer << data;
  12126. SSLClient cli("localhost", port);
  12127. cli.enable_server_certificate_verification(false);
  12128. UploadFormDataItems items{
  12129. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12130. {"hello", "world", "", ""},
  12131. };
  12132. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  12133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12134. ASSERT_EQ(StatusCode::OK_200, res->status);
  12135. }
  12136. }
  12137. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  12138. std::string data(1024 * 1024 * 2, '&');
  12139. std::stringstream buffer;
  12140. buffer << data;
  12141. Client cli("https://localhost:8080");
  12142. cli.enable_server_certificate_verification(false);
  12143. UploadFormDataItems items{
  12144. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12145. {"hello", "world", "", ""},
  12146. };
  12147. for (const char &c : " \t\r\n") {
  12148. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  12149. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  12150. ASSERT_FALSE(res);
  12151. }
  12152. }
  12153. TEST(MultipartFormDataTest, AlternateFilename) {
  12154. auto handled = false;
  12155. Server svr;
  12156. svr.Post("/test", [&](const Request &req, Response &res) {
  12157. ASSERT_EQ(2u, req.form.files.size());
  12158. ASSERT_EQ(1u, req.form.fields.size());
  12159. // Test files
  12160. const auto &file1 = req.form.get_file("file1");
  12161. ASSERT_EQ("file1", file1.name);
  12162. ASSERT_EQ("A.txt", file1.filename);
  12163. ASSERT_EQ("text/plain", file1.content_type);
  12164. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12165. const auto &file2 = req.form.get_file("file2");
  12166. ASSERT_EQ("file2", file2.name);
  12167. ASSERT_EQ("a.html", file2.filename);
  12168. ASSERT_EQ("text/html", file2.content_type);
  12169. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12170. file2.content);
  12171. // Test text field
  12172. const auto &text = req.form.get_field("text");
  12173. ASSERT_EQ("text default", text);
  12174. res.set_content("ok", "text/plain");
  12175. handled = true;
  12176. });
  12177. thread t = thread([&] { svr.listen(HOST, PORT); });
  12178. auto se = detail::scope_exit([&] {
  12179. svr.stop();
  12180. t.join();
  12181. ASSERT_FALSE(svr.is_running());
  12182. ASSERT_TRUE(handled);
  12183. });
  12184. svr.wait_until_ready();
  12185. auto req = "POST /test HTTP/1.1\r\n"
  12186. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12187. "Content-Length: 399\r\n"
  12188. "\r\n"
  12189. "----------\r\n"
  12190. "Content-Disposition: form-data; name=\"text\"\r\n"
  12191. "\r\n"
  12192. "text default\r\n"
  12193. "----------\r\n"
  12194. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12195. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12196. "Content-Type: text/plain\r\n"
  12197. "\r\n"
  12198. "Content of a.txt.\r\n"
  12199. "\r\n"
  12200. "----------\r\n"
  12201. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12202. "\"a.html\"\r\n"
  12203. "Content-Type: text/html\r\n"
  12204. "\r\n"
  12205. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12206. "\r\n"
  12207. "------------\r\n";
  12208. ASSERT_TRUE(send_request(1, req));
  12209. }
  12210. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12211. auto handled = false;
  12212. Server svr;
  12213. svr.Post("/test", [&](const Request &req, Response &res) {
  12214. // Case-insensitive "utf-8''" prefix with a long value
  12215. const auto &file = req.form.get_file("file1");
  12216. ASSERT_EQ("file1", file.name);
  12217. // 8000 chars exercises both the Content-Disposition parser and the
  12218. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12219. // Prior to the fix, std::regex_match on this header would cause O(N)
  12220. // stack recursion in libstdc++, leading to SIGSEGV.
  12221. std::string expected_filename(8000, 'A');
  12222. ASSERT_EQ(expected_filename, file.filename);
  12223. res.set_content("ok", "text/plain");
  12224. handled = true;
  12225. });
  12226. thread t = thread([&] { svr.listen(HOST, PORT); });
  12227. auto se = detail::scope_exit([&] {
  12228. svr.stop();
  12229. t.join();
  12230. ASSERT_FALSE(svr.is_running());
  12231. ASSERT_TRUE(handled);
  12232. });
  12233. svr.wait_until_ready();
  12234. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12235. // Regression test for GHSA-qq6v-r583-3h69
  12236. std::string long_filename(8000, 'A');
  12237. std::string body = "----------\r\n"
  12238. "Content-Disposition: form-data; name=\"file1\"; "
  12239. "filename*=\"Utf-8''" +
  12240. long_filename +
  12241. "\"\r\n"
  12242. "\r\n"
  12243. "hello\r\n"
  12244. "------------\r\n";
  12245. auto req = "POST /test HTTP/1.1\r\n"
  12246. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12247. "Content-Length: " +
  12248. std::to_string(body.size()) + "\r\n\r\n" + body;
  12249. ASSERT_TRUE(send_request(1, req));
  12250. }
  12251. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12252. auto handled = false;
  12253. Server svr;
  12254. svr.Post("/test", [&](const Request &req, Response &) {
  12255. ASSERT_EQ(2u, req.form.fields.size());
  12256. const auto &text1 = req.form.get_field("text1");
  12257. ASSERT_EQ("text1", text1);
  12258. const auto &text2 = req.form.get_field("text2");
  12259. ASSERT_EQ("text2", text2);
  12260. handled = true;
  12261. });
  12262. thread t = thread([&] { svr.listen(HOST, PORT); });
  12263. auto se = detail::scope_exit([&] {
  12264. svr.stop();
  12265. t.join();
  12266. ASSERT_FALSE(svr.is_running());
  12267. ASSERT_TRUE(handled);
  12268. });
  12269. svr.wait_until_ready();
  12270. auto req = "POST /test HTTP/1.1\r\n"
  12271. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12272. "Content-Length: 146\r\n"
  12273. "\r\n----------\r\n"
  12274. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12275. "\r\n"
  12276. "text1"
  12277. "\r\n----------\r\n"
  12278. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12279. "\r\n"
  12280. "text2"
  12281. "\r\n------------";
  12282. std::string response;
  12283. ASSERT_TRUE(send_request(1, req, &response));
  12284. ASSERT_EQ("200", response.substr(9, 3));
  12285. }
  12286. TEST(MultipartFormDataTest, ContentLength) {
  12287. auto handled = false;
  12288. Server svr;
  12289. svr.Post("/test", [&](const Request &req, Response &) {
  12290. ASSERT_EQ(2u, req.form.fields.size());
  12291. const auto &text1 = req.form.get_field("text1");
  12292. ASSERT_EQ("text1", text1);
  12293. const auto &text2 = req.form.get_field("text2");
  12294. ASSERT_EQ("text2", text2);
  12295. handled = true;
  12296. });
  12297. thread t = thread([&] { svr.listen(HOST, PORT); });
  12298. auto se = detail::scope_exit([&] {
  12299. svr.stop();
  12300. t.join();
  12301. ASSERT_FALSE(svr.is_running());
  12302. ASSERT_TRUE(handled);
  12303. });
  12304. svr.wait_until_ready();
  12305. auto req = "POST /test HTTP/1.1\r\n"
  12306. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12307. "Content-Length: 167\r\n"
  12308. "\r\n----------\r\n"
  12309. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12310. "Content-Length: 5\r\n"
  12311. "\r\n"
  12312. "text1"
  12313. "\r\n----------\r\n"
  12314. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12315. "\r\n"
  12316. "text2"
  12317. "\r\n------------\r\n";
  12318. std::string response;
  12319. ASSERT_TRUE(send_request(1, req, &response));
  12320. ASSERT_EQ("200", response.substr(9, 3));
  12321. }
  12322. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12323. auto handled = false;
  12324. Server svr;
  12325. svr.Post("/test", [&](const Request &req, Response &) {
  12326. ASSERT_EQ(2u, req.form.fields.size());
  12327. const auto &text1 = req.form.get_field("text1");
  12328. ASSERT_EQ("text1", text1);
  12329. // TODO: Add header access for text fields if needed
  12330. const auto &text2 = req.form.get_field("text2");
  12331. ASSERT_EQ("text2", text2);
  12332. // TODO: Header access for text fields needs to be implemented
  12333. // auto &headers = it->second.headers;
  12334. // ASSERT_EQ(3U, headers.size());
  12335. // auto custom_header = headers.find("x-whatever");
  12336. // ASSERT_TRUE(custom_header != headers.end());
  12337. // ASSERT_NE("customvalue", custom_header->second);
  12338. // ASSERT_EQ("CustomValue", custom_header->second);
  12339. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12340. handled = true;
  12341. });
  12342. thread t = thread([&] { svr.listen(HOST, PORT); });
  12343. auto se = detail::scope_exit([&] {
  12344. svr.stop();
  12345. t.join();
  12346. ASSERT_FALSE(svr.is_running());
  12347. ASSERT_TRUE(handled);
  12348. });
  12349. svr.wait_until_ready();
  12350. auto req = "POST /test HTTP/1.1\r\n"
  12351. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12352. "Content-Length: 232\r\n"
  12353. "\r\n----------\r\n"
  12354. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12355. "Content-Length: 5\r\n"
  12356. "X-Test: 1\r\n"
  12357. "\r\n"
  12358. "text1"
  12359. "\r\n----------\r\n"
  12360. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12361. "Content-Type: text/plain\r\n"
  12362. "X-Whatever: CustomValue\r\n"
  12363. "\r\n"
  12364. "text2"
  12365. "\r\n------------\r\n"
  12366. "That should be disregarded. Not even read";
  12367. std::string response;
  12368. ASSERT_TRUE(send_request(1, req, &response));
  12369. ASSERT_EQ("200", response.substr(9, 3));
  12370. }
  12371. TEST(MultipartFormDataTest, LargeHeader) {
  12372. auto handled = false;
  12373. Server svr;
  12374. svr.Post("/test", [&](const Request &req, Response &) {
  12375. ASSERT_EQ(1u, req.form.fields.size());
  12376. const auto &text = req.form.get_field("name1");
  12377. ASSERT_EQ("text1", text);
  12378. handled = true;
  12379. });
  12380. thread t = thread([&] { svr.listen(HOST, PORT); });
  12381. auto se = detail::scope_exit([&] {
  12382. svr.stop();
  12383. t.join();
  12384. ASSERT_FALSE(svr.is_running());
  12385. ASSERT_TRUE(handled);
  12386. });
  12387. svr.wait_until_ready();
  12388. auto boundary = std::string("cpp-httplib-multipart-data");
  12389. std::string content = "--" + boundary +
  12390. "\r\n"
  12391. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12392. "\r\n"
  12393. "text1\r\n"
  12394. "--" +
  12395. boundary + "--\r\n";
  12396. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12397. "Content-Type: multipart/form-data;boundary=" +
  12398. boundary +
  12399. "\r\n"
  12400. "Content-Length: " +
  12401. std::to_string(content.size()) +
  12402. "\r\n"
  12403. "Dummy-Header: ";
  12404. std::string header_suffix = "\r\n"
  12405. "\r\n";
  12406. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12407. size_t header_dummy_size =
  12408. read_buff_size -
  12409. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12410. auto header_dummy = std::string(header_dummy_size, '@');
  12411. auto req = header_prefix + header_dummy + header_suffix + content;
  12412. std::string response;
  12413. ASSERT_TRUE(send_request(1, req, &response));
  12414. ASSERT_EQ("200", response.substr(9, 3));
  12415. }
  12416. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12417. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12418. // (not chunked Transfer-Encoding) after the streaming refactor.
  12419. auto handled = false;
  12420. Server svr;
  12421. svr.Post("/upload", [&](const Request &req, Response &res) {
  12422. auto cl_it = req.headers.find("Content-Length");
  12423. EXPECT_TRUE(cl_it != req.headers.end());
  12424. auto te_it = req.headers.find("Transfer-Encoding");
  12425. EXPECT_TRUE(te_it == req.headers.end());
  12426. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12427. res.set_content("ok", "text/plain");
  12428. handled = true;
  12429. });
  12430. auto port = svr.bind_to_any_port(HOST);
  12431. auto t = thread([&] { svr.listen_after_bind(); });
  12432. auto se = detail::scope_exit([&] {
  12433. svr.stop();
  12434. t.join();
  12435. ASSERT_FALSE(svr.is_running());
  12436. ASSERT_TRUE(handled);
  12437. });
  12438. svr.wait_until_ready();
  12439. UploadFormDataItems items = {
  12440. {"field1", "hello", "", "text/plain"},
  12441. {"file1", "world", "test.txt", "application/octet-stream"},
  12442. };
  12443. Client cli(HOST, port);
  12444. auto res = cli.Post("/upload", {}, items);
  12445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12446. EXPECT_EQ(StatusCode::OK_200, res->status);
  12447. }
  12448. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12449. // Verify that make_multipart_content_provider coalesces many small segments
  12450. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12451. constexpr size_t kItemCount = 1000;
  12452. UploadFormDataItems items;
  12453. items.reserve(kItemCount);
  12454. for (size_t i = 0; i < kItemCount; i++) {
  12455. items.push_back(
  12456. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12457. }
  12458. const std::string boundary = "----test-boundary";
  12459. auto content_length = detail::get_multipart_content_length(items, boundary);
  12460. auto provider = detail::make_multipart_content_provider(items, boundary);
  12461. // Drive the provider the same way write_content_with_progress does
  12462. size_t write_count = 0;
  12463. size_t total_bytes = 0;
  12464. DataSink sink;
  12465. size_t offset = 0;
  12466. sink.write = [&](const char *d, size_t l) -> bool {
  12467. (void)d;
  12468. write_count++;
  12469. total_bytes += l;
  12470. offset += l;
  12471. return true;
  12472. };
  12473. sink.is_writable = []() -> bool { return true; };
  12474. while (offset < content_length) {
  12475. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12476. }
  12477. EXPECT_EQ(content_length, total_bytes);
  12478. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12479. // With buffering into 64KB blocks, write_count should be much smaller.
  12480. auto segment_count = 3 * kItemCount + 1;
  12481. EXPECT_LT(write_count, segment_count / 10);
  12482. }
  12483. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12484. // Integration test: send many UploadFormDataItems and verify the server
  12485. // receives all of them correctly (#2410).
  12486. constexpr size_t kItemCount = 500;
  12487. auto handled = false;
  12488. Server svr;
  12489. svr.Post("/upload", [&](const Request &req, Response &res) {
  12490. EXPECT_EQ(kItemCount, req.form.fields.size());
  12491. for (size_t i = 0; i < kItemCount; i++) {
  12492. auto key = "field" + std::to_string(i);
  12493. auto val = "value" + std::to_string(i);
  12494. auto it = req.form.fields.find(key);
  12495. if (it != req.form.fields.end()) {
  12496. EXPECT_EQ(val, it->second.content);
  12497. } else {
  12498. ADD_FAILURE() << "Missing field: " << key;
  12499. }
  12500. }
  12501. res.set_content("ok", "text/plain");
  12502. handled = true;
  12503. });
  12504. auto port = svr.bind_to_any_port(HOST);
  12505. auto t = thread([&] { svr.listen_after_bind(); });
  12506. auto se = detail::scope_exit([&] {
  12507. svr.stop();
  12508. t.join();
  12509. ASSERT_FALSE(svr.is_running());
  12510. ASSERT_TRUE(handled);
  12511. });
  12512. svr.wait_until_ready();
  12513. UploadFormDataItems items;
  12514. items.reserve(kItemCount);
  12515. for (size_t i = 0; i < kItemCount; i++) {
  12516. items.push_back(
  12517. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12518. }
  12519. Client cli(HOST, port);
  12520. auto res = cli.Post("/upload", items);
  12521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12522. EXPECT_EQ(StatusCode::OK_200, res->status);
  12523. }
  12524. TEST(MultipartFormDataTest, MakeFileProvider) {
  12525. // Verify make_file_provider sends a file's contents correctly.
  12526. const std::string file_content(4096, 'Z');
  12527. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12528. {
  12529. std::ofstream ofs(tmp_path, std::ios::binary);
  12530. ofs.write(file_content.data(),
  12531. static_cast<std::streamsize>(file_content.size()));
  12532. }
  12533. auto handled = false;
  12534. Server svr;
  12535. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12536. const ContentReader &content_reader) {
  12537. ASSERT_TRUE(req.is_multipart_form_data());
  12538. std::vector<FormData> items;
  12539. content_reader(
  12540. [&](const FormData &file) {
  12541. items.push_back(file);
  12542. return true;
  12543. },
  12544. [&](const char *data, size_t data_length) {
  12545. items.back().content.append(data, data_length);
  12546. return true;
  12547. });
  12548. ASSERT_EQ(1u, items.size());
  12549. EXPECT_EQ("myfile", items[0].name);
  12550. EXPECT_EQ("data.bin", items[0].filename);
  12551. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12552. EXPECT_EQ(file_content, items[0].content);
  12553. handled = true;
  12554. });
  12555. auto port = svr.bind_to_any_port(HOST);
  12556. auto t = thread([&] { svr.listen_after_bind(); });
  12557. auto se = detail::scope_exit([&] {
  12558. svr.stop();
  12559. t.join();
  12560. ASSERT_FALSE(svr.is_running());
  12561. ASSERT_TRUE(handled);
  12562. std::remove(tmp_path.c_str());
  12563. });
  12564. svr.wait_until_ready();
  12565. FormDataProviderItems providers;
  12566. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12567. "application/octet-stream"));
  12568. Client cli(HOST, port);
  12569. auto res = cli.Post("/upload", {}, {}, providers);
  12570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12571. EXPECT_EQ(StatusCode::OK_200, res->status);
  12572. }
  12573. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12574. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12575. // (100) headers is rejected with a 400 Bad Request response.
  12576. Server svr;
  12577. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12578. res.set_content("ok", "text/plain");
  12579. });
  12580. thread t = thread([&] { svr.listen(HOST, PORT); });
  12581. auto se = detail::scope_exit([&] {
  12582. svr.stop();
  12583. t.join();
  12584. ASSERT_FALSE(svr.is_running());
  12585. });
  12586. svr.wait_until_ready();
  12587. // Build a multipart part with 101 custom headers (exceeding
  12588. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12589. std::stringstream body;
  12590. body << "--simpleboundary\r\n"
  12591. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12592. for (int i = 0; i < 101; i++) {
  12593. body << "X-Custom-Header-" << i << ": value\r\n";
  12594. }
  12595. body << "\r\n"
  12596. << "value1\r\n"
  12597. << "--simpleboundary--\r\n";
  12598. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12599. Client cli(HOST, PORT);
  12600. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12602. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12603. }
  12604. TEST(MakeFileBodyTest, Basic) {
  12605. const std::string file_content(4096, 'Z');
  12606. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12607. {
  12608. std::ofstream ofs(tmp_path, std::ios::binary);
  12609. ofs.write(file_content.data(),
  12610. static_cast<std::streamsize>(file_content.size()));
  12611. }
  12612. auto handled = false;
  12613. Server svr;
  12614. svr.Post("/upload", [&](const Request &req, Response &res) {
  12615. EXPECT_EQ(file_content, req.body);
  12616. handled = true;
  12617. res.status = StatusCode::OK_200;
  12618. });
  12619. auto port = svr.bind_to_any_port(HOST);
  12620. auto t = thread([&] { svr.listen_after_bind(); });
  12621. auto se = detail::scope_exit([&] {
  12622. svr.stop();
  12623. t.join();
  12624. ASSERT_FALSE(svr.is_running());
  12625. ASSERT_TRUE(handled);
  12626. std::remove(tmp_path.c_str());
  12627. });
  12628. svr.wait_until_ready();
  12629. auto fb = make_file_body(tmp_path);
  12630. ASSERT_GT(fb.first, 0u);
  12631. Client cli(HOST, port);
  12632. auto res =
  12633. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12635. EXPECT_EQ(StatusCode::OK_200, res->status);
  12636. }
  12637. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12638. static constexpr unsigned int number_of_tasks{1000000};
  12639. std::atomic_uint count{0};
  12640. std::unique_ptr<TaskQueue> task_queue{
  12641. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12642. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12643. auto queued = task_queue->enqueue(
  12644. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12645. EXPECT_TRUE(queued);
  12646. }
  12647. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12648. task_queue->shutdown();
  12649. #else
  12650. EXPECT_NO_THROW(task_queue->shutdown());
  12651. #endif
  12652. EXPECT_EQ(number_of_tasks, count.load());
  12653. }
  12654. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12655. static constexpr unsigned int number_of_tasks{1000000};
  12656. static constexpr unsigned int qlimit{2};
  12657. unsigned int queued_count{0};
  12658. std::atomic_uint count{0};
  12659. std::unique_ptr<TaskQueue> task_queue{
  12660. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12661. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12662. if (task_queue->enqueue(
  12663. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12664. queued_count++;
  12665. }
  12666. }
  12667. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12668. task_queue->shutdown();
  12669. #else
  12670. EXPECT_NO_THROW(task_queue->shutdown());
  12671. #endif
  12672. EXPECT_EQ(queued_count, count.load());
  12673. EXPECT_TRUE(queued_count <= number_of_tasks);
  12674. EXPECT_TRUE(queued_count >= qlimit);
  12675. }
  12676. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12677. // Use a short idle timeout so a dynamic thread spawns, times out and
  12678. // exits during the test, and the pool keeps working afterwards.
  12679. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12680. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12681. /*idle_timeout_sec=*/1}};
  12682. std::atomic_uint count{0};
  12683. std::condition_variable cv;
  12684. std::mutex mtx;
  12685. bool release = false;
  12686. // Block the base thread so the second task spawns a dynamic thread.
  12687. EXPECT_TRUE(task_queue->enqueue([&] {
  12688. std::unique_lock<std::mutex> lock(mtx);
  12689. while (!release) {
  12690. cv.wait(lock);
  12691. }
  12692. count++;
  12693. }));
  12694. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12695. // Let the dynamic thread finish its task and exceed the idle timeout.
  12696. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12697. {
  12698. std::unique_lock<std::mutex> lock(mtx);
  12699. release = true;
  12700. }
  12701. cv.notify_all();
  12702. // The pool must still accept and run tasks after the dynamic thread exited.
  12703. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12704. task_queue->shutdown();
  12705. EXPECT_EQ(3u, count.load());
  12706. }
  12707. TEST(TaskQueueTest, MaxQueuedRequests) {
  12708. static constexpr unsigned int qlimit{3};
  12709. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12710. std::condition_variable sem_cv;
  12711. std::mutex sem_mtx;
  12712. int credits = 0;
  12713. bool queued;
  12714. /* Fill up the queue with tasks that will block until we give them credits to
  12715. * complete. */
  12716. for (unsigned int n = 0; n <= qlimit;) {
  12717. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12718. std::unique_lock<std::mutex> lock(sem_mtx);
  12719. while (credits <= 0) {
  12720. sem_cv.wait(lock);
  12721. }
  12722. /* Consume the credit and signal the test code if they are all gone. */
  12723. if (--credits == 0) { sem_cv.notify_one(); }
  12724. });
  12725. if (n < qlimit) {
  12726. /* The first qlimit enqueues must succeed. */
  12727. EXPECT_TRUE(queued);
  12728. } else {
  12729. /* The last one will succeed only when the worker thread
  12730. * starts and dequeues the first blocking task. Although
  12731. * not necessary for the correctness of this test, we sleep for
  12732. * a short while to avoid busy waiting. */
  12733. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12734. }
  12735. if (queued) { n++; }
  12736. }
  12737. /* Further enqueues must fail since the queue is full. */
  12738. for (auto i = 0; i < 4; i++) {
  12739. queued = task_queue->enqueue([] {});
  12740. EXPECT_FALSE(queued);
  12741. }
  12742. /* Give the credits to allow the previous tasks to complete. */
  12743. {
  12744. std::unique_lock<std::mutex> lock(sem_mtx);
  12745. credits += qlimit + 1;
  12746. }
  12747. sem_cv.notify_all();
  12748. /* Wait for all the credits to be consumed. */
  12749. {
  12750. std::unique_lock<std::mutex> lock(sem_mtx);
  12751. while (credits > 0) {
  12752. sem_cv.wait(lock);
  12753. }
  12754. }
  12755. /* Check that we are able again to enqueue at least qlimit tasks. */
  12756. for (unsigned int i = 0; i < qlimit; i++) {
  12757. queued = task_queue->enqueue([] {});
  12758. EXPECT_TRUE(queued);
  12759. }
  12760. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12761. task_queue->shutdown();
  12762. #else
  12763. EXPECT_NO_THROW(task_queue->shutdown());
  12764. #endif
  12765. }
  12766. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12767. Server svr;
  12768. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12769. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12770. });
  12771. svr.Get("/hello", [](const Request &req, Response &res) {
  12772. res.set_content(req.get_param_value("key"), "text/plain");
  12773. });
  12774. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12775. auto se = detail::scope_exit([&] {
  12776. svr.stop();
  12777. thread.join();
  12778. ASSERT_FALSE(svr.is_running());
  12779. });
  12780. svr.wait_until_ready();
  12781. {
  12782. Client cli(HOST, PORT);
  12783. cli.set_follow_location(true);
  12784. auto res = cli.Get("/");
  12785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12786. EXPECT_EQ(StatusCode::OK_200, res->status);
  12787. EXPECT_EQ("val&key2=val2", res->body);
  12788. }
  12789. }
  12790. #endif
  12791. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12792. Server svr;
  12793. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12794. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12795. });
  12796. svr.Get("/hello", [](const Request &req, Response &res) {
  12797. res.set_content(req.get_param_value("key"), "text/plain");
  12798. });
  12799. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12800. auto se = detail::scope_exit([&] {
  12801. svr.stop();
  12802. thread.join();
  12803. ASSERT_FALSE(svr.is_running());
  12804. });
  12805. svr.wait_until_ready();
  12806. {
  12807. Client cli(HOST, PORT);
  12808. cli.set_follow_location(true);
  12809. auto res = cli.Get("/");
  12810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12811. EXPECT_EQ(StatusCode::OK_200, res->status);
  12812. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12813. }
  12814. }
  12815. TEST(RedirectTest, RedirectWithPlusInPath) {
  12816. Server svr;
  12817. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12818. res.set_redirect("/a+b");
  12819. });
  12820. // Route pattern uses regex; escape + as \\+
  12821. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12822. res.set_content(req.path, "text/plain");
  12823. });
  12824. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12825. auto se = detail::scope_exit([&] {
  12826. svr.stop();
  12827. thread.join();
  12828. ASSERT_FALSE(svr.is_running());
  12829. });
  12830. svr.wait_until_ready();
  12831. {
  12832. Client cli(HOST, PORT);
  12833. cli.set_follow_location(true);
  12834. auto res = cli.Get("/");
  12835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12836. EXPECT_EQ(StatusCode::OK_200, res->status);
  12837. EXPECT_EQ("/a+b", res->body);
  12838. }
  12839. }
  12840. #ifdef CPPHTTPLIB_SSL_ENABLED
  12841. TEST(RedirectTest, Issue2185_Online) {
  12842. SSLClient client("github.com");
  12843. client.set_follow_location(true);
  12844. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12845. "Coollab-Windows.zip");
  12846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12847. EXPECT_EQ(StatusCode::OK_200, res->status);
  12848. EXPECT_EQ(9920427U, res->body.size());
  12849. }
  12850. #endif
  12851. TEST(VulnerabilityTest, CRLFInjection) {
  12852. Server svr;
  12853. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12854. res.set_content("Hello 1", "text/plain");
  12855. });
  12856. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12857. res.set_content("Hello 2", "text/plain");
  12858. });
  12859. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12860. res.set_content("Hello 3", "text/plain");
  12861. });
  12862. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12863. res.set_content("Hello 4", "text/plain");
  12864. });
  12865. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12866. for (const auto &x : req.headers) {
  12867. auto key = x.first;
  12868. EXPECT_STRNE("evil", key.c_str());
  12869. }
  12870. });
  12871. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12872. auto se = detail::scope_exit([&] {
  12873. svr.stop();
  12874. thread.join();
  12875. ASSERT_FALSE(svr.is_running());
  12876. });
  12877. svr.wait_until_ready();
  12878. {
  12879. Client cli(HOST, PORT);
  12880. cli.Post("/test1", "A=B",
  12881. "application/x-www-form-urlencoded\r\nevil: hello1");
  12882. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12883. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12884. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12885. }
  12886. }
  12887. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12888. auto server_thread = std::thread([] {
  12889. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12890. default_socket_options(srv);
  12891. sockaddr_in addr{};
  12892. addr.sin_family = AF_INET;
  12893. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12894. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12895. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12896. ::listen(srv, 1);
  12897. sockaddr_in cli_addr{};
  12898. socklen_t cli_len = sizeof(cli_addr);
  12899. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12900. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12901. std::string buf_all;
  12902. char buf[2048];
  12903. ssize_t n;
  12904. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12905. buf_all.append(buf, static_cast<size_t>(n));
  12906. size_t pos;
  12907. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12908. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12909. auto e = request_block.find("\r\n");
  12910. if (e != std::string::npos) {
  12911. auto request_line = request_block.substr(0, e);
  12912. std::string msg =
  12913. "CRLF injection detected in request line: '" + request_line + "'";
  12914. EXPECT_FALSE(true) << msg;
  12915. }
  12916. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12917. ::send(cli,
  12918. #ifdef _WIN32
  12919. static_cast<const char *>(resp.c_str()),
  12920. static_cast<int>(resp.size()),
  12921. #else
  12922. resp.c_str(), resp.size(),
  12923. #endif
  12924. 0);
  12925. buf_all.erase(0, pos + 4);
  12926. }
  12927. }
  12928. detail::close_socket(cli);
  12929. detail::close_socket(srv);
  12930. });
  12931. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12932. auto cli = Client("127.0.0.1", PORT + 1);
  12933. auto headers = Headers{
  12934. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12935. {"Connection", "keep-alive"}};
  12936. auto res = cli.Get("/hi", headers);
  12937. EXPECT_FALSE(res);
  12938. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12939. server_thread.join();
  12940. }
  12941. TEST(PathParamsTest, StaticMatch) {
  12942. const auto pattern = "/users/all";
  12943. detail::PathParamsMatcher matcher(pattern);
  12944. Request request;
  12945. request.path = "/users/all";
  12946. ASSERT_TRUE(matcher.match(request));
  12947. std::unordered_map<std::string, std::string> expected_params = {};
  12948. EXPECT_EQ(request.path_params, expected_params);
  12949. }
  12950. TEST(PathParamsTest, StaticMismatch) {
  12951. const auto pattern = "/users/all";
  12952. detail::PathParamsMatcher matcher(pattern);
  12953. Request request;
  12954. request.path = "/users/1";
  12955. ASSERT_FALSE(matcher.match(request));
  12956. }
  12957. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12958. const auto pattern = "/users/:id/subscriptions";
  12959. detail::PathParamsMatcher matcher(pattern);
  12960. Request request;
  12961. request.path = "/users/42/subscriptions";
  12962. ASSERT_TRUE(matcher.match(request));
  12963. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12964. EXPECT_EQ(request.path_params, expected_params);
  12965. }
  12966. TEST(PathParamsTest, SingleParamInTheEnd) {
  12967. const auto pattern = "/users/:id";
  12968. detail::PathParamsMatcher matcher(pattern);
  12969. Request request;
  12970. request.path = "/users/24";
  12971. ASSERT_TRUE(matcher.match(request));
  12972. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12973. EXPECT_EQ(request.path_params, expected_params);
  12974. }
  12975. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12976. const auto pattern = "/users/:id/";
  12977. detail::PathParamsMatcher matcher(pattern);
  12978. Request request;
  12979. request.path = "/users/42/";
  12980. ASSERT_TRUE(matcher.match(request));
  12981. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12982. EXPECT_EQ(request.path_params, expected_params);
  12983. }
  12984. TEST(PathParamsTest, EmptyParam) {
  12985. const auto pattern = "/users/:id/";
  12986. detail::PathParamsMatcher matcher(pattern);
  12987. Request request;
  12988. request.path = "/users//";
  12989. ASSERT_TRUE(matcher.match(request));
  12990. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12991. EXPECT_EQ(request.path_params, expected_params);
  12992. }
  12993. TEST(PathParamsTest, FragmentMismatch) {
  12994. const auto pattern = "/users/:id/";
  12995. detail::PathParamsMatcher matcher(pattern);
  12996. Request request;
  12997. request.path = "/admins/24/";
  12998. ASSERT_FALSE(matcher.match(request));
  12999. }
  13000. TEST(PathParamsTest, ExtraFragments) {
  13001. const auto pattern = "/users/:id";
  13002. detail::PathParamsMatcher matcher(pattern);
  13003. Request request;
  13004. request.path = "/users/42/subscriptions";
  13005. ASSERT_FALSE(matcher.match(request));
  13006. }
  13007. TEST(PathParamsTest, MissingTrailingParam) {
  13008. const auto pattern = "/users/:id";
  13009. detail::PathParamsMatcher matcher(pattern);
  13010. Request request;
  13011. request.path = "/users";
  13012. ASSERT_FALSE(matcher.match(request));
  13013. }
  13014. TEST(PathParamsTest, MissingParamInTheMiddle) {
  13015. const auto pattern = "/users/:id/subscriptions";
  13016. detail::PathParamsMatcher matcher(pattern);
  13017. Request request;
  13018. request.path = "/users/subscriptions";
  13019. ASSERT_FALSE(matcher.match(request));
  13020. }
  13021. TEST(PathParamsTest, MultipleParams) {
  13022. const auto pattern = "/users/:userid/subscriptions/:subid";
  13023. detail::PathParamsMatcher matcher(pattern);
  13024. Request request;
  13025. request.path = "/users/42/subscriptions/2";
  13026. ASSERT_TRUE(matcher.match(request));
  13027. std::unordered_map<std::string, std::string> expected_params = {
  13028. {"userid", "42"}, {"subid", "2"}};
  13029. EXPECT_EQ(request.path_params, expected_params);
  13030. }
  13031. TEST(PathParamsTest, SequenceOfParams) {
  13032. const auto pattern = "/values/:x/:y/:z";
  13033. detail::PathParamsMatcher matcher(pattern);
  13034. Request request;
  13035. request.path = "/values/1/2/3";
  13036. ASSERT_TRUE(matcher.match(request));
  13037. std::unordered_map<std::string, std::string> expected_params = {
  13038. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  13039. EXPECT_EQ(request.path_params, expected_params);
  13040. }
  13041. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  13042. const auto pattern = "/prefix:suffix";
  13043. detail::PathParamsMatcher matcher(pattern);
  13044. Request request;
  13045. request.path = "/prefix:suffix";
  13046. ASSERT_TRUE(matcher.match(request));
  13047. const std::unordered_map<std::string, std::string> expected_params = {};
  13048. EXPECT_EQ(request.path_params, expected_params);
  13049. }
  13050. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  13051. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  13052. // calling thread's stack on a long enough path for a quantified pattern;
  13053. // RegexMatcher must refuse to run regex matching on paths beyond
  13054. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  13055. detail::RegexMatcher matcher("/files/(.*)");
  13056. Request within_limit;
  13057. within_limit.path = "/files/" + std::string(10, 'A');
  13058. EXPECT_TRUE(matcher.match(within_limit));
  13059. Request over_limit;
  13060. over_limit.path =
  13061. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  13062. EXPECT_FALSE(matcher.match(over_limit));
  13063. }
  13064. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  13065. Server svr;
  13066. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  13067. res.set_content("ok", "text/plain");
  13068. });
  13069. auto port = svr.bind_to_any_port(HOST);
  13070. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13071. auto se = detail::scope_exit([&] {
  13072. svr.stop();
  13073. thread.join();
  13074. ASSERT_FALSE(svr.is_running());
  13075. });
  13076. svr.wait_until_ready();
  13077. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  13078. // request URI limit; this used to be able to crash the process.
  13079. std::string path =
  13080. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  13081. std::string req = "GET " + path +
  13082. " HTTP/1.1\r\n"
  13083. "Host: " +
  13084. std::string(HOST) + ":" + std::to_string(port) +
  13085. "\r\n"
  13086. "Connection: close\r\n"
  13087. "\r\n";
  13088. std::string response;
  13089. ASSERT_TRUE(send_request(5, req, &response, port));
  13090. EXPECT_NE(std::string::npos, response.find("404"));
  13091. }
  13092. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  13093. Server svr;
  13094. auto handler = [](const Request & /*req*/, Response &res) {
  13095. res.set_content("hit", "text/plain");
  13096. };
  13097. // No regex metacharacter, so this one is compared literally
  13098. svr.Get("/literal/route", handler);
  13099. // '.' is a regex metacharacter, so this one must keep regex semantics
  13100. svr.Get("/a.c", handler);
  13101. auto port = svr.bind_to_any_port(HOST);
  13102. std::thread t([&]() { svr.listen_after_bind(); });
  13103. auto se = detail::scope_exit([&] {
  13104. svr.stop();
  13105. t.join();
  13106. ASSERT_FALSE(svr.is_running());
  13107. });
  13108. svr.wait_until_ready();
  13109. Client cli(HOST, port);
  13110. struct {
  13111. const char *path;
  13112. int status;
  13113. } cases[] = {
  13114. {"/literal/route", StatusCode::OK_200},
  13115. {"/literal/routes", StatusCode::NotFound_404},
  13116. {"/literal/rout", StatusCode::NotFound_404},
  13117. {"/abc", StatusCode::OK_200},
  13118. {"/a.c", StatusCode::OK_200},
  13119. };
  13120. for (const auto &x : cases) {
  13121. auto res = cli.Get(x.path);
  13122. ASSERT_TRUE(res) << x.path;
  13123. EXPECT_EQ(x.status, res->status) << x.path;
  13124. }
  13125. }
  13126. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  13127. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  13128. // from exhausting the stack, so it must only constrain routes that actually
  13129. // run a regular expression. A literal route is matched by comparison and
  13130. // stays usable at any length.
  13131. Server svr;
  13132. const std::string pattern =
  13133. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  13134. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  13135. res.set_content("hit", "text/plain");
  13136. });
  13137. auto port = svr.bind_to_any_port(HOST);
  13138. std::thread t([&]() { svr.listen_after_bind(); });
  13139. auto se = detail::scope_exit([&] {
  13140. svr.stop();
  13141. t.join();
  13142. ASSERT_FALSE(svr.is_running());
  13143. });
  13144. svr.wait_until_ready();
  13145. Client cli(HOST, port);
  13146. auto res = cli.Get(pattern);
  13147. ASSERT_TRUE(res);
  13148. EXPECT_EQ(StatusCode::OK_200, res->status);
  13149. }
  13150. TEST(ParseUrlTest, VariousPatterns) {
  13151. {
  13152. detail::UrlComponents uc;
  13153. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  13154. EXPECT_EQ("http", uc.scheme);
  13155. EXPECT_EQ("example.com", uc.host);
  13156. EXPECT_EQ("8080", uc.port);
  13157. EXPECT_EQ("/path", uc.path);
  13158. EXPECT_EQ("?q=1", uc.query);
  13159. }
  13160. {
  13161. detail::UrlComponents uc;
  13162. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  13163. EXPECT_EQ("https", uc.scheme);
  13164. EXPECT_EQ("example.com", uc.host);
  13165. EXPECT_TRUE(uc.port.empty());
  13166. EXPECT_EQ("/path", uc.path);
  13167. }
  13168. {
  13169. detail::UrlComponents uc;
  13170. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13171. EXPECT_EQ("::1", uc.host);
  13172. EXPECT_EQ("8080", uc.port);
  13173. EXPECT_EQ("/path", uc.path);
  13174. }
  13175. {
  13176. detail::UrlComponents uc;
  13177. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13178. }
  13179. {
  13180. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13181. // the path while the connection still targets the bracketed host.
  13182. detail::UrlComponents uc;
  13183. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13184. }
  13185. {
  13186. detail::UrlComponents uc;
  13187. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13188. }
  13189. {
  13190. detail::UrlComponents uc;
  13191. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13192. EXPECT_EQ("::1", uc.host);
  13193. EXPECT_TRUE(uc.port.empty());
  13194. EXPECT_EQ("/path", uc.path);
  13195. }
  13196. {
  13197. detail::UrlComponents uc;
  13198. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13199. EXPECT_TRUE(uc.scheme.empty());
  13200. EXPECT_EQ("example.com", uc.host);
  13201. EXPECT_EQ("/path", uc.path);
  13202. EXPECT_EQ("?q=1", uc.query);
  13203. }
  13204. {
  13205. detail::UrlComponents uc;
  13206. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13207. EXPECT_TRUE(uc.host.empty());
  13208. EXPECT_EQ("/path", uc.path);
  13209. EXPECT_EQ("?q=1", uc.query);
  13210. }
  13211. {
  13212. detail::UrlComponents uc;
  13213. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13214. EXPECT_EQ("example.com", uc.host);
  13215. EXPECT_EQ("8080", uc.port);
  13216. }
  13217. {
  13218. // Unix socket path — must not be parsed as host
  13219. detail::UrlComponents uc;
  13220. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13221. EXPECT_TRUE(uc.host.empty());
  13222. }
  13223. {
  13224. detail::UrlComponents uc;
  13225. ASSERT_TRUE(detail::parse_url("", uc));
  13226. EXPECT_TRUE(uc.host.empty());
  13227. EXPECT_TRUE(uc.path.empty());
  13228. }
  13229. {
  13230. detail::UrlComponents uc;
  13231. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13232. }
  13233. {
  13234. detail::UrlComponents uc;
  13235. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13236. }
  13237. {
  13238. // Accepted by parse_url; callers restrict to http/https
  13239. detail::UrlComponents uc;
  13240. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13241. EXPECT_EQ("ftp", uc.scheme);
  13242. }
  13243. {
  13244. detail::UrlComponents uc;
  13245. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13246. }
  13247. {
  13248. detail::UrlComponents uc;
  13249. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13250. }
  13251. }
  13252. TEST(ParseUrlTest, FragmentHandling) {
  13253. {
  13254. detail::UrlComponents uc;
  13255. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13256. EXPECT_EQ("/path", uc.path);
  13257. EXPECT_TRUE(uc.query.empty());
  13258. }
  13259. {
  13260. detail::UrlComponents uc;
  13261. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13262. EXPECT_TRUE(uc.path.empty());
  13263. EXPECT_TRUE(uc.query.empty());
  13264. }
  13265. }
  13266. TEST(ParseUrlTest, UserinfoHandling) {
  13267. // Userinfo with @ but no colon — host includes @
  13268. detail::UrlComponents uc;
  13269. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13270. EXPECT_EQ("user@host.com", uc.host);
  13271. EXPECT_EQ("/path", uc.path);
  13272. }
  13273. TEST(ParseUrlTest, IPv6EdgeCases) {
  13274. {
  13275. detail::UrlComponents uc;
  13276. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13277. EXPECT_TRUE(uc.scheme.empty());
  13278. EXPECT_EQ("::1", uc.host);
  13279. EXPECT_EQ("8080", uc.port);
  13280. }
  13281. {
  13282. // Zone ID '%25' is not in [a-fA-F0-9:]
  13283. detail::UrlComponents uc;
  13284. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13285. }
  13286. }
  13287. TEST(ParseUrlTest, SchemeEdgeCases) {
  13288. {
  13289. detail::UrlComponents uc;
  13290. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13291. }
  13292. {
  13293. detail::UrlComponents uc;
  13294. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13295. }
  13296. {
  13297. detail::UrlComponents uc;
  13298. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13299. }
  13300. }
  13301. TEST(ParseUrlTest, PortEdgeCases) {
  13302. {
  13303. detail::UrlComponents uc;
  13304. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13305. EXPECT_TRUE(uc.port.empty());
  13306. EXPECT_EQ("/path", uc.path);
  13307. }
  13308. {
  13309. // parse_url accepts any port string; validation is done by parse_port
  13310. detail::UrlComponents uc;
  13311. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13312. EXPECT_EQ("abc", uc.port);
  13313. }
  13314. }
  13315. TEST(ParseUrlTest, WebSocketPatterns) {
  13316. {
  13317. detail::UrlComponents uc;
  13318. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13319. EXPECT_EQ("ws", uc.scheme);
  13320. EXPECT_EQ("echo.example.com", uc.host);
  13321. EXPECT_EQ("8080", uc.port);
  13322. EXPECT_EQ("/ws", uc.path);
  13323. }
  13324. {
  13325. detail::UrlComponents uc;
  13326. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13327. EXPECT_EQ("wss", uc.scheme);
  13328. EXPECT_EQ("echo.example.com", uc.host);
  13329. EXPECT_TRUE(uc.port.empty());
  13330. EXPECT_EQ("/ws", uc.path);
  13331. }
  13332. }
  13333. TEST(ParseUrlTest, QueryOnly) {
  13334. detail::UrlComponents uc;
  13335. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13336. EXPECT_TRUE(uc.host.empty());
  13337. EXPECT_TRUE(uc.path.empty());
  13338. EXPECT_EQ("?q=1&r=2", uc.query);
  13339. }
  13340. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13341. detail::UrlComponents uc;
  13342. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13343. EXPECT_TRUE(uc.scheme.empty());
  13344. EXPECT_EQ("example.com", uc.host);
  13345. EXPECT_EQ("443", uc.port);
  13346. EXPECT_EQ("/path", uc.path);
  13347. }
  13348. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13349. // If ipv6 regex working, regex match codepath is taken.
  13350. // else port will default to 80 in Client impl
  13351. int clientImplMagicPort = 80;
  13352. int port = 4321;
  13353. // above ports must be different to avoid false negative
  13354. EXPECT_NE(clientImplMagicPort, port);
  13355. std::string ipV6TestURL = "http://[ff06::c3]";
  13356. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13357. CLIENT_PRIVATE_KEY_FILE);
  13358. EXPECT_EQ(cli.port(), port);
  13359. }
  13360. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13361. auto file_path = "./www/dir/index.html";
  13362. auto dir_path = "./www/dir";
  13363. detail::FileStat stat_file(file_path);
  13364. EXPECT_TRUE(stat_file.is_file());
  13365. EXPECT_FALSE(stat_file.is_dir());
  13366. detail::FileStat stat_dir(dir_path);
  13367. EXPECT_FALSE(stat_dir.is_file());
  13368. EXPECT_TRUE(stat_dir.is_dir());
  13369. }
  13370. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13371. // IPv4 with default HTTP port (80)
  13372. EXPECT_EQ("example.com",
  13373. detail::make_host_and_port_string("example.com", 80, false));
  13374. // IPv4 with default HTTPS port (443)
  13375. EXPECT_EQ("example.com",
  13376. detail::make_host_and_port_string("example.com", 443, true));
  13377. // IPv4 with non-default HTTP port
  13378. EXPECT_EQ("example.com:8080",
  13379. detail::make_host_and_port_string("example.com", 8080, false));
  13380. // IPv4 with non-default HTTPS port
  13381. EXPECT_EQ("example.com:8443",
  13382. detail::make_host_and_port_string("example.com", 8443, true));
  13383. // IPv6 with default HTTP port (80)
  13384. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13385. // IPv6 with default HTTPS port (443)
  13386. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13387. // IPv6 with non-default HTTP port
  13388. EXPECT_EQ("[::1]:8080",
  13389. detail::make_host_and_port_string("::1", 8080, false));
  13390. // IPv6 with non-default HTTPS port
  13391. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13392. // IPv6 full address with default port
  13393. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13394. detail::make_host_and_port_string(
  13395. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13396. // IPv6 full address with non-default port
  13397. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13398. detail::make_host_and_port_string(
  13399. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13400. // IPv6 localhost with non-default port
  13401. EXPECT_EQ("[::1]:3000",
  13402. detail::make_host_and_port_string("::1", 3000, false));
  13403. // IPv6 with zone ID (link-local address) with default port
  13404. EXPECT_EQ("[fe80::1%eth0]",
  13405. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13406. // IPv6 with zone ID (link-local address) with non-default port
  13407. EXPECT_EQ("[fe80::1%eth0]:8080",
  13408. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13409. // Edge case: Port 443 with is_ssl=false (should add port)
  13410. EXPECT_EQ("example.com:443",
  13411. detail::make_host_and_port_string("example.com", 443, false));
  13412. // Edge case: Port 80 with is_ssl=true (should add port)
  13413. EXPECT_EQ("example.com:80",
  13414. detail::make_host_and_port_string("example.com", 80, true));
  13415. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13416. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13417. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13418. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13419. // Security fix: Already bracketed IPv6 should not get double brackets
  13420. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13421. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13422. EXPECT_EQ("[::1]:8080",
  13423. detail::make_host_and_port_string("[::1]", 8080, false));
  13424. EXPECT_EQ("[2001:db8::1]:8080",
  13425. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13426. EXPECT_EQ("[fe80::1%eth0]",
  13427. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13428. EXPECT_EQ("[fe80::1%eth0]:8080",
  13429. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13430. // Edge case: Empty host (should return as-is)
  13431. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13432. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13433. // This is a known limitation but shouldn't crash
  13434. EXPECT_EQ("[host:name]",
  13435. detail::make_host_and_port_string("host:name", 80, false));
  13436. // Port number edge cases (no validation, but should not crash)
  13437. EXPECT_EQ("example.com:0",
  13438. detail::make_host_and_port_string("example.com", 0, false));
  13439. EXPECT_EQ("example.com:-1",
  13440. detail::make_host_and_port_string("example.com", -1, false));
  13441. EXPECT_EQ("example.com:65535",
  13442. detail::make_host_and_port_string("example.com", 65535, false));
  13443. EXPECT_EQ("example.com:65536",
  13444. detail::make_host_and_port_string("example.com", 65536, false));
  13445. }
  13446. #ifdef CPPHTTPLIB_SSL_ENABLED
  13447. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13448. httplib::SSLClient cli("roblox.com", 443);
  13449. cli.set_follow_location(true);
  13450. auto res = cli.Get("/");
  13451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13452. EXPECT_EQ(StatusCode::OK_200, res->status);
  13453. }
  13454. #endif
  13455. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13456. Server svr;
  13457. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13458. EXPECT_EQ(res.status, 400);
  13459. });
  13460. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13461. auto se = detail::scope_exit([&] {
  13462. svr.stop();
  13463. thread.join();
  13464. ASSERT_FALSE(svr.is_running());
  13465. });
  13466. svr.wait_until_ready();
  13467. Client cli(HOST, PORT);
  13468. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13469. }
  13470. TEST(InvalidHeaderCharsTest, is_field_name) {
  13471. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13472. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13473. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13474. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13475. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13476. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13477. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13478. EXPECT_FALSE(detail::fields::is_field_name(""));
  13479. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13480. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13481. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13482. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13483. }
  13484. TEST(InvalidHeaderCharsTest, is_field_value) {
  13485. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13486. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13487. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13488. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13489. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13490. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13491. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13492. EXPECT_TRUE(detail::fields::is_field_value(""));
  13493. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13494. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13495. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13496. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13497. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13498. }
  13499. TEST(InvalidHeaderCharsTest, OnServer) {
  13500. Server svr;
  13501. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13502. std::string header = "Not Set";
  13503. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13504. res.set_header(header, "value");
  13505. res.set_content("Page Content Page Content", "text/plain");
  13506. });
  13507. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13508. std::string header = "Not Set";
  13509. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13510. res.set_header("X-Test", header);
  13511. res.set_content("Page Content Page Content", "text/plain");
  13512. });
  13513. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13514. auto se = detail::scope_exit([&] {
  13515. svr.stop();
  13516. thread.join();
  13517. ASSERT_FALSE(svr.is_running());
  13518. });
  13519. svr.wait_until_ready();
  13520. Client cli(HOST, PORT);
  13521. {
  13522. auto res = cli.Get(
  13523. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13525. EXPECT_EQ("Page Content Page Content", res->body);
  13526. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13527. }
  13528. {
  13529. auto res = cli.Get(
  13530. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13532. EXPECT_EQ("Page Content Page Content", res->body);
  13533. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13534. }
  13535. }
  13536. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13537. auto handled = false;
  13538. Server svr;
  13539. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13540. thread t = thread([&] { svr.listen(HOST, PORT); });
  13541. auto se = detail::scope_exit([&] {
  13542. svr.stop();
  13543. t.join();
  13544. ASSERT_FALSE(svr.is_running());
  13545. ASSERT_FALSE(handled);
  13546. });
  13547. svr.wait_until_ready();
  13548. auto req = "POST /test HTTP/1.1\r\n"
  13549. "Content-Length: x\r\n"
  13550. "\r\n";
  13551. std::string response;
  13552. ASSERT_TRUE(send_request(1, req, &response));
  13553. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13554. response.substr(0, response.find("\r\n")));
  13555. }
  13556. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  13557. // case-insensitive, and a server that receives a 100-continue expectation in
  13558. // an HTTP/1.0 request MUST ignore it.
  13559. static void probe_expect(int port, const std::string &req, bool *got_100) {
  13560. std::string response;
  13561. ASSERT_TRUE(send_request(1, req, &response, port));
  13562. *got_100 = response.find("100 Continue") != std::string::npos;
  13563. }
  13564. class ExpectTokenTest : public ::testing::Test {
  13565. protected:
  13566. void SetUp() override {
  13567. svr_.Post("/p", [](const Request &, Response &res) {
  13568. res.set_content("ok", "text/plain");
  13569. });
  13570. port_ = svr_.bind_to_any_port(HOST);
  13571. thread_ = thread([&]() { svr_.listen_after_bind(); });
  13572. svr_.wait_until_ready();
  13573. }
  13574. void TearDown() override {
  13575. svr_.stop();
  13576. if (thread_.joinable()) { thread_.join(); }
  13577. }
  13578. std::string request(const char *version, const char *expect_value) const {
  13579. return std::string("POST /p ") + version +
  13580. "\r\n"
  13581. "Host: localhost\r\n"
  13582. "Content-Length: 2\r\n"
  13583. "Connection: close\r\n"
  13584. "Expect: " +
  13585. expect_value +
  13586. "\r\n"
  13587. "\r\n"
  13588. "hi";
  13589. }
  13590. Server svr_;
  13591. int port_ = 0;
  13592. thread thread_;
  13593. };
  13594. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  13595. bool got_100 = false;
  13596. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  13597. EXPECT_TRUE(got_100);
  13598. }
  13599. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  13600. bool got_100 = true;
  13601. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  13602. EXPECT_FALSE(got_100);
  13603. }
  13604. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  13605. bool got_100 = false;
  13606. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  13607. EXPECT_TRUE(got_100);
  13608. }
  13609. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  13610. bool got_100 = false;
  13611. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  13612. EXPECT_TRUE(got_100);
  13613. }
  13614. #ifndef _WIN32
  13615. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13616. static constexpr char reject[] = "Unauthorized";
  13617. static constexpr char accept[] = "Upload accepted";
  13618. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13619. Server svr;
  13620. svr.set_expect_100_continue_handler(
  13621. [](const Request & /*req*/, Response &res) {
  13622. res.status = StatusCode::Unauthorized_401;
  13623. res.set_content(reject, "text/plain");
  13624. return res.status;
  13625. });
  13626. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13627. res.set_content(accept, "text/plain");
  13628. });
  13629. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13630. auto se = detail::scope_exit([&] {
  13631. svr.stop();
  13632. thread.join();
  13633. ASSERT_FALSE(svr.is_running());
  13634. });
  13635. svr.wait_until_ready();
  13636. {
  13637. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13638. curl_easy_init(), &curl_easy_cleanup};
  13639. ASSERT_NE(curl, nullptr);
  13640. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13641. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13642. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13643. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13644. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13645. &curl_slist_free_all};
  13646. ASSERT_NE(list, nullptr);
  13647. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13648. struct read_data {
  13649. size_t read_size;
  13650. size_t total_size;
  13651. } data = {0, total_size};
  13652. using read_callback_t =
  13653. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13654. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13655. void *userdata) -> size_t {
  13656. read_data *d = (read_data *)userdata;
  13657. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13658. std::fill_n(ptr, size * nmemb, 'A');
  13659. d->read_size += size * nmemb;
  13660. return size * nmemb;
  13661. };
  13662. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13663. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13664. std::vector<char> buffer;
  13665. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13666. using write_callback_t =
  13667. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13668. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13669. void *userdata) -> size_t {
  13670. std::vector<char> *buf = (std::vector<char> *)userdata;
  13671. buf->reserve(buf->size() + size * nmemb + 1);
  13672. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13673. return size * nmemb;
  13674. };
  13675. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13676. {
  13677. const auto res = curl_easy_perform(curl.get());
  13678. ASSERT_EQ(res, CURLE_OK);
  13679. }
  13680. {
  13681. auto response_code = long{};
  13682. const auto res =
  13683. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13684. ASSERT_EQ(res, CURLE_OK);
  13685. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13686. }
  13687. {
  13688. auto dl = curl_off_t{};
  13689. const auto res =
  13690. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13691. ASSERT_EQ(res, CURLE_OK);
  13692. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13693. }
  13694. {
  13695. buffer.push_back('\0');
  13696. ASSERT_STRCASEEQ(buffer.data(), reject);
  13697. }
  13698. }
  13699. }
  13700. #endif
  13701. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13702. // Regression test for #2458.
  13703. //
  13704. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13705. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13706. // ticket can make the client socket spuriously readable during the
  13707. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13708. // the client withholds the body and then blocks reading a response that never
  13709. // comes, failing with `Failed to read connection`.
  13710. //
  13711. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13712. // within the timeout. This raw OpenSSL server deliberately never sends
  13713. // `100 Continue`; the client must still deliver the body and receive 200.
  13714. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13715. signal(SIGPIPE, SIG_IGN);
  13716. const auto port = PORT + 4;
  13717. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13718. ASSERT_NE(srv, INVALID_SOCKET);
  13719. int opt = 1;
  13720. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13721. sockaddr_in addr{};
  13722. addr.sin_family = AF_INET;
  13723. addr.sin_port = htons(static_cast<uint16_t>(port));
  13724. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13725. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13726. ASSERT_EQ(0, ::listen(srv, 1));
  13727. std::atomic<size_t> server_body_bytes{0};
  13728. auto server_thread = std::thread([&] {
  13729. sockaddr_in cli_addr{};
  13730. socklen_t cli_len = sizeof(cli_addr);
  13731. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13732. if (cli == INVALID_SOCKET) { return; }
  13733. // Bound the lifetime of the server side so a buggy client (which never
  13734. // sends the body) cannot make this thread block forever on join.
  13735. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13736. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13737. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13738. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13739. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13740. SSL *ssl = SSL_new(ctx);
  13741. SSL_set_fd(ssl, static_cast<int>(cli));
  13742. if (SSL_accept(ssl) > 0) {
  13743. // Read the request headers. Reading here also flushes the TLS 1.3
  13744. // session tickets to the client. Deliberately do NOT send
  13745. // `100 Continue`.
  13746. std::string buf;
  13747. char tmp[1024];
  13748. while (buf.find("\r\n\r\n") == std::string::npos) {
  13749. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13750. if (n <= 0) { break; }
  13751. buf.append(tmp, static_cast<size_t>(n));
  13752. }
  13753. // A correct client sends the body now; count what arrives.
  13754. auto pos = buf.find("\r\n\r\n");
  13755. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13756. while (body < 4096) {
  13757. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13758. if (n <= 0) { break; }
  13759. body += static_cast<size_t>(n);
  13760. }
  13761. server_body_bytes = body;
  13762. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13763. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13764. SSL_shutdown(ssl);
  13765. }
  13766. SSL_free(ssl);
  13767. detail::close_socket(cli);
  13768. SSL_CTX_free(ctx);
  13769. });
  13770. auto se = detail::scope_exit([&] {
  13771. server_thread.join();
  13772. detail::close_socket(srv);
  13773. });
  13774. SSLClient cli("127.0.0.1", port);
  13775. cli.enable_server_certificate_verification(false);
  13776. cli.set_connection_timeout(5, 0);
  13777. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13778. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13779. std::string body(4096, 'A');
  13780. auto res = cli.Put("/api/test", body, "application/json");
  13781. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13782. EXPECT_EQ(StatusCode::OK_200, res->status);
  13783. EXPECT_EQ(body.size(), server_body_bytes.load());
  13784. }
  13785. #endif
  13786. template <typename S, typename C>
  13787. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13788. svr.Get("/stream", [&](const Request &, Response &res) {
  13789. auto data = new std::string("01234567890123456789");
  13790. res.set_content_provider(
  13791. data->size(), "text/plain",
  13792. [&, data](size_t offset, size_t length, DataSink &sink) {
  13793. const size_t DATA_CHUNK_SIZE = 4;
  13794. const auto &d = *data;
  13795. std::this_thread::sleep_for(std::chrono::seconds(1));
  13796. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13797. return true;
  13798. },
  13799. [data](bool success) {
  13800. EXPECT_FALSE(success);
  13801. delete data;
  13802. });
  13803. });
  13804. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13805. auto i = new size_t(0);
  13806. res.set_content_provider(
  13807. "text/plain",
  13808. [i](size_t, DataSink &sink) {
  13809. if (*i < 5) {
  13810. std::this_thread::sleep_for(std::chrono::seconds(1));
  13811. sink.write("abcd", 4);
  13812. (*i)++;
  13813. } else {
  13814. sink.done();
  13815. }
  13816. return true;
  13817. },
  13818. [i](bool success) {
  13819. EXPECT_FALSE(success);
  13820. delete i;
  13821. });
  13822. });
  13823. svr.Get("/chunked", [&](const Request &, Response &res) {
  13824. auto i = new size_t(0);
  13825. res.set_chunked_content_provider(
  13826. "text/plain",
  13827. [i](size_t, DataSink &sink) {
  13828. if (*i < 5) {
  13829. std::this_thread::sleep_for(std::chrono::seconds(1));
  13830. sink.os << "abcd";
  13831. (*i)++;
  13832. } else {
  13833. sink.done();
  13834. }
  13835. return true;
  13836. },
  13837. [i](bool success) {
  13838. EXPECT_FALSE(success);
  13839. delete i;
  13840. });
  13841. });
  13842. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13843. auto se = detail::scope_exit([&] {
  13844. svr.stop();
  13845. listen_thread.join();
  13846. ASSERT_FALSE(svr.is_running());
  13847. });
  13848. svr.wait_until_ready();
  13849. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13850. {
  13851. auto start = std::chrono::steady_clock::now();
  13852. auto res = cli.Get("/stream");
  13853. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13854. std::chrono::steady_clock::now() - start)
  13855. .count();
  13856. ASSERT_FALSE(res);
  13857. EXPECT_EQ(Error::Read, res.error());
  13858. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13859. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13860. }
  13861. {
  13862. auto start = std::chrono::steady_clock::now();
  13863. auto res = cli.Get("/stream_without_length");
  13864. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13865. std::chrono::steady_clock::now() - start)
  13866. .count();
  13867. ASSERT_FALSE(res);
  13868. EXPECT_EQ(Error::Read, res.error());
  13869. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13870. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13871. }
  13872. {
  13873. auto start = std::chrono::steady_clock::now();
  13874. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13875. EXPECT_EQ("abcd", string(data, data_length));
  13876. return true;
  13877. });
  13878. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13879. std::chrono::steady_clock::now() - start)
  13880. .count();
  13881. ASSERT_FALSE(res);
  13882. EXPECT_EQ(Error::Read, res.error());
  13883. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13884. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13885. }
  13886. }
  13887. TEST(MaxTimeoutTest, ContentStream) {
  13888. time_t timeout = 2000;
  13889. time_t threshold = 200;
  13890. Server svr;
  13891. Client cli("localhost", PORT);
  13892. max_timeout_test(svr, cli, timeout, threshold);
  13893. }
  13894. #ifdef CPPHTTPLIB_SSL_ENABLED
  13895. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13896. time_t timeout = 2000;
  13897. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13899. SSLClient cli("localhost", PORT);
  13900. cli.enable_server_certificate_verification(false);
  13901. max_timeout_test(svr, cli, timeout, threshold);
  13902. }
  13903. #endif
  13904. class EventDispatcher {
  13905. public:
  13906. EventDispatcher() {}
  13907. bool wait_event(DataSink *sink) {
  13908. unique_lock<mutex> lk(m_);
  13909. int id = id_;
  13910. // Wait with timeout to prevent hanging if client disconnects
  13911. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13912. [&] { return cid_ == id; })) {
  13913. return false; // Timeout occurred
  13914. }
  13915. sink->write(message_.data(), message_.size());
  13916. return true;
  13917. }
  13918. void send_event(const string &message) {
  13919. lock_guard<mutex> lk(m_);
  13920. cid_ = id_++;
  13921. message_ = message;
  13922. cv_.notify_all();
  13923. }
  13924. private:
  13925. mutex m_;
  13926. condition_variable cv_;
  13927. atomic_int id_{0};
  13928. atomic_int cid_{-1};
  13929. string message_;
  13930. };
  13931. TEST(ClientInThreadTest, Issue2068) {
  13932. EventDispatcher ed;
  13933. Server svr;
  13934. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13935. res.set_chunked_content_provider("text/event-stream",
  13936. [&](size_t /*offset*/, DataSink &sink) {
  13937. return ed.wait_event(&sink);
  13938. });
  13939. });
  13940. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13941. svr.wait_until_ready();
  13942. thread event_thread([&] {
  13943. int id = 0;
  13944. while (svr.is_running()) {
  13945. this_thread::sleep_for(chrono::milliseconds(500));
  13946. std::stringstream ss;
  13947. ss << "data: " << id << "\n\n";
  13948. ed.send_event(ss.str());
  13949. id++;
  13950. }
  13951. });
  13952. auto se = detail::scope_exit([&] {
  13953. svr.stop();
  13954. listen_thread.join();
  13955. event_thread.join();
  13956. ASSERT_FALSE(svr.is_running());
  13957. });
  13958. {
  13959. auto client = detail::make_unique<Client>(HOST, PORT);
  13960. client->set_read_timeout(std::chrono::minutes(10));
  13961. std::atomic<bool> stop{false};
  13962. std::thread t([&] {
  13963. client->Get("/event1",
  13964. [&](const char *, size_t) -> bool { return !stop; });
  13965. });
  13966. std::this_thread::sleep_for(std::chrono::seconds(2));
  13967. stop = true;
  13968. client->stop();
  13969. t.join();
  13970. // Reset client after thread has finished
  13971. client.reset();
  13972. }
  13973. }
  13974. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13975. auto handled = false;
  13976. Server svr;
  13977. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13978. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13979. auto se = detail::scope_exit([&] {
  13980. svr.stop();
  13981. t.join();
  13982. ASSERT_FALSE(svr.is_running());
  13983. ASSERT_FALSE(handled);
  13984. });
  13985. svr.wait_until_ready();
  13986. // Two Content-Length headers with different values — must be rejected
  13987. auto req = "POST /test HTTP/1.1\r\n"
  13988. "Content-Length: 5\r\n"
  13989. "Content-Length: 10\r\n"
  13990. "\r\n"
  13991. "hello";
  13992. std::string response;
  13993. ASSERT_TRUE(send_request(1, req, &response));
  13994. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13995. response.substr(0, response.find("\r\n")));
  13996. }
  13997. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13998. auto handled = false;
  13999. Server svr;
  14000. svr.Post("/test", [&](const Request &, Response &res) {
  14001. handled = true;
  14002. res.set_content("ok", "text/plain");
  14003. });
  14004. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14005. auto se = detail::scope_exit([&] {
  14006. svr.stop();
  14007. t.join();
  14008. ASSERT_FALSE(svr.is_running());
  14009. ASSERT_TRUE(handled);
  14010. });
  14011. svr.wait_until_ready();
  14012. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  14013. auto req = "POST /test HTTP/1.1\r\n"
  14014. "Content-Length: 5\r\n"
  14015. "Content-Length: 5\r\n"
  14016. "\r\n"
  14017. "hello";
  14018. std::string response;
  14019. ASSERT_TRUE(send_request(1, req, &response));
  14020. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  14021. }
  14022. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  14023. Server svr;
  14024. svr.Get("/", [](const Request &req, Response &res) {
  14025. EXPECT_EQ(2U, req.trailers.size());
  14026. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  14027. // Denied
  14028. EXPECT_FALSE(req.has_trailer("Content-Length"));
  14029. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  14030. // Accepted
  14031. EXPECT_TRUE(req.has_trailer("X-Hello"));
  14032. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  14033. EXPECT_TRUE(req.has_trailer("X-World"));
  14034. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  14035. res.set_content("ok", "text/plain");
  14036. });
  14037. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14038. auto se = detail::scope_exit([&] {
  14039. svr.stop();
  14040. t.join();
  14041. ASSERT_FALSE(svr.is_running());
  14042. });
  14043. svr.wait_until_ready();
  14044. const std::string req = "GET / HTTP/1.1\r\n"
  14045. "Transfer-Encoding: chunked\r\n"
  14046. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  14047. "\r\n"
  14048. "0\r\n"
  14049. "Content-Length: 10\r\n"
  14050. "Host: internal.local\r\n"
  14051. "Content-Type: malicious/content\r\n"
  14052. "Cookie: any\r\n"
  14053. "Set-Cookie: any\r\n"
  14054. "X-Forwarded-For: attacker.com\r\n"
  14055. "X-Real-Ip: 1.1.1.1\r\n"
  14056. "X-Hello: hello\r\n"
  14057. "X-World: world\r\n"
  14058. "\r\n";
  14059. std::string res;
  14060. ASSERT_TRUE(send_request(1, req, &res));
  14061. }
  14062. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  14063. // several field lines, and the combined value is what has to be parsed. A
  14064. // Trailer field split across lines therefore declares every name it lists;
  14065. // reading only the first line silently drops the trailers the later lines
  14066. // declare. The prohibited-trailer filter still applies to every line.
  14067. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  14068. Server svr;
  14069. size_t observed_trailer_count = 0;
  14070. std::string observed_hello;
  14071. std::string observed_world;
  14072. bool observed_content_length = true;
  14073. svr.Get("/", [&](const Request &req, Response &res) {
  14074. observed_trailer_count = req.trailers.size();
  14075. observed_hello = req.get_trailer_value("X-Hello");
  14076. observed_world = req.get_trailer_value("X-World");
  14077. observed_content_length = req.has_trailer("Content-Length");
  14078. res.set_content("ok", "text/plain");
  14079. });
  14080. auto port = svr.bind_to_any_port(HOST);
  14081. thread t = thread([&]() { svr.listen_after_bind(); });
  14082. auto se = detail::scope_exit([&] {
  14083. svr.stop();
  14084. t.join();
  14085. ASSERT_FALSE(svr.is_running());
  14086. });
  14087. svr.wait_until_ready();
  14088. const std::string req = "GET / HTTP/1.1\r\n"
  14089. "Transfer-Encoding: chunked\r\n"
  14090. "Trailer: X-Hello\r\n"
  14091. "Trailer: X-World, Content-Length\r\n"
  14092. "\r\n"
  14093. "0\r\n"
  14094. "X-Hello: hello\r\n"
  14095. "X-World: world\r\n"
  14096. "Content-Length: 10\r\n"
  14097. "\r\n";
  14098. std::string res;
  14099. ASSERT_TRUE(send_request(1, req, &res, port));
  14100. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  14101. // Accepted: both field lines contribute to the declared set
  14102. EXPECT_EQ(2U, observed_trailer_count);
  14103. EXPECT_EQ(observed_hello, "hello");
  14104. EXPECT_EQ(observed_world, "world");
  14105. // Denied: a prohibited name stays prohibited on a later field line
  14106. EXPECT_FALSE(observed_content_length);
  14107. }
  14108. // A direct client that is not listed in trusted_proxies must not be able to
  14109. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  14110. // the peer address on the actual TCP connection determines whether the
  14111. // header is honored.
  14112. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  14113. Server svr;
  14114. // Deliberately does NOT include the loopback address the test client
  14115. // actually connects from, so the direct connection is not a trusted proxy.
  14116. svr.set_trusted_proxies({"203.0.113.66"});
  14117. std::string observed_remote_addr;
  14118. svr.Get("/ip", [&](const Request &req, Response &res) {
  14119. observed_remote_addr = req.remote_addr;
  14120. res.set_content("ok", "text/plain");
  14121. });
  14122. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14123. auto se = detail::scope_exit([&] {
  14124. svr.stop();
  14125. t.join();
  14126. ASSERT_FALSE(svr.is_running());
  14127. });
  14128. svr.wait_until_ready();
  14129. Client cli(HOST, PORT);
  14130. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  14131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14132. EXPECT_EQ(StatusCode::OK_200, res->status);
  14133. // The connecting peer is not a trusted proxy, so the spoofed header must be
  14134. // ignored entirely and the real connection-level address retained.
  14135. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14136. observed_remote_addr == "127.0.0.1");
  14137. }
  14138. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  14139. Server svr;
  14140. std::string observed_remote_addr;
  14141. std::string observed_xff;
  14142. svr.Get("/ip", [&](const Request &req, Response &res) {
  14143. observed_remote_addr = req.remote_addr;
  14144. observed_xff = req.get_header_value("X-Forwarded-For");
  14145. res.set_content("ok", "text/plain");
  14146. });
  14147. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14148. auto se = detail::scope_exit([&] {
  14149. svr.stop();
  14150. t.join();
  14151. ASSERT_FALSE(svr.is_running());
  14152. });
  14153. svr.wait_until_ready();
  14154. Client cli(HOST, PORT);
  14155. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  14156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14157. EXPECT_EQ(StatusCode::OK_200, res->status);
  14158. EXPECT_EQ(observed_xff, "203.0.113.66");
  14159. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14160. observed_remote_addr == "127.0.0.1");
  14161. }
  14162. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  14163. Server svr;
  14164. svr.set_trusted_proxies({"203.0.113.66"});
  14165. std::string observed_remote_addr;
  14166. std::string observed_xff;
  14167. svr.Get("/ip", [&](const Request &req, Response &res) {
  14168. observed_remote_addr = req.remote_addr;
  14169. observed_xff = req.get_header_value("X-Forwarded-For");
  14170. res.set_content("ok", "text/plain");
  14171. });
  14172. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14173. auto se = detail::scope_exit([&] {
  14174. svr.stop();
  14175. t.join();
  14176. ASSERT_FALSE(svr.is_running());
  14177. });
  14178. svr.wait_until_ready();
  14179. Client cli(HOST, PORT);
  14180. auto res = cli.Get("/ip");
  14181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14182. EXPECT_EQ(StatusCode::OK_200, res->status);
  14183. EXPECT_EQ(observed_xff, "");
  14184. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14185. observed_remote_addr == "127.0.0.1");
  14186. }
  14187. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  14188. Server svr;
  14189. // Include the loopback address the test client actually connects from, so
  14190. // the direct connection itself is recognized as the trusted proxy hop.
  14191. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  14192. std::string observed_remote_addr;
  14193. std::string observed_xff;
  14194. svr.Get("/ip", [&](const Request &req, Response &res) {
  14195. observed_remote_addr = req.remote_addr;
  14196. observed_xff = req.get_header_value("X-Forwarded-For");
  14197. res.set_content("ok", "text/plain");
  14198. });
  14199. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14200. auto se = detail::scope_exit([&] {
  14201. svr.stop();
  14202. t.join();
  14203. ASSERT_FALSE(svr.is_running());
  14204. });
  14205. svr.wait_until_ready();
  14206. Client cli(HOST, PORT);
  14207. auto res = cli.Get(
  14208. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  14209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14210. EXPECT_EQ(StatusCode::OK_200, res->status);
  14211. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  14212. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14213. }
  14214. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  14215. Server svr;
  14216. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  14217. std::string observed_remote_addr;
  14218. std::string observed_xff;
  14219. svr.Get("/ip", [&](const Request &req, Response &res) {
  14220. observed_remote_addr = req.remote_addr;
  14221. observed_xff = req.get_header_value("X-Forwarded-For");
  14222. res.set_content("ok", "text/plain");
  14223. });
  14224. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14225. auto se = detail::scope_exit([&] {
  14226. svr.stop();
  14227. t.join();
  14228. ASSERT_FALSE(svr.is_running());
  14229. });
  14230. svr.wait_until_ready();
  14231. Client cli(HOST, PORT);
  14232. auto res = cli.Get(
  14233. "/ip",
  14234. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14236. EXPECT_EQ(StatusCode::OK_200, res->status);
  14237. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14238. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14239. }
  14240. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  14241. Server svr;
  14242. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14243. std::string observed_remote_addr;
  14244. std::string observed_xff;
  14245. svr.Get("/ip", [&](const Request &req, Response &res) {
  14246. observed_remote_addr = req.remote_addr;
  14247. observed_xff = req.get_header_value("X-Forwarded-For");
  14248. res.set_content("ok", "text/plain");
  14249. });
  14250. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14251. auto se = detail::scope_exit([&] {
  14252. svr.stop();
  14253. t.join();
  14254. ASSERT_FALSE(svr.is_running());
  14255. });
  14256. svr.wait_until_ready();
  14257. Client cli(HOST, PORT);
  14258. auto res = cli.Get(
  14259. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  14260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14261. EXPECT_EQ(StatusCode::OK_200, res->status);
  14262. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  14263. // by the closest hop) is used. The leftmost entry is fully client-controlled
  14264. // and must not be selected.
  14265. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  14266. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  14267. }
  14268. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  14269. Server svr;
  14270. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14271. std::string observed_remote_addr;
  14272. svr.Get("/ip", [&](const Request &req, Response &res) {
  14273. observed_remote_addr = req.remote_addr;
  14274. res.set_content("ok", "text/plain");
  14275. });
  14276. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14277. auto se = detail::scope_exit([&] {
  14278. svr.stop();
  14279. t.join();
  14280. ASSERT_FALSE(svr.is_running());
  14281. });
  14282. svr.wait_until_ready();
  14283. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14284. // a forged address and the trusted proxy's own address; the forged value must
  14285. // not win over the address the trusted proxy actually recorded.
  14286. Client cli(HOST, PORT);
  14287. auto res = cli.Get(
  14288. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14290. EXPECT_EQ(StatusCode::OK_200, res->status);
  14291. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14292. }
  14293. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14294. Server svr;
  14295. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14296. std::string observed_remote_addr;
  14297. std::string observed_xff;
  14298. svr.Get("/ip", [&](const Request &req, Response &res) {
  14299. observed_remote_addr = req.remote_addr;
  14300. observed_xff = req.get_header_value("X-Forwarded-For");
  14301. res.set_content("ok", "text/plain");
  14302. });
  14303. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14304. auto se = detail::scope_exit([&] {
  14305. svr.stop();
  14306. t.join();
  14307. ASSERT_FALSE(svr.is_running());
  14308. });
  14309. svr.wait_until_ready();
  14310. Client cli(HOST, PORT);
  14311. auto res = cli.Get(
  14312. "/ip",
  14313. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14315. EXPECT_EQ(StatusCode::OK_200, res->status);
  14316. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14317. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14318. }
  14319. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14320. Server svr;
  14321. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14322. std::string observed_remote_addr;
  14323. std::string observed_xff;
  14324. svr.Get("/ip", [&](const Request &req, Response &res) {
  14325. observed_remote_addr = req.remote_addr;
  14326. observed_xff = req.get_header_value("X-Forwarded-For");
  14327. res.set_content("ok", "text/plain");
  14328. });
  14329. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14330. auto se = detail::scope_exit([&] {
  14331. svr.stop();
  14332. t.join();
  14333. ASSERT_FALSE(svr.is_running());
  14334. });
  14335. svr.wait_until_ready();
  14336. std::string raw_req =
  14337. "GET /ip HTTP/1.1\r\n"
  14338. "Host: localhost\r\n"
  14339. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14340. "Connection: close\r\n"
  14341. "\r\n";
  14342. std::string out;
  14343. ASSERT_TRUE(send_request(5, raw_req, &out));
  14344. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14345. // Header parser trims surrounding whitespace of the header value
  14346. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14347. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14348. }
  14349. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  14350. // one comma-joined value, in the order received. Proxies such as HAProxy append
  14351. // their own X-Forwarded-For as a separate field line rather than extending the
  14352. // one the client sent, so every occurrence has to be taken into account.
  14353. // Reading only the first one hands back the address the client chose.
  14354. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  14355. Server svr;
  14356. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14357. std::string observed_remote_addr;
  14358. size_t observed_xff_count = 0;
  14359. svr.Get("/ip", [&](const Request &req, Response &res) {
  14360. observed_remote_addr = req.remote_addr;
  14361. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  14362. res.set_content("ok", "text/plain");
  14363. });
  14364. auto port = svr.bind_to_any_port(HOST);
  14365. thread t = thread([&]() { svr.listen_after_bind(); });
  14366. auto se = detail::scope_exit([&] {
  14367. svr.stop();
  14368. t.join();
  14369. ASSERT_FALSE(svr.is_running());
  14370. });
  14371. svr.wait_until_ready();
  14372. // The client supplies the first field line; the trusted proxy appends the
  14373. // address it observed as a second one.
  14374. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  14375. "Host: localhost\r\n"
  14376. "X-Forwarded-For: 1.2.3.4\r\n"
  14377. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  14378. "Connection: close\r\n"
  14379. "\r\n";
  14380. std::string out;
  14381. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14382. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14383. EXPECT_EQ(observed_xff_count, 2U);
  14384. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14385. // The same chain spread over one field line per hop derives the same client
  14386. // address, i.e. the split and the comma-joined representations agree.
  14387. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  14388. "Host: localhost\r\n"
  14389. "X-Forwarded-For: 1.2.3.4\r\n"
  14390. "X-Forwarded-For: 198.51.100.23\r\n"
  14391. "X-Forwarded-For: 192.0.2.45\r\n"
  14392. "Connection: close\r\n"
  14393. "\r\n";
  14394. out.clear();
  14395. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  14396. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14397. EXPECT_EQ(observed_xff_count, 3U);
  14398. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  14399. }
  14400. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14401. // crash the server (it used to call front() on an empty vector inside
  14402. // get_client_ip). The connection-level remote address must be retained instead.
  14403. static void run_malformed_xff_test(const std::string &xff_value) {
  14404. Server svr;
  14405. svr.set_trusted_proxies({"192.0.2.45"});
  14406. std::string observed_remote_addr;
  14407. svr.Get("/ip", [&](const Request &req, Response &res) {
  14408. observed_remote_addr = req.remote_addr;
  14409. res.set_content("ok", "text/plain");
  14410. });
  14411. int port = 0;
  14412. thread t = thread([&]() {
  14413. port = svr.bind_to_any_port(HOST);
  14414. svr.listen_after_bind();
  14415. });
  14416. auto se = detail::scope_exit([&] {
  14417. svr.stop();
  14418. t.join();
  14419. ASSERT_FALSE(svr.is_running());
  14420. });
  14421. svr.wait_until_ready();
  14422. Client cli(HOST, port);
  14423. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  14424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14425. EXPECT_EQ(StatusCode::OK_200, res->status);
  14426. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14427. observed_remote_addr == "127.0.0.1");
  14428. }
  14429. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  14430. run_malformed_xff_test("");
  14431. }
  14432. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  14433. run_malformed_xff_test(",");
  14434. }
  14435. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  14436. run_malformed_xff_test(", , ,");
  14437. }
  14438. // The same rule applies to Accept: a request whose acceptable types are spread
  14439. // over several field lines must be negotiated against all of them.
  14440. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  14441. // case-insensitive connection options. Comparing the whole field value against
  14442. // one option misses a client that sends several of them, and misses every
  14443. // casing but the one written in the comparison.
  14444. //
  14445. // Sends req, reads the response, then reuses the same socket for a second
  14446. // request to find out whether the server kept the connection.
  14447. static void probe_connection_reuse(int port, const std::string &req,
  14448. bool *announced_close, bool *reusable) {
  14449. auto error = Error::Success;
  14450. auto sock = detail::create_client_socket(
  14451. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  14452. /*connection_timeout_sec=*/5, 0,
  14453. /*read_timeout_sec=*/1, 0,
  14454. /*write_timeout_sec=*/5, 0, std::string(), error);
  14455. ASSERT_NE(sock, INVALID_SOCKET);
  14456. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  14457. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  14458. "Host: localhost\r\n"
  14459. "Connection: close\r\n"
  14460. "\r\n";
  14461. std::string first_response;
  14462. std::string second_response;
  14463. detail::process_client_socket(
  14464. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  14465. [&](Stream &strm) {
  14466. if (strm.write(req.data(), req.size()) !=
  14467. static_cast<ssize_t>(req.size())) {
  14468. return false;
  14469. }
  14470. char buf[512];
  14471. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  14472. // Headers plus the two-byte body of the handler below
  14473. while (reader.getline()) {
  14474. first_response += reader.ptr();
  14475. if (first_response.find("ok") != std::string::npos) { break; }
  14476. }
  14477. if (strm.write(second.data(), second.size()) !=
  14478. static_cast<ssize_t>(second.size())) {
  14479. return true;
  14480. }
  14481. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  14482. while (reader2.getline()) {
  14483. second_response += reader2.ptr();
  14484. if (second_response.find("ok") != std::string::npos) { break; }
  14485. }
  14486. return true;
  14487. });
  14488. *announced_close =
  14489. first_response.find("Connection: close") != std::string::npos;
  14490. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  14491. }
  14492. class ConnectionTokenTest : public ::testing::Test {
  14493. protected:
  14494. void SetUp() override {
  14495. svr_.Get("/keepalive", [](const Request &, Response &res) {
  14496. res.set_content("ok", "text/plain");
  14497. });
  14498. port_ = svr_.bind_to_any_port(HOST);
  14499. thread_ = thread([&]() { svr_.listen_after_bind(); });
  14500. svr_.wait_until_ready();
  14501. }
  14502. void TearDown() override {
  14503. svr_.stop();
  14504. if (thread_.joinable()) { thread_.join(); }
  14505. }
  14506. Server svr_;
  14507. int port_ = 0;
  14508. thread thread_;
  14509. };
  14510. // "close" alongside another option still closes the connection, and the
  14511. // response says so rather than leaving the peer to discover it.
  14512. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  14513. bool announced_close = false;
  14514. bool reusable = true;
  14515. probe_connection_reuse(port_,
  14516. "GET /keepalive HTTP/1.1\r\n"
  14517. "Host: localhost\r\n"
  14518. "Connection: keep-alive, close\r\n"
  14519. "\r\n",
  14520. &announced_close, &reusable);
  14521. EXPECT_TRUE(announced_close);
  14522. EXPECT_FALSE(reusable);
  14523. }
  14524. // "close" split over two field lines is the same list, so it is honored too.
  14525. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  14526. bool announced_close = false;
  14527. bool reusable = true;
  14528. probe_connection_reuse(port_,
  14529. "GET /keepalive HTTP/1.1\r\n"
  14530. "Host: localhost\r\n"
  14531. "Connection: keep-alive\r\n"
  14532. "Connection: close\r\n"
  14533. "\r\n",
  14534. &announced_close, &reusable);
  14535. EXPECT_TRUE(announced_close);
  14536. EXPECT_FALSE(reusable);
  14537. }
  14538. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  14539. // keep-alive in the spelling everyone actually sends keeps its connection.
  14540. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  14541. bool announced_close = false;
  14542. bool reusable = false;
  14543. probe_connection_reuse(port_,
  14544. "GET /keepalive HTTP/1.0\r\n"
  14545. "Host: localhost\r\n"
  14546. "Connection: keep-alive\r\n"
  14547. "\r\n",
  14548. &announced_close, &reusable);
  14549. EXPECT_FALSE(announced_close);
  14550. EXPECT_TRUE(reusable);
  14551. }
  14552. // A token the value merely contains is not the token itself.
  14553. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  14554. bool announced_close = false;
  14555. bool reusable = false;
  14556. probe_connection_reuse(port_,
  14557. "GET /keepalive HTTP/1.1\r\n"
  14558. "Host: localhost\r\n"
  14559. "Connection: notclose\r\n"
  14560. "\r\n",
  14561. &announced_close, &reusable);
  14562. EXPECT_FALSE(announced_close);
  14563. EXPECT_TRUE(reusable);
  14564. }
  14565. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  14566. Server svr;
  14567. std::vector<std::string> observed_types;
  14568. svr.Get("/", [&](const Request &req, Response &res) {
  14569. observed_types = req.accept_content_types;
  14570. res.set_content("ok", "text/plain");
  14571. });
  14572. auto port = svr.bind_to_any_port(HOST);
  14573. thread t = thread([&]() { svr.listen_after_bind(); });
  14574. auto se = detail::scope_exit([&] {
  14575. svr.stop();
  14576. t.join();
  14577. ASSERT_FALSE(svr.is_running());
  14578. });
  14579. svr.wait_until_ready();
  14580. Client cli(HOST, port);
  14581. Headers headers;
  14582. headers.emplace("Accept", "text/plain;q=0.5");
  14583. headers.emplace("Accept", "application/json");
  14584. auto res = cli.Get("/", headers);
  14585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14586. EXPECT_EQ(StatusCode::OK_200, res->status);
  14587. // Sorted by q-value, so the second field line's type comes first
  14588. ASSERT_EQ(2U, observed_types.size());
  14589. EXPECT_EQ("application/json", observed_types[0]);
  14590. EXPECT_EQ("text/plain", observed_types[1]);
  14591. }
  14592. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  14593. // empty field line must not contribute a bare comma to the combined value.
  14594. // parse_accept_header() rejects a leading comma outright, so a stray one would
  14595. // turn a legal request into 400 Bad Request.
  14596. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  14597. Server svr;
  14598. std::vector<std::string> observed_types;
  14599. svr.Get("/", [&](const Request &req, Response &res) {
  14600. observed_types = req.accept_content_types;
  14601. res.set_content("ok", "text/plain");
  14602. });
  14603. auto port = svr.bind_to_any_port(HOST);
  14604. thread t = thread([&]() { svr.listen_after_bind(); });
  14605. auto se = detail::scope_exit([&] {
  14606. svr.stop();
  14607. t.join();
  14608. ASSERT_FALSE(svr.is_running());
  14609. });
  14610. svr.wait_until_ready();
  14611. // Empty first field line, then a real one
  14612. std::string raw_req = "GET / HTTP/1.1\r\n"
  14613. "Host: localhost\r\n"
  14614. "Accept:\r\n"
  14615. "Accept: application/json\r\n"
  14616. "Connection: close\r\n"
  14617. "\r\n";
  14618. std::string out;
  14619. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  14620. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14621. ASSERT_EQ(1U, observed_types.size());
  14622. EXPECT_EQ("application/json", observed_types[0]);
  14623. }
  14624. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14625. // An encoding offered on a later Accept-Encoding field line is still offered.
  14626. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  14627. Server svr;
  14628. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14629. res.set_content(std::string(1024, 'x'), "text/plain");
  14630. });
  14631. auto port = svr.bind_to_any_port(HOST);
  14632. thread t = thread([&]() { svr.listen_after_bind(); });
  14633. auto se = detail::scope_exit([&] {
  14634. svr.stop();
  14635. t.join();
  14636. ASSERT_FALSE(svr.is_running());
  14637. });
  14638. svr.wait_until_ready();
  14639. Client cli(HOST, port);
  14640. cli.set_decompress(false);
  14641. Headers headers;
  14642. headers.emplace("Accept-Encoding", "identity");
  14643. headers.emplace("Accept-Encoding", "gzip");
  14644. auto res = cli.Get("/", headers);
  14645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14646. EXPECT_EQ(StatusCode::OK_200, res->status);
  14647. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  14648. }
  14649. #endif
  14650. #ifndef _WIN32
  14651. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  14652. Server svr;
  14653. svr.Post("/post", [&](const Request &req, Response &res) {
  14654. res.set_content(req.body, "text/plain");
  14655. });
  14656. svr.Put("/put", [&](const Request &req, Response &res) {
  14657. res.set_content(req.body, "text/plain");
  14658. });
  14659. svr.Patch("/patch", [&](const Request &req, Response &res) {
  14660. res.set_content(req.body, "text/plain");
  14661. });
  14662. svr.Delete("/delete", [&](const Request &req, Response &res) {
  14663. res.set_content(req.body, "text/plain");
  14664. });
  14665. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14666. auto se = detail::scope_exit([&] {
  14667. svr.stop();
  14668. t.join();
  14669. ASSERT_FALSE(svr.is_running());
  14670. });
  14671. svr.wait_until_ready();
  14672. std::string resp;
  14673. // POST without Content-Length
  14674. ASSERT_TRUE(send_request(5,
  14675. "POST /post HTTP/1.1\r\n"
  14676. "Host: localhost\r\n"
  14677. "Connection: close\r\n"
  14678. "\r\n",
  14679. &resp));
  14680. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14681. // PUT without Content-Length
  14682. resp.clear();
  14683. ASSERT_TRUE(send_request(5,
  14684. "PUT /put HTTP/1.1\r\n"
  14685. "Host: localhost\r\n"
  14686. "Connection: close\r\n"
  14687. "\r\n",
  14688. &resp));
  14689. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14690. // PATCH without Content-Length
  14691. resp.clear();
  14692. ASSERT_TRUE(send_request(5,
  14693. "PATCH /patch HTTP/1.1\r\n"
  14694. "Host: localhost\r\n"
  14695. "Connection: close\r\n"
  14696. "\r\n",
  14697. &resp));
  14698. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14699. // DELETE without Content-Length
  14700. resp.clear();
  14701. ASSERT_TRUE(send_request(5,
  14702. "DELETE /delete HTTP/1.1\r\n"
  14703. "Host: localhost\r\n"
  14704. "Connection: close\r\n"
  14705. "\r\n",
  14706. &resp));
  14707. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14708. }
  14709. #endif
  14710. //==============================================================================
  14711. // open_stream() Tests
  14712. //==============================================================================
  14713. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  14714. std::string result;
  14715. char buf[8192];
  14716. ssize_t n;
  14717. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14718. result.append(buf, static_cast<size_t>(n));
  14719. }
  14720. return result;
  14721. }
  14722. // Mock stream for unit tests
  14723. class MockStream : public Stream {
  14724. public:
  14725. std::string data;
  14726. size_t pos = 0;
  14727. ssize_t error_after = -1; // -1 = no error
  14728. explicit MockStream(const std::string &d, ssize_t err = -1)
  14729. : data(d), error_after(err) {}
  14730. bool is_readable() const override { return true; }
  14731. bool wait_readable() const override { return true; }
  14732. bool wait_writable() const override { return true; }
  14733. ssize_t read(char *ptr, size_t size) override {
  14734. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  14735. if (pos >= data.size()) return 0;
  14736. size_t limit =
  14737. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  14738. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  14739. std::memcpy(ptr, data.data() + pos, to_read);
  14740. pos += to_read;
  14741. return static_cast<ssize_t>(to_read);
  14742. }
  14743. ssize_t write(const char *, size_t) override { return -1; }
  14744. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  14745. ip = "127.0.0.1";
  14746. port = 0;
  14747. }
  14748. void get_local_ip_and_port(std::string &ip, int &port) const override {
  14749. ip = "127.0.0.1";
  14750. port = 0;
  14751. }
  14752. socket_t socket() const override { return INVALID_SOCKET; }
  14753. time_t duration() const override { return 0; }
  14754. };
  14755. TEST(StreamHandleTest, Basic) {
  14756. ClientImpl::StreamHandle handle;
  14757. EXPECT_FALSE(handle.is_valid());
  14758. handle.response = detail::make_unique<Response>();
  14759. handle.error = Error::Connection;
  14760. EXPECT_FALSE(handle.is_valid());
  14761. handle.error = Error::Success;
  14762. EXPECT_TRUE(handle.is_valid());
  14763. }
  14764. TEST(BodyReaderTest, Basic) {
  14765. MockStream stream("Hello, World!");
  14766. detail::BodyReader reader;
  14767. reader.stream = &stream;
  14768. reader.content_length = 13;
  14769. char buf[32];
  14770. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  14771. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  14772. EXPECT_TRUE(reader.eof);
  14773. }
  14774. TEST(BodyReaderTest, NoStream) {
  14775. detail::BodyReader reader;
  14776. char buf[32];
  14777. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14778. EXPECT_EQ(Error::Connection, reader.last_error);
  14779. }
  14780. TEST(BodyReaderTest, Error) {
  14781. MockStream stream("Hello, World!", 5);
  14782. detail::BodyReader reader;
  14783. reader.stream = &stream;
  14784. reader.content_length = 13;
  14785. char buf[32];
  14786. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  14787. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14788. EXPECT_EQ(Error::Read, reader.last_error);
  14789. }
  14790. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  14791. // Mock-based StreamHandle tests relying on private internals are removed.
  14792. class OpenStreamTest : public ::testing::Test {
  14793. protected:
  14794. void SetUp() override {
  14795. svr_.Get("/hello", [](const Request &, Response &res) {
  14796. res.set_content("Hello World!", "text/plain");
  14797. });
  14798. svr_.Get("/large", [](const Request &, Response &res) {
  14799. res.set_content(std::string(10000, 'X'), "text/plain");
  14800. });
  14801. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  14802. res.set_content("Hello World!", "image/jpeg");
  14803. res.set_header("Content-Encoding", "UTF-8");
  14804. });
  14805. svr_.Get("/chunked", [](const Request &, Response &res) {
  14806. res.set_chunked_content_provider("text/plain",
  14807. [](size_t offset, DataSink &sink) {
  14808. if (offset < 15) {
  14809. sink.write("chunk", 5);
  14810. return true;
  14811. }
  14812. sink.done();
  14813. return true;
  14814. });
  14815. });
  14816. svr_.Get("/compressible", [](const Request &, Response &res) {
  14817. res.set_chunked_content_provider("text/plain", [](size_t offset,
  14818. DataSink &sink) {
  14819. if (offset < 100 * 1024) {
  14820. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  14821. sink.write(chunk.data(), chunk.size());
  14822. return true;
  14823. }
  14824. sink.done();
  14825. return true;
  14826. });
  14827. });
  14828. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  14829. [](const Request & /*req*/, Response &res) {
  14830. auto i = new int(0);
  14831. res.set_header("Trailer", "Content-Length, X-Allowed");
  14832. res.set_chunked_content_provider(
  14833. "text/plain",
  14834. [i](size_t /*offset*/, DataSink &sink) {
  14835. switch (*i) {
  14836. case 0: sink.os << "123"; break;
  14837. case 1: sink.os << "456"; break;
  14838. case 2: sink.os << "789"; break;
  14839. case 3: {
  14840. sink.done_with_trailer(
  14841. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  14842. } break;
  14843. }
  14844. (*i)++;
  14845. return true;
  14846. },
  14847. [i](bool success) {
  14848. EXPECT_TRUE(success);
  14849. delete i;
  14850. });
  14851. });
  14852. // Echo headers endpoint for header-related tests
  14853. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  14854. std::string body;
  14855. for (const auto &h : req.headers) {
  14856. body.append(h.first);
  14857. body.push_back(':');
  14858. body.append(h.second);
  14859. body.push_back('\n');
  14860. }
  14861. res.set_content(body, "text/plain");
  14862. });
  14863. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  14864. std::string body;
  14865. for (const auto &h : req.headers) {
  14866. body.append(h.first);
  14867. body.push_back(':');
  14868. body.append(h.second);
  14869. body.push_back('\n');
  14870. }
  14871. res.set_content(body, "text/plain");
  14872. });
  14873. port_ = svr_.bind_to_any_port("127.0.0.1");
  14874. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14875. svr_.wait_until_ready();
  14876. }
  14877. void TearDown() override {
  14878. svr_.stop();
  14879. if (thread_.joinable()) thread_.join();
  14880. }
  14881. Server svr_;
  14882. std::thread thread_;
  14883. int port_ = 0;
  14884. };
  14885. TEST_F(OpenStreamTest, Basic) {
  14886. Client cli("127.0.0.1", port_);
  14887. auto handle = cli.open_stream("GET", "/hello");
  14888. EXPECT_TRUE(handle.is_valid());
  14889. EXPECT_EQ("Hello World!", read_all(handle));
  14890. }
  14891. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  14892. Client cli("127.0.0.1", port_);
  14893. auto handle = cli.open_stream("GET", "/unknown-encoding");
  14894. ASSERT_TRUE(handle.is_valid());
  14895. EXPECT_EQ("Hello World!", read_all(handle));
  14896. }
  14897. TEST_F(OpenStreamTest, SmallBuffer) {
  14898. Client cli("127.0.0.1", port_);
  14899. auto handle = cli.open_stream("GET", "/hello");
  14900. std::string result;
  14901. char buf[4];
  14902. ssize_t n;
  14903. while ((n = handle.read(buf, sizeof(buf))) > 0)
  14904. result.append(buf, static_cast<size_t>(n));
  14905. EXPECT_EQ("Hello World!", result);
  14906. }
  14907. TEST_F(OpenStreamTest, DefaultHeaders) {
  14908. Client cli("127.0.0.1", port_);
  14909. // open_stream GET should include Host, User-Agent and Accept-Encoding
  14910. {
  14911. auto handle = cli.open_stream("GET", "/echo-headers");
  14912. ASSERT_TRUE(handle.is_valid());
  14913. auto body = read_all(handle);
  14914. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  14915. std::string::npos);
  14916. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  14917. std::string::npos);
  14918. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  14919. }
  14920. // open_stream POST with body and no explicit content_type should NOT add
  14921. // text/plain Content-Type (behavior differs from non-streaming path), but
  14922. // should include Content-Length
  14923. {
  14924. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14925. ASSERT_TRUE(handle.is_valid());
  14926. auto body = read_all(handle);
  14927. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14928. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14929. }
  14930. // open_stream POST with explicit Content-Type should preserve it
  14931. {
  14932. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14933. {{"Content-Type", "application/custom"}},
  14934. "{}", "application/custom");
  14935. ASSERT_TRUE(handle.is_valid());
  14936. auto body = read_all(handle);
  14937. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14938. }
  14939. // User-specified User-Agent must not be overwritten for stream API
  14940. {
  14941. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14942. {{"User-Agent", "MyAgent/1.2"}});
  14943. ASSERT_TRUE(handle.is_valid());
  14944. auto body = read_all(handle);
  14945. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14946. }
  14947. }
  14948. TEST_F(OpenStreamTest, Large) {
  14949. Client cli("127.0.0.1", port_);
  14950. auto handle = cli.open_stream("GET", "/large");
  14951. EXPECT_EQ(10000u, read_all(handle).size());
  14952. }
  14953. TEST_F(OpenStreamTest, ConnectionError) {
  14954. Client cli("127.0.0.1", 9999);
  14955. auto handle = cli.open_stream("GET", "/hello");
  14956. EXPECT_FALSE(handle.is_valid());
  14957. }
  14958. TEST_F(OpenStreamTest, Chunked) {
  14959. Client cli("127.0.0.1", port_);
  14960. auto handle = cli.open_stream("GET", "/chunked");
  14961. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14962. "Transfer-Encoding") == "chunked");
  14963. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14964. }
  14965. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14966. Client cli("127.0.0.1", port_);
  14967. auto handle =
  14968. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14969. ASSERT_TRUE(handle.is_valid());
  14970. // Consume body to allow trailers to be received/parsed
  14971. auto body = read_all(handle);
  14972. // Explicitly parse trailers (ensure trailers are available for assertion)
  14973. handle.parse_trailers_if_needed();
  14974. EXPECT_EQ(std::string("123456789"), body);
  14975. // The response should include a Trailer header declaring both names
  14976. ASSERT_TRUE(handle.response);
  14977. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14978. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14979. handle.response->get_header_value("Trailer"));
  14980. // Prohibited trailer must not be present
  14981. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14982. // Allowed trailer should be present
  14983. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14984. EXPECT_EQ(std::string("yes"),
  14985. handle.response->get_trailer_value("X-Allowed"));
  14986. // Verify trailers are NOT present as regular headers
  14987. EXPECT_EQ(std::string(""),
  14988. handle.response->get_header_value("Content-Length"));
  14989. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14990. }
  14991. static std::thread serve_single_response(std::promise<int> &port_promise,
  14992. const std::string &response) {
  14993. return std::thread([&port_promise, response] {
  14994. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14995. default_socket_options(srv);
  14996. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14997. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14998. sockaddr_in addr{};
  14999. addr.sin_family = AF_INET;
  15000. addr.sin_port = htons(0); // Let OS assign a free port
  15001. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15002. int opt = 1;
  15003. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  15004. #ifdef _WIN32
  15005. reinterpret_cast<const char *>(&opt),
  15006. #else
  15007. &opt,
  15008. #endif
  15009. sizeof(opt));
  15010. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  15011. ::listen(srv, 1) != 0) {
  15012. port_promise.set_value(-1);
  15013. detail::close_socket(srv);
  15014. return;
  15015. }
  15016. socklen_t addr_len = sizeof(addr);
  15017. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  15018. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  15019. sockaddr_in cli_addr{};
  15020. socklen_t cli_len = sizeof(cli_addr);
  15021. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15022. if (cli != INVALID_SOCKET) {
  15023. // Read the complete HTTP request (until the blank line that terminates
  15024. // headers) before sending the response. If the server closes the socket
  15025. // while the client's request data is still unread in the kernel receive
  15026. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  15027. // connection on both sides: it discards the client's receive buffer
  15028. // (which already holds our response) and causes any in-progress write on
  15029. // the client to fail with ECONNRESET. Reading all request data first
  15030. // ensures close() emits a graceful FIN.
  15031. {
  15032. char rbuf[256];
  15033. std::string req;
  15034. while (req.find("\r\n\r\n") == std::string::npos) {
  15035. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  15036. if (n <= 0) { break; }
  15037. req.append(rbuf, static_cast<size_t>(n));
  15038. }
  15039. }
  15040. ::send(cli,
  15041. #ifdef _WIN32
  15042. static_cast<const char *>(response.c_str()),
  15043. static_cast<int>(response.size()),
  15044. #else
  15045. response.c_str(), response.size(),
  15046. #endif
  15047. 0);
  15048. detail::close_socket(cli);
  15049. }
  15050. detail::close_socket(srv);
  15051. });
  15052. }
  15053. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  15054. #ifndef _WIN32
  15055. signal(SIGPIPE, SIG_IGN);
  15056. #endif
  15057. std::promise<int> port_promise;
  15058. auto port_future = port_promise.get_future();
  15059. auto server_thread =
  15060. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  15061. "Content-Type: text/plain\r\n"
  15062. "Content-Length: not-a-number\r\n"
  15063. "Connection: close\r\n"
  15064. "\r\n"
  15065. "hello");
  15066. auto port = port_future.get();
  15067. ASSERT_GT(port, 0);
  15068. Client cli("127.0.0.1", port);
  15069. auto handle = cli.open_stream("GET", "/");
  15070. EXPECT_FALSE(handle.is_valid());
  15071. server_thread.join();
  15072. }
  15073. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  15074. #ifndef _WIN32
  15075. signal(SIGPIPE, SIG_IGN);
  15076. #endif
  15077. std::promise<int> port_promise;
  15078. auto port_future = port_promise.get_future();
  15079. auto server_thread = serve_single_response(
  15080. port_promise, "HTTP/1.1 200 OK\r\n"
  15081. "Content-Type: text/plain\r\n"
  15082. "Content-Length: 99999999999999999999999999\r\n"
  15083. "Connection: close\r\n"
  15084. "\r\n"
  15085. "hello");
  15086. auto port = port_future.get();
  15087. ASSERT_GT(port, 0);
  15088. // Historically std::stoull would throw std::out_of_range here and crash
  15089. // the process, then parsing silently clamped to a bogus framing length and
  15090. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  15091. // so the stream fails to open, matching the not-a-number case above. The
  15092. // process still must NOT terminate.
  15093. Client cli("127.0.0.1", port);
  15094. auto handle = cli.open_stream("GET", "/");
  15095. EXPECT_FALSE(handle.is_valid());
  15096. server_thread.join();
  15097. }
  15098. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15099. TEST_F(OpenStreamTest, Gzip) {
  15100. Client cli("127.0.0.1", port_);
  15101. auto handle = cli.open_stream("GET", "/compressible", {},
  15102. {{"Accept-Encoding", "gzip"}});
  15103. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  15104. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15105. }
  15106. #endif
  15107. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15108. TEST_F(OpenStreamTest, Brotli) {
  15109. Client cli("127.0.0.1", port_);
  15110. auto handle =
  15111. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  15112. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  15113. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15114. }
  15115. #endif
  15116. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15117. TEST_F(OpenStreamTest, Zstd) {
  15118. Client cli("127.0.0.1", port_);
  15119. auto handle = cli.open_stream("GET", "/compressible", {},
  15120. {{"Accept-Encoding", "zstd"}});
  15121. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  15122. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  15123. }
  15124. #endif
  15125. #ifdef CPPHTTPLIB_SSL_ENABLED
  15126. class SSLOpenStreamTest : public ::testing::Test {
  15127. protected:
  15128. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  15129. void SetUp() override {
  15130. svr_.Get("/hello", [](const Request &, Response &res) {
  15131. res.set_content("Hello SSL World!", "text/plain");
  15132. });
  15133. svr_.Get("/chunked", [](const Request &, Response &res) {
  15134. res.set_chunked_content_provider("text/plain",
  15135. [](size_t offset, DataSink &sink) {
  15136. if (offset < 15) {
  15137. sink.write("chunk", 5);
  15138. return true;
  15139. }
  15140. sink.done();
  15141. return true;
  15142. });
  15143. });
  15144. svr_.Post("/echo", [](const Request &req, Response &res) {
  15145. res.set_content(req.body, req.get_header_value("Content-Type"));
  15146. });
  15147. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  15148. std::string body = req.body;
  15149. res.set_chunked_content_provider(
  15150. "text/plain", [body](size_t offset, DataSink &sink) {
  15151. if (offset < body.size()) {
  15152. sink.write(body.data() + offset, body.size() - offset);
  15153. }
  15154. sink.done();
  15155. return true;
  15156. });
  15157. });
  15158. port_ = svr_.bind_to_any_port("127.0.0.1");
  15159. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15160. svr_.wait_until_ready();
  15161. }
  15162. void TearDown() override {
  15163. svr_.stop();
  15164. if (thread_.joinable()) thread_.join();
  15165. }
  15166. SSLServer svr_;
  15167. std::thread thread_;
  15168. int port_ = 0;
  15169. };
  15170. TEST_F(SSLOpenStreamTest, Basic) {
  15171. SSLClient cli("127.0.0.1", port_);
  15172. cli.enable_server_certificate_verification(false);
  15173. auto handle = cli.open_stream("GET", "/hello");
  15174. ASSERT_TRUE(handle.is_valid());
  15175. EXPECT_EQ("Hello SSL World!", read_all(handle));
  15176. }
  15177. TEST_F(SSLOpenStreamTest, Chunked) {
  15178. SSLClient cli("127.0.0.1", port_);
  15179. cli.enable_server_certificate_verification(false);
  15180. auto handle = cli.open_stream("GET", "/chunked");
  15181. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15182. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  15183. "Transfer-Encoding") == "chunked");
  15184. auto body = read_all(handle);
  15185. EXPECT_EQ("chunkchunkchunk", body);
  15186. }
  15187. TEST_F(SSLOpenStreamTest, Post) {
  15188. SSLClient cli("127.0.0.1", port_);
  15189. cli.enable_server_certificate_verification(false);
  15190. auto handle =
  15191. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  15192. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  15193. EXPECT_EQ(200, handle.response->status);
  15194. auto body = read_all(handle);
  15195. EXPECT_EQ("Hello SSL POST", body);
  15196. }
  15197. TEST_F(SSLOpenStreamTest, PostChunked) {
  15198. SSLClient cli("127.0.0.1", port_);
  15199. cli.enable_server_certificate_verification(false);
  15200. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  15201. "Chunked SSL Data", "text/plain");
  15202. ASSERT_TRUE(handle.is_valid());
  15203. EXPECT_EQ(200, handle.response->status);
  15204. auto body = read_all(handle);
  15205. EXPECT_EQ("Chunked SSL Data", body);
  15206. }
  15207. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  15208. // Content-Length is terminated by the server closing the connection. When the
  15209. // SSL peer sends a close_notify after the body, the client must treat it as a
  15210. // clean EOF and return a successful response rather than an error.
  15211. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  15212. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15213. ASSERT_TRUE(svr.is_valid());
  15214. svr.set_keep_alive_max_count(1);
  15215. const std::string expected_body = "Hello from connection-close response!";
  15216. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  15217. res.set_content_provider("text/plain",
  15218. [&](size_t offset, DataSink &sink) -> bool {
  15219. if (offset < expected_body.size()) {
  15220. sink.write(expected_body.data() + offset,
  15221. expected_body.size() - offset);
  15222. }
  15223. sink.done();
  15224. return true;
  15225. });
  15226. });
  15227. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  15228. auto se = detail::scope_exit([&] {
  15229. svr.stop();
  15230. listen_thread.join();
  15231. ASSERT_FALSE(svr.is_running());
  15232. });
  15233. svr.wait_until_ready();
  15234. SSLClient cli(HOST, PORT);
  15235. cli.enable_server_certificate_verification(false);
  15236. auto res = cli.Get("/no-content-length");
  15237. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  15238. EXPECT_EQ(StatusCode::OK_200, res->status);
  15239. EXPECT_EQ(expected_body, res->body);
  15240. }
  15241. #endif // CPPHTTPLIB_SSL_ENABLED
  15242. //==============================================================================
  15243. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  15244. // results for various scenarios.
  15245. //==============================================================================
  15246. TEST(ParityTest, GetVsOpenStream) {
  15247. Server svr;
  15248. const std::string path = "/parity";
  15249. const std::string content = "Parity test content: hello world";
  15250. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15251. res.set_content(content, "text/plain");
  15252. });
  15253. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15254. auto se = detail::scope_exit([&] {
  15255. svr.stop();
  15256. t.join();
  15257. ASSERT_FALSE(svr.is_running());
  15258. });
  15259. svr.wait_until_ready();
  15260. Client cli(HOST, PORT);
  15261. // Non-stream path
  15262. auto r1 = cli.Get(path);
  15263. ASSERT_TRUE(r1);
  15264. EXPECT_EQ(StatusCode::OK_200, r1->status);
  15265. // Stream path
  15266. auto h = cli.open_stream("GET", path);
  15267. ASSERT_TRUE(h.is_valid());
  15268. EXPECT_EQ(r1->body, read_all(h));
  15269. }
  15270. // Helper to compress data with provided compressor type T
  15271. template <typename Compressor>
  15272. static std::string compress_payload_for_parity(const std::string &in) {
  15273. std::string out;
  15274. Compressor compressor;
  15275. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  15276. [&](const char *data, size_t n) {
  15277. out.append(data, n);
  15278. return true;
  15279. });
  15280. EXPECT_TRUE(ok);
  15281. return out;
  15282. }
  15283. // Helper function for compression parity tests
  15284. template <typename Compressor>
  15285. static void test_compression_parity(const std::string &original,
  15286. const std::string &path,
  15287. const std::string &encoding) {
  15288. const std::string compressed =
  15289. compress_payload_for_parity<Compressor>(original);
  15290. Server svr;
  15291. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  15292. res.set_content(compressed, "application/octet-stream");
  15293. res.set_header("Content-Encoding", encoding);
  15294. });
  15295. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  15296. auto se = detail::scope_exit([&] {
  15297. svr.stop();
  15298. t.join();
  15299. ASSERT_FALSE(svr.is_running());
  15300. });
  15301. svr.wait_until_ready();
  15302. Client cli(HOST, PORT);
  15303. // Non-streaming
  15304. {
  15305. auto res = cli.Get(path);
  15306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15307. EXPECT_EQ(StatusCode::OK_200, res->status);
  15308. EXPECT_EQ(original, res->body);
  15309. }
  15310. // Streaming
  15311. {
  15312. auto h = cli.open_stream("GET", path);
  15313. ASSERT_TRUE(h.is_valid());
  15314. EXPECT_EQ(original, read_all(h));
  15315. }
  15316. }
  15317. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15318. TEST(ParityTest, Gzip) {
  15319. test_compression_parity<detail::gzip_compressor>(
  15320. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  15321. }
  15322. #endif
  15323. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15324. TEST(ParityTest, Brotli) {
  15325. test_compression_parity<detail::brotli_compressor>(
  15326. "Hello, brotli parity test payload", "/parity-br", "br");
  15327. }
  15328. #endif
  15329. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  15330. TEST(ParityTest, Zstd) {
  15331. test_compression_parity<detail::zstd_compressor>(
  15332. "Zstandard parity test payload", "/parity-zstd", "zstd");
  15333. }
  15334. #endif
  15335. //==============================================================================
  15336. // New Stream API Tests
  15337. //==============================================================================
  15338. inline std::string read_body(httplib::stream::Result &result) {
  15339. std::string body;
  15340. while (result.next()) {
  15341. body.append(result.data(), result.size());
  15342. }
  15343. return body;
  15344. }
  15345. TEST(ClientConnectionTest, Basic) {
  15346. httplib::ClientConnection conn;
  15347. EXPECT_FALSE(conn.is_open());
  15348. conn.sock = 1;
  15349. EXPECT_TRUE(conn.is_open());
  15350. httplib::ClientConnection conn2(std::move(conn));
  15351. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  15352. conn2.sock = INVALID_SOCKET;
  15353. }
  15354. // Unified test server for all stream::* tests
  15355. class StreamApiTest : public ::testing::Test {
  15356. protected:
  15357. void SetUp() override {
  15358. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15359. res.set_content("Hello World!", "text/plain");
  15360. });
  15361. svr_.Get("/echo-params",
  15362. [](const httplib::Request &req, httplib::Response &res) {
  15363. std::string r;
  15364. for (const auto &p : req.params) {
  15365. if (!r.empty()) r += "&";
  15366. r += p.first + "=" + p.second;
  15367. }
  15368. res.set_content(r, "text/plain");
  15369. });
  15370. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15371. res.set_content(req.body, req.get_header_value("Content-Type"));
  15372. });
  15373. svr_.Post("/echo-headers",
  15374. [](const httplib::Request &req, httplib::Response &res) {
  15375. std::string r;
  15376. for (const auto &h : req.headers)
  15377. r += h.first + ": " + h.second + "\n";
  15378. res.set_content(r, "text/plain");
  15379. });
  15380. svr_.Post("/echo-params",
  15381. [](const httplib::Request &req, httplib::Response &res) {
  15382. std::string r = "params:";
  15383. for (const auto &p : req.params)
  15384. r += p.first + "=" + p.second + ";";
  15385. res.set_content(r + " body:" + req.body, "text/plain");
  15386. });
  15387. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  15388. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  15389. });
  15390. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15391. res.set_content("PUT:" + req.body, "text/plain");
  15392. });
  15393. svr_.Patch("/echo",
  15394. [](const httplib::Request &req, httplib::Response &res) {
  15395. res.set_content("PATCH:" + req.body, "text/plain");
  15396. });
  15397. svr_.Delete(
  15398. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  15399. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  15400. "text/plain");
  15401. });
  15402. svr_.Get("/head-test",
  15403. [](const httplib::Request &, httplib::Response &res) {
  15404. res.set_content("body for HEAD", "text/plain");
  15405. });
  15406. svr_.Options("/options",
  15407. [](const httplib::Request &, httplib::Response &res) {
  15408. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  15409. });
  15410. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  15411. svr_.wait_until_ready();
  15412. }
  15413. void TearDown() override {
  15414. svr_.stop();
  15415. if (thread_.joinable()) thread_.join();
  15416. }
  15417. httplib::Server svr_;
  15418. std::thread thread_;
  15419. };
  15420. // stream::Get tests
  15421. TEST_F(StreamApiTest, GetBasic) {
  15422. httplib::Client cli(HOST, PORT);
  15423. auto result = httplib::stream::Get(cli, "/hello");
  15424. ASSERT_TRUE(result.is_valid());
  15425. EXPECT_EQ(200, result.status());
  15426. EXPECT_EQ("Hello World!", read_body(result));
  15427. }
  15428. TEST_F(StreamApiTest, GetWithParams) {
  15429. httplib::Client cli(HOST, PORT);
  15430. httplib::Params params{{"foo", "bar"}};
  15431. auto result = httplib::stream::Get(cli, "/echo-params", params);
  15432. ASSERT_TRUE(result.is_valid());
  15433. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  15434. }
  15435. TEST_F(StreamApiTest, GetConnectionError) {
  15436. httplib::Client cli(HOST, 9999);
  15437. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  15438. }
  15439. TEST_F(StreamApiTest, Get404) {
  15440. httplib::Client cli(HOST, PORT);
  15441. auto result = httplib::stream::Get(cli, "/nonexistent");
  15442. EXPECT_TRUE(result.is_valid());
  15443. EXPECT_EQ(404, result.status());
  15444. }
  15445. // stream::Post tests
  15446. TEST_F(StreamApiTest, PostBasic) {
  15447. httplib::Client cli(HOST, PORT);
  15448. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  15449. "application/json");
  15450. ASSERT_TRUE(result.is_valid());
  15451. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  15452. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  15453. }
  15454. TEST_F(StreamApiTest, PostWithHeaders) {
  15455. httplib::Client cli(HOST, PORT);
  15456. httplib::Headers headers{{"X-Custom", "value"}};
  15457. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  15458. "text/plain");
  15459. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  15460. }
  15461. TEST_F(StreamApiTest, PostWithParams) {
  15462. httplib::Client cli(HOST, PORT);
  15463. httplib::Params params{{"k", "v"}};
  15464. auto result =
  15465. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  15466. auto body = read_body(result);
  15467. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  15468. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  15469. }
  15470. TEST_F(StreamApiTest, PostLarge) {
  15471. httplib::Client cli(HOST, PORT);
  15472. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  15473. size_t total = 0;
  15474. while (result.next()) {
  15475. total += result.size();
  15476. }
  15477. EXPECT_EQ(100u * 1024u, total);
  15478. }
  15479. // stream::Put/Patch tests
  15480. TEST_F(StreamApiTest, PutAndPatch) {
  15481. httplib::Client cli(HOST, PORT);
  15482. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  15483. EXPECT_EQ("PUT:test", read_body(put));
  15484. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  15485. EXPECT_EQ("PATCH:test", read_body(patch));
  15486. }
  15487. // stream::Delete tests
  15488. TEST_F(StreamApiTest, Delete) {
  15489. httplib::Client cli(HOST, PORT);
  15490. auto del1 = httplib::stream::Delete(cli, "/resource");
  15491. EXPECT_EQ("Deleted", read_body(del1));
  15492. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  15493. EXPECT_EQ("Deleted:data", read_body(del2));
  15494. }
  15495. // stream::Head/Options tests
  15496. TEST_F(StreamApiTest, HeadAndOptions) {
  15497. httplib::Client cli(HOST, PORT);
  15498. auto head = httplib::stream::Head(cli, "/head-test");
  15499. EXPECT_TRUE(head.is_valid());
  15500. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  15501. auto opts = httplib::stream::Options(cli, "/options");
  15502. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  15503. }
  15504. // SSL stream::* tests
  15505. #ifdef CPPHTTPLIB_SSL_ENABLED
  15506. class SSLStreamApiTest : public ::testing::Test {
  15507. protected:
  15508. void SetUp() override {
  15509. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  15510. res.set_content("Hello SSL!", "text/plain");
  15511. });
  15512. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  15513. res.set_content(req.body, "text/plain");
  15514. });
  15515. port_ = svr_.bind_to_any_port("127.0.0.1");
  15516. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  15517. svr_.wait_until_ready();
  15518. }
  15519. void TearDown() override {
  15520. svr_.stop();
  15521. if (thread_.joinable()) thread_.join();
  15522. }
  15523. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  15524. std::thread thread_;
  15525. int port_ = 0;
  15526. };
  15527. TEST_F(SSLStreamApiTest, GetAndPost) {
  15528. httplib::SSLClient cli("127.0.0.1", port_);
  15529. cli.enable_server_certificate_verification(false);
  15530. auto get = httplib::stream::Get(cli, "/hello");
  15531. EXPECT_EQ("Hello SSL!", read_body(get));
  15532. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  15533. EXPECT_EQ("test", read_body(post));
  15534. }
  15535. #endif
  15536. // Tests for Error::Timeout and Error::ConnectionClosed error types
  15537. // These errors are set in SocketStream/SSLSocketStream and propagated through
  15538. // BodyReader
  15539. TEST(ErrorHandlingTest, StreamReadTimeout) {
  15540. // Test that read timeout during streaming is detected
  15541. // Use a large content-length response where server delays mid-stream
  15542. Server svr;
  15543. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15544. // Send a large response with delay in the middle
  15545. res.set_content_provider(
  15546. 1000, // content_length
  15547. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  15548. if (offset < 100) {
  15549. // Send first 100 bytes immediately
  15550. std::string data(100, 'A');
  15551. sink.write(data.c_str(), data.size());
  15552. return true;
  15553. }
  15554. // Then delay longer than client timeout
  15555. std::this_thread::sleep_for(std::chrono::seconds(3));
  15556. std::string data(900, 'B');
  15557. sink.write(data.c_str(), data.size());
  15558. return true;
  15559. });
  15560. });
  15561. auto port = 8091;
  15562. std::thread t([&]() { svr.listen("localhost", port); });
  15563. svr.wait_until_ready();
  15564. Client cli("localhost", port);
  15565. cli.set_read_timeout(1, 0); // 1 second timeout
  15566. auto handle = cli.open_stream("GET", "/slow-stream");
  15567. ASSERT_TRUE(handle.is_valid());
  15568. char buf[256];
  15569. ssize_t total = 0;
  15570. ssize_t n;
  15571. bool got_error = false;
  15572. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15573. total += n;
  15574. }
  15575. if (n < 0) {
  15576. got_error = true;
  15577. // Should be timeout or read error
  15578. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15579. handle.get_read_error() == Error::Read)
  15580. << "Actual error: " << to_string(handle.get_read_error());
  15581. }
  15582. // Either we got an error, or we got less data than expected
  15583. EXPECT_TRUE(got_error || total < 1000)
  15584. << "Expected timeout but got all " << total << " bytes";
  15585. svr.stop();
  15586. t.join();
  15587. }
  15588. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  15589. // Test connection closed detection via BodyReader
  15590. Server svr;
  15591. std::atomic<bool> close_now{false};
  15592. svr.Get("/will-close", [&](const Request &, Response &res) {
  15593. res.set_content_provider(
  15594. 10000, // Large content_length that we won't fully send
  15595. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15596. if (offset < 100) {
  15597. std::string data(100, 'X');
  15598. sink.write(data.c_str(), data.size());
  15599. return true;
  15600. }
  15601. // Wait for signal then abort
  15602. while (!close_now) {
  15603. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15604. }
  15605. return false; // Abort - server will close connection
  15606. });
  15607. });
  15608. auto port = 8092;
  15609. std::thread t([&]() { svr.listen("localhost", port); });
  15610. svr.wait_until_ready();
  15611. Client cli("localhost", port);
  15612. auto handle = cli.open_stream("GET", "/will-close");
  15613. ASSERT_TRUE(handle.is_valid());
  15614. char buf[256];
  15615. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15616. EXPECT_GT(n, 0) << "First read should succeed";
  15617. // Signal server to close
  15618. close_now = true;
  15619. // Keep reading until error or EOF
  15620. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15621. // Keep reading
  15622. }
  15623. // Should get an error since content_length wasn't satisfied
  15624. if (n < 0) {
  15625. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15626. handle.get_read_error() == Error::Read)
  15627. << "Actual error: " << to_string(handle.get_read_error());
  15628. }
  15629. svr.stop();
  15630. t.join();
  15631. }
  15632. #ifdef CPPHTTPLIB_SSL_ENABLED
  15633. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  15634. // Test that read timeout during SSL streaming is detected
  15635. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15636. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15637. res.set_content_provider(
  15638. 1000, "text/plain",
  15639. [](size_t offset, size_t /*length*/, DataSink &sink) {
  15640. if (offset < 100) {
  15641. std::string data(100, 'A');
  15642. sink.write(data.c_str(), data.size());
  15643. return true;
  15644. }
  15645. std::this_thread::sleep_for(std::chrono::seconds(3));
  15646. std::string data(900, 'B');
  15647. sink.write(data.c_str(), data.size());
  15648. return true;
  15649. });
  15650. });
  15651. auto port = 8093;
  15652. std::thread t([&]() { svr.listen("localhost", port); });
  15653. svr.wait_until_ready();
  15654. SSLClient cli("localhost", port);
  15655. cli.enable_server_certificate_verification(false);
  15656. cli.set_read_timeout(1, 0); // 1 second timeout
  15657. auto handle = cli.open_stream("GET", "/slow-stream");
  15658. ASSERT_TRUE(handle.is_valid());
  15659. char buf[256];
  15660. ssize_t total = 0;
  15661. ssize_t n;
  15662. bool got_error = false;
  15663. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15664. total += n;
  15665. }
  15666. if (n < 0) {
  15667. got_error = true;
  15668. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15669. handle.get_read_error() == Error::Read)
  15670. << "Actual error: " << to_string(handle.get_read_error());
  15671. }
  15672. EXPECT_TRUE(got_error || total < 1000)
  15673. << "Expected timeout but got all " << total << " bytes";
  15674. svr.stop();
  15675. t.join();
  15676. }
  15677. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  15678. // Test SSL connection closed detection
  15679. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15680. std::atomic<bool> close_now{false};
  15681. svr.Get("/will-close", [&](const Request &, Response &res) {
  15682. res.set_content_provider(
  15683. 10000, "text/plain",
  15684. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15685. if (offset < 100) {
  15686. std::string data(100, 'X');
  15687. sink.write(data.c_str(), data.size());
  15688. return true;
  15689. }
  15690. while (!close_now) {
  15691. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15692. }
  15693. return false;
  15694. });
  15695. });
  15696. auto port = 8094;
  15697. std::thread t([&]() { svr.listen("localhost", port); });
  15698. svr.wait_until_ready();
  15699. SSLClient cli("localhost", port);
  15700. cli.enable_server_certificate_verification(false);
  15701. auto handle = cli.open_stream("GET", "/will-close");
  15702. ASSERT_TRUE(handle.is_valid());
  15703. char buf[256];
  15704. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15705. EXPECT_GT(n, 0);
  15706. // Signal server to close
  15707. close_now = true;
  15708. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15709. // Keep reading
  15710. }
  15711. if (n < 0) {
  15712. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15713. handle.get_read_error() == Error::Read)
  15714. << "Actual error: " << to_string(handle.get_read_error());
  15715. }
  15716. svr.stop();
  15717. t.join();
  15718. }
  15719. #endif
  15720. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  15721. using namespace httplib;
  15722. // Create a test file
  15723. const char *fname = "etag_testfile.txt";
  15724. const char *content = "etag-content";
  15725. {
  15726. std::ofstream ofs(fname);
  15727. ofs << content;
  15728. ASSERT_TRUE(ofs.good());
  15729. }
  15730. Server svr;
  15731. svr.set_mount_point("/static", ".");
  15732. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15733. svr.wait_until_ready();
  15734. Client cli(HOST, PORT);
  15735. // First request: should get 200 with ETag header
  15736. auto res1 = cli.Get("/static/etag_testfile.txt");
  15737. ASSERT_TRUE(res1);
  15738. ASSERT_EQ(200, res1->status);
  15739. ASSERT_TRUE(res1->has_header("ETag"));
  15740. std::string etag = res1->get_header_value("ETag");
  15741. EXPECT_FALSE(etag.empty());
  15742. // Verify ETag format: W/"hex-hex"
  15743. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  15744. EXPECT_EQ('W', etag[0]);
  15745. EXPECT_EQ('/', etag[1]);
  15746. EXPECT_EQ('"', etag[2]);
  15747. EXPECT_EQ('"', etag.back());
  15748. // Exact match: expect 304 Not Modified
  15749. Headers h2 = {{"If-None-Match", etag}};
  15750. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  15751. ASSERT_TRUE(res2);
  15752. EXPECT_EQ(304, res2->status);
  15753. // Wildcard match: expect 304 Not Modified
  15754. Headers h3 = {{"If-None-Match", "*"}};
  15755. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  15756. ASSERT_TRUE(res3);
  15757. EXPECT_EQ(304, res3->status);
  15758. // Non-matching ETag: expect 200
  15759. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  15760. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  15761. ASSERT_TRUE(res4);
  15762. EXPECT_EQ(200, res4->status);
  15763. // Multiple ETags with one matching: expect 304
  15764. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  15765. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  15766. ASSERT_TRUE(res5);
  15767. EXPECT_EQ(304, res5->status);
  15768. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  15769. // that equivalent to the single comma-separated list above, so the match on
  15770. // the second line must still be found.
  15771. Headers h6;
  15772. h6.emplace("If-None-Match", "W/\"other\"");
  15773. h6.emplace("If-None-Match", etag);
  15774. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  15775. ASSERT_TRUE(res6);
  15776. EXPECT_EQ(304, res6->status);
  15777. svr.stop();
  15778. t.join();
  15779. std::remove(fname);
  15780. }
  15781. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  15782. using namespace httplib;
  15783. Server svr;
  15784. svr.set_mount_point("/static", ".");
  15785. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15786. svr.wait_until_ready();
  15787. Client cli(HOST, PORT);
  15788. // Send If-None-Match: * to a non-existent file
  15789. Headers h = {{"If-None-Match", "*"}};
  15790. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  15791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15792. EXPECT_EQ(404, res->status);
  15793. svr.stop();
  15794. t.join();
  15795. }
  15796. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  15797. using namespace httplib;
  15798. // Create a test file
  15799. const char *fname = "etag_boundary_testfile.txt";
  15800. const char *content = "boundary-test";
  15801. {
  15802. std::ofstream ofs(fname);
  15803. ofs << content;
  15804. ASSERT_TRUE(ofs.good());
  15805. }
  15806. Server svr;
  15807. svr.set_mount_point("/static", ".");
  15808. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15809. svr.wait_until_ready();
  15810. Client cli(HOST, PORT);
  15811. // Get the actual ETag
  15812. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  15813. ASSERT_TRUE(res1);
  15814. ASSERT_EQ(200, res1->status);
  15815. ASSERT_TRUE(res1->has_header("ETag"));
  15816. std::string etag = res1->get_header_value("ETag");
  15817. // Test 1: Very long ETag value (longer than actual ETag)
  15818. // Should NOT match and return 200 (not trigger out-of-bounds read)
  15819. Headers h1 = {{"If-None-Match", "W/"
  15820. "\"very-long-etag-value-that-is-much-longer-"
  15821. "than-the-actual-etag-value\""}};
  15822. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  15823. ASSERT_TRUE(res2);
  15824. EXPECT_EQ(200, res2->status); // Should not match
  15825. // Test 2: Long string followed by wildcard
  15826. // Should match on "*" and return 304 (without out-of-bounds read on the long
  15827. // string)
  15828. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  15829. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  15830. ASSERT_TRUE(res3);
  15831. EXPECT_EQ(304, res3->status); // Should match on "*"
  15832. // Test 3: Wildcard followed by long string
  15833. // Should match on "*" immediately and return 304
  15834. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  15835. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  15836. ASSERT_TRUE(res4);
  15837. EXPECT_EQ(304, res4->status); // Should match on "*"
  15838. // Test 4: Multiple long non-matching values
  15839. // Should NOT match and return 200 (test that all comparisons are safe)
  15840. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  15841. "W/\"second-long-non-matching-value\", "
  15842. "W/\"third-long-non-matching-value\""}};
  15843. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  15844. ASSERT_TRUE(res5);
  15845. EXPECT_EQ(200, res5->status); // Should not match
  15846. // Test 5: Single character that is not "*" (edge case)
  15847. Headers h5 = {{"If-None-Match", "X"}};
  15848. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  15849. ASSERT_TRUE(res6);
  15850. EXPECT_EQ(200, res6->status); // Should not match
  15851. svr.stop();
  15852. t.join();
  15853. std::remove(fname);
  15854. }
  15855. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  15856. using namespace httplib;
  15857. // Create a test file
  15858. const char *fname = "ims_testfile.txt";
  15859. const char *content = "if-modified-since-test";
  15860. {
  15861. std::ofstream ofs(fname);
  15862. ofs << content;
  15863. ASSERT_TRUE(ofs.good());
  15864. }
  15865. Server svr;
  15866. svr.set_mount_point("/static", ".");
  15867. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15868. svr.wait_until_ready();
  15869. Client cli(HOST, PORT);
  15870. // First request: should get 200 with Last-Modified header
  15871. auto res1 = cli.Get("/static/ims_testfile.txt");
  15872. ASSERT_TRUE(res1);
  15873. ASSERT_EQ(200, res1->status);
  15874. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15875. std::string last_modified = res1->get_header_value("Last-Modified");
  15876. EXPECT_FALSE(last_modified.empty());
  15877. // If-Modified-Since with same time: expect 304
  15878. Headers h2 = {{"If-Modified-Since", last_modified}};
  15879. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  15880. ASSERT_TRUE(res2);
  15881. EXPECT_EQ(304, res2->status);
  15882. // If-Modified-Since with future time: expect 304
  15883. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15884. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  15885. ASSERT_TRUE(res3);
  15886. EXPECT_EQ(304, res3->status);
  15887. // If-Modified-Since with past time: expect 200
  15888. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15889. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  15890. ASSERT_TRUE(res4);
  15891. EXPECT_EQ(200, res4->status);
  15892. // If-None-Match takes precedence over If-Modified-Since
  15893. // (send matching ETag with old If-Modified-Since -> should still be 304)
  15894. ASSERT_TRUE(res1->has_header("ETag"));
  15895. std::string etag = res1->get_header_value("ETag");
  15896. Headers h5 = {{"If-None-Match", etag},
  15897. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15898. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  15899. ASSERT_TRUE(res5);
  15900. EXPECT_EQ(304, res5->status);
  15901. svr.stop();
  15902. t.join();
  15903. std::remove(fname);
  15904. }
  15905. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  15906. using namespace httplib;
  15907. Server svr;
  15908. // Endpoint that returns compressible content
  15909. svr.Get("/compressible", [](const Request &, Response &res) {
  15910. // Return a large enough body to trigger compression
  15911. std::string body(1000, 'a');
  15912. res.set_content(body, "text/plain");
  15913. });
  15914. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15915. svr.wait_until_ready();
  15916. Client cli(HOST, PORT);
  15917. // Request with gzip support: should get Vary header when compressed
  15918. cli.set_compress(true);
  15919. auto res1 = cli.Get("/compressible");
  15920. ASSERT_TRUE(res1);
  15921. EXPECT_EQ(200, res1->status);
  15922. // If Content-Encoding is set, Vary should also be set
  15923. if (res1->has_header("Content-Encoding")) {
  15924. EXPECT_TRUE(res1->has_header("Vary"));
  15925. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  15926. }
  15927. // Request without Accept-Encoding header: should not have compression
  15928. Headers h_no_compress;
  15929. auto res2 = cli.Get("/compressible", h_no_compress);
  15930. ASSERT_TRUE(res2);
  15931. EXPECT_EQ(200, res2->status);
  15932. // Verify Vary header is present when compression is applied
  15933. // (the exact behavior depends on server configuration)
  15934. svr.stop();
  15935. t.join();
  15936. }
  15937. TEST(ETagTest, IfRangeWithETag) {
  15938. using namespace httplib;
  15939. // Create a test file with known content
  15940. const char *fname = "if_range_testfile.txt";
  15941. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15942. {
  15943. std::ofstream ofs(fname);
  15944. ofs << content;
  15945. ASSERT_TRUE(ofs.good());
  15946. }
  15947. Server svr;
  15948. svr.set_mount_point("/static", ".");
  15949. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15950. svr.wait_until_ready();
  15951. Client cli(HOST, PORT);
  15952. // First request: get ETag
  15953. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15954. ASSERT_TRUE(res1);
  15955. ASSERT_EQ(200, res1->status);
  15956. ASSERT_TRUE(res1->has_header("ETag"));
  15957. std::string etag = res1->get_header_value("ETag");
  15958. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15959. // Since our server generates weak ETags (W/"..."), If-Range with our
  15960. // ETag should NOT result in partial content - it should return full content.
  15961. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15962. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15963. ASSERT_TRUE(res2);
  15964. // Weak ETag in If-Range -> full content (200), not partial (206)
  15965. EXPECT_EQ(200, res2->status);
  15966. EXPECT_EQ(content, res2->body);
  15967. EXPECT_FALSE(res2->has_header("Content-Range"));
  15968. // Range request with non-matching If-Range (ETag): should get 200 (full
  15969. // content)
  15970. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15971. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15972. ASSERT_TRUE(res3);
  15973. EXPECT_EQ(200, res3->status);
  15974. EXPECT_EQ(content, res3->body);
  15975. EXPECT_FALSE(res3->has_header("Content-Range"));
  15976. // Range request with strong ETag (hypothetical - our server doesn't generate
  15977. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15978. // should return full content)
  15979. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15980. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15981. ASSERT_TRUE(res4);
  15982. EXPECT_EQ(200, res4->status);
  15983. EXPECT_EQ(content, res4->body);
  15984. EXPECT_FALSE(res4->has_header("Content-Range"));
  15985. svr.stop();
  15986. t.join();
  15987. std::remove(fname);
  15988. }
  15989. TEST(ETagTest, IfRangeWithDate) {
  15990. using namespace httplib;
  15991. // Create a test file
  15992. const char *fname = "if_range_date_testfile.txt";
  15993. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15994. {
  15995. std::ofstream ofs(fname);
  15996. ofs << content;
  15997. ASSERT_TRUE(ofs.good());
  15998. }
  15999. Server svr;
  16000. svr.set_mount_point("/static", ".");
  16001. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16002. svr.wait_until_ready();
  16003. Client cli(HOST, PORT);
  16004. // First request: get Last-Modified
  16005. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  16006. ASSERT_TRUE(res1);
  16007. ASSERT_EQ(200, res1->status);
  16008. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16009. std::string last_modified = res1->get_header_value("Last-Modified");
  16010. // Range request with matching If-Range (date): should get 206
  16011. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  16012. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  16013. ASSERT_TRUE(res2);
  16014. EXPECT_EQ(206, res2->status);
  16015. EXPECT_EQ("FGHIJ", res2->body);
  16016. // Range request with old If-Range date: should get 200 (full content)
  16017. Headers h3 = {{"Range", "bytes=5-9"},
  16018. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  16019. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  16020. ASSERT_TRUE(res3);
  16021. EXPECT_EQ(200, res3->status);
  16022. EXPECT_EQ(content, res3->body);
  16023. // Range request with future If-Range date: should get 206
  16024. Headers h4 = {{"Range", "bytes=0-4"},
  16025. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  16026. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  16027. ASSERT_TRUE(res4);
  16028. EXPECT_EQ(206, res4->status);
  16029. EXPECT_EQ("ABCDE", res4->body);
  16030. svr.stop();
  16031. t.join();
  16032. std::remove(fname);
  16033. }
  16034. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  16035. using namespace httplib;
  16036. const char *fname = "etag_malformed.txt";
  16037. const char *content = "malformed-etag";
  16038. {
  16039. std::ofstream ofs(fname);
  16040. ofs << content;
  16041. ASSERT_TRUE(ofs.good());
  16042. }
  16043. Server svr;
  16044. svr.set_mount_point("/static", ".");
  16045. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16046. svr.wait_until_ready();
  16047. Client cli(HOST, PORT);
  16048. // baseline: should get 200 and an ETag
  16049. auto res1 = cli.Get("/static/etag_malformed.txt");
  16050. ASSERT_TRUE(res1);
  16051. ASSERT_EQ(200, res1->status);
  16052. ASSERT_TRUE(res1->has_header("ETag"));
  16053. // Malformed ETag value (missing quotes) should be treated as non-matching
  16054. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  16055. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  16056. ASSERT_TRUE(res_bad);
  16057. EXPECT_EQ(200, res_bad->status);
  16058. // Whitespace-only header value should be considered invalid / non-matching
  16059. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  16060. "Host: localhost\r\n"
  16061. "If-None-Match: \r\n"
  16062. "Connection: close\r\n"
  16063. "\r\n";
  16064. std::string out;
  16065. ASSERT_TRUE(send_request(5, raw_req, &out));
  16066. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16067. svr.stop();
  16068. t.join();
  16069. std::remove(fname);
  16070. }
  16071. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  16072. using namespace httplib;
  16073. const char *fname = "ims_invalid_format.txt";
  16074. const char *content = "ims-bad-format";
  16075. {
  16076. std::ofstream ofs(fname);
  16077. ofs << content;
  16078. ASSERT_TRUE(ofs.good());
  16079. }
  16080. Server svr;
  16081. svr.set_mount_point("/static", ".");
  16082. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16083. svr.wait_until_ready();
  16084. Client cli(HOST, PORT);
  16085. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  16086. ASSERT_TRUE(res1);
  16087. ASSERT_EQ(200, res1->status);
  16088. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16089. // If-Modified-Since with invalid format should not result in 304
  16090. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  16091. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  16092. ASSERT_TRUE(res_bad);
  16093. EXPECT_EQ(200, res_bad->status);
  16094. // If-Range with invalid date format should be treated as mismatch -> full
  16095. // content (200)
  16096. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  16097. {"If-Range", "invalid-date"}};
  16098. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  16099. ASSERT_TRUE(res_ifrange);
  16100. EXPECT_EQ(200, res_ifrange->status);
  16101. svr.stop();
  16102. t.join();
  16103. std::remove(fname);
  16104. }
  16105. TEST(ETagTest, IfRangeWithMalformedETag) {
  16106. using namespace httplib;
  16107. const char *fname = "ifrange_malformed.txt";
  16108. const std::string content = "0123456789";
  16109. {
  16110. std::ofstream ofs(fname);
  16111. ofs << content;
  16112. ASSERT_TRUE(ofs.good());
  16113. }
  16114. Server svr;
  16115. svr.set_mount_point("/static", ".");
  16116. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16117. svr.wait_until_ready();
  16118. Client cli(HOST, PORT);
  16119. // First request: get ETag
  16120. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  16121. ASSERT_TRUE(res1);
  16122. ASSERT_EQ(200, res1->status);
  16123. ASSERT_TRUE(res1->has_header("ETag"));
  16124. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  16125. // full content (200)
  16126. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  16127. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  16128. ASSERT_TRUE(res2);
  16129. EXPECT_EQ(200, res2->status);
  16130. EXPECT_EQ(content, res2->body);
  16131. svr.stop();
  16132. t.join();
  16133. std::remove(fname);
  16134. }
  16135. TEST(ETagTest, ExtremeLargeDateValues) {
  16136. using namespace httplib;
  16137. const char *fname = "ims_extreme_date.txt";
  16138. const char *content = "ims-extreme-date";
  16139. {
  16140. std::ofstream ofs(fname);
  16141. ofs << content;
  16142. ASSERT_TRUE(ofs.good());
  16143. }
  16144. Server svr;
  16145. svr.set_mount_point("/static", ".");
  16146. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16147. svr.wait_until_ready();
  16148. Client cli(HOST, PORT);
  16149. auto res1 = cli.Get(std::string("/static/") + fname);
  16150. ASSERT_TRUE(res1);
  16151. ASSERT_EQ(200, res1->status);
  16152. ASSERT_TRUE(res1->has_header("Last-Modified"));
  16153. // Extremely large year that may overflow date parsing routines.
  16154. Headers h_large_date = {
  16155. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16156. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  16157. ASSERT_TRUE(res_bad);
  16158. // Expect server to treat this as invalid/mismatch and return full content
  16159. EXPECT_EQ(200, res_bad->status);
  16160. // If-Range with extremely large date should be treated as mismatch -> full
  16161. // content (200)
  16162. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  16163. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16164. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  16165. ASSERT_TRUE(res_ifrange);
  16166. EXPECT_EQ(200, res_ifrange->status);
  16167. svr.stop();
  16168. t.join();
  16169. std::remove(fname);
  16170. }
  16171. TEST(ETagTest, NegativeFileModificationTime) {
  16172. using namespace httplib;
  16173. const char *fname = "ims_negative_mtime.txt";
  16174. const std::string content = "negative-mtime";
  16175. {
  16176. std::ofstream ofs(fname);
  16177. ofs << content;
  16178. ASSERT_TRUE(ofs.good());
  16179. }
  16180. // Try to set file mtime to a negative value. This may fail on some
  16181. // platforms/filesystems; if it fails, the test will still verify server
  16182. // behaves safely by performing a regular conditional request.
  16183. #if defined(__APPLE__) || defined(__linux__)
  16184. bool set_negative = false;
  16185. do {
  16186. struct timeval times[2];
  16187. // access time: now
  16188. times[0].tv_sec = time(nullptr);
  16189. times[0].tv_usec = 0;
  16190. // modification time: negative (e.g., -1)
  16191. times[1].tv_sec = -1;
  16192. times[1].tv_usec = 0;
  16193. if (utimes(fname, times) == 0) { set_negative = true; }
  16194. } while (0);
  16195. #else
  16196. bool set_negative = false;
  16197. #endif
  16198. Server svr;
  16199. svr.set_mount_point("/static", ".");
  16200. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16201. svr.wait_until_ready();
  16202. Client cli(HOST, PORT);
  16203. auto res1 = cli.Get(std::string("/static/") + fname);
  16204. ASSERT_TRUE(res1);
  16205. ASSERT_EQ(200, res1->status);
  16206. bool has_last_modified = res1->has_header("Last-Modified");
  16207. std::string last_modified;
  16208. if (has_last_modified) {
  16209. last_modified = res1->get_header_value("Last-Modified");
  16210. }
  16211. if (set_negative) {
  16212. // If we successfully set a negative mtime, ensure server returns a
  16213. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  16214. // with an old date and ensure server handles it without crash.
  16215. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  16216. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  16217. ASSERT_TRUE(res2);
  16218. // Behavior may vary; at minimum ensure server responds (200 or 304).
  16219. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  16220. } else {
  16221. // Could not set negative mtime on this platform; fall back to verifying
  16222. // that normal invalid/malformed dates are treated safely (non-304).
  16223. Headers h_bad_date = {
  16224. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  16225. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  16226. ASSERT_TRUE(res_bad);
  16227. EXPECT_EQ(200, res_bad->status);
  16228. }
  16229. svr.stop();
  16230. t.join();
  16231. std::remove(fname);
  16232. }
  16233. //==============================================================================
  16234. // SSE Parsing Tests
  16235. //==============================================================================
  16236. class SSEParsingTest : public ::testing::Test {
  16237. protected:
  16238. // Test helper that mimics SSE parsing behavior
  16239. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  16240. int &retry_ms) {
  16241. // Blank line signals end of event
  16242. if (line.empty() || line == "\r") { return true; }
  16243. // Lines starting with ':' are comments (ignored)
  16244. if (!line.empty() && line[0] == ':') { return false; }
  16245. // Find the colon separator
  16246. auto colon_pos = line.find(':');
  16247. if (colon_pos == std::string::npos) {
  16248. // Line with no colon is treated as field name with empty value
  16249. return false;
  16250. }
  16251. std::string field = line.substr(0, colon_pos);
  16252. std::string value;
  16253. // Value starts after colon, skip optional single space
  16254. if (colon_pos + 1 < line.size()) {
  16255. size_t value_start = colon_pos + 1;
  16256. if (line[value_start] == ' ') { value_start++; }
  16257. value = line.substr(value_start);
  16258. // Remove trailing \r if present
  16259. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  16260. }
  16261. // Handle known fields
  16262. if (field == "event") {
  16263. msg.event = value;
  16264. } else if (field == "data") {
  16265. // Multiple data lines are concatenated with newlines
  16266. if (!msg.data.empty()) { msg.data += "\n"; }
  16267. msg.data += value;
  16268. } else if (field == "id") {
  16269. // Empty id is valid (clears the last event ID)
  16270. msg.id = value;
  16271. } else if (field == "retry") {
  16272. // Parse retry interval in milliseconds
  16273. {
  16274. int v = 0;
  16275. auto res =
  16276. detail::from_chars(value.data(), value.data() + value.size(), v);
  16277. if (res.ec == std::errc{}) { retry_ms = v; }
  16278. }
  16279. }
  16280. // Unknown fields are ignored per SSE spec
  16281. return false;
  16282. }
  16283. };
  16284. // Test: Single-line data
  16285. TEST_F(SSEParsingTest, SingleLineData) {
  16286. sse::SSEMessage msg;
  16287. int retry_ms = 3000;
  16288. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  16289. EXPECT_EQ(msg.data, "hello");
  16290. EXPECT_EQ(msg.event, "message");
  16291. // Blank line ends event
  16292. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16293. }
  16294. // Test: Multi-line data
  16295. TEST_F(SSEParsingTest, MultiLineData) {
  16296. sse::SSEMessage msg;
  16297. int retry_ms = 3000;
  16298. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  16299. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  16300. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  16301. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  16302. }
  16303. // Test: Custom event types
  16304. TEST_F(SSEParsingTest, CustomEventType) {
  16305. sse::SSEMessage msg;
  16306. int retry_ms = 3000;
  16307. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  16308. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  16309. EXPECT_EQ(msg.event, "update");
  16310. EXPECT_EQ(msg.data, "payload");
  16311. }
  16312. // Test: Event ID handling
  16313. TEST_F(SSEParsingTest, EventIdHandling) {
  16314. sse::SSEMessage msg;
  16315. int retry_ms = 3000;
  16316. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  16317. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  16318. EXPECT_EQ(msg.id, "12345");
  16319. }
  16320. // Test: Empty event ID (clears last event ID)
  16321. TEST_F(SSEParsingTest, EmptyEventId) {
  16322. sse::SSEMessage msg;
  16323. msg.id = "previous";
  16324. int retry_ms = 3000;
  16325. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  16326. EXPECT_EQ(msg.id, "");
  16327. }
  16328. // Test: Retry field parsing
  16329. TEST_F(SSEParsingTest, RetryFieldParsing) {
  16330. sse::SSEMessage msg;
  16331. int retry_ms = 3000;
  16332. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  16333. EXPECT_EQ(retry_ms, 5000);
  16334. }
  16335. // Test: Invalid retry value
  16336. TEST_F(SSEParsingTest, InvalidRetryValue) {
  16337. sse::SSEMessage msg;
  16338. int retry_ms = 3000;
  16339. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  16340. EXPECT_EQ(retry_ms, 3000); // Unchanged
  16341. }
  16342. // Test: Comments (lines starting with :)
  16343. TEST_F(SSEParsingTest, CommentsIgnored) {
  16344. sse::SSEMessage msg;
  16345. int retry_ms = 3000;
  16346. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  16347. EXPECT_EQ(msg.data, "");
  16348. EXPECT_EQ(msg.event, "message");
  16349. }
  16350. // Test: Colon in value
  16351. TEST_F(SSEParsingTest, ColonInValue) {
  16352. sse::SSEMessage msg;
  16353. int retry_ms = 3000;
  16354. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  16355. EXPECT_EQ(msg.data, "hello:world:test");
  16356. }
  16357. // Test: Line with no colon (field name only)
  16358. TEST_F(SSEParsingTest, FieldNameOnly) {
  16359. sse::SSEMessage msg;
  16360. int retry_ms = 3000;
  16361. // According to SSE spec, this is treated as field name with empty value
  16362. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  16363. // Since we don't recognize "data" without colon, data should be empty
  16364. EXPECT_EQ(msg.data, "");
  16365. }
  16366. // Test: Trailing \r handling
  16367. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  16368. sse::SSEMessage msg;
  16369. int retry_ms = 3000;
  16370. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  16371. EXPECT_EQ(msg.data, "hello");
  16372. }
  16373. // Test: Unknown fields ignored
  16374. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  16375. sse::SSEMessage msg;
  16376. int retry_ms = 3000;
  16377. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  16378. EXPECT_EQ(msg.data, "");
  16379. EXPECT_EQ(msg.event, "message");
  16380. }
  16381. // Test: Space after colon is optional
  16382. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  16383. sse::SSEMessage msg1, msg2;
  16384. int retry_ms = 3000;
  16385. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  16386. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  16387. EXPECT_EQ(msg1.data, "hello");
  16388. EXPECT_EQ(msg2.data, "hello");
  16389. }
  16390. // Test: SSEMessage clear
  16391. TEST_F(SSEParsingTest, MessageClear) {
  16392. sse::SSEMessage msg;
  16393. msg.event = "custom";
  16394. msg.data = "some data";
  16395. msg.id = "123";
  16396. msg.clear();
  16397. EXPECT_EQ(msg.event, "message");
  16398. EXPECT_EQ(msg.data, "");
  16399. EXPECT_EQ(msg.id, "");
  16400. }
  16401. // Test: Complete event parsing
  16402. TEST_F(SSEParsingTest, CompleteEventParsing) {
  16403. sse::SSEMessage msg;
  16404. int retry_ms = 3000;
  16405. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  16406. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  16407. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  16408. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  16409. // Blank line ends event
  16410. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  16411. EXPECT_EQ(msg.event, "notification");
  16412. EXPECT_EQ(msg.id, "evt-42");
  16413. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  16414. EXPECT_EQ(retry_ms, 1000);
  16415. }
  16416. //==============================================================================
  16417. // Integration Tests with Server
  16418. //==============================================================================
  16419. class SSEIntegrationTest : public ::testing::Test {
  16420. protected:
  16421. void SetUp() override {
  16422. stop_server_.store(false);
  16423. events_.clear();
  16424. server_ = httplib::detail::make_unique<Server>();
  16425. setup_server();
  16426. start_server();
  16427. }
  16428. void TearDown() override {
  16429. stop_server_.store(true);
  16430. event_cv_.notify_all();
  16431. server_->stop();
  16432. if (server_thread_.joinable()) { server_thread_.join(); }
  16433. }
  16434. void setup_server() {
  16435. // Simple SSE endpoint
  16436. server_->Get("/events", [this](const Request &req, Response &res) {
  16437. auto last_id = req.get_header_value("Last-Event-ID");
  16438. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  16439. res.set_chunked_content_provider(
  16440. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  16441. std::unique_lock<std::mutex> lock(event_mutex_);
  16442. if (event_cv_.wait_for(
  16443. lock, std::chrono::milliseconds(200), [this] {
  16444. return !events_.empty() || stop_server_.load();
  16445. })) {
  16446. if (stop_server_.load()) { return false; }
  16447. if (!events_.empty()) {
  16448. std::string event = events_.front();
  16449. events_.erase(events_.begin());
  16450. sink.write(event.data(), event.size());
  16451. return true;
  16452. }
  16453. }
  16454. return !stop_server_.load();
  16455. });
  16456. });
  16457. // Endpoint that returns error
  16458. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  16459. res.status = 500;
  16460. res.set_content("Internal Server Error", "text/plain");
  16461. });
  16462. // Endpoint for custom event types
  16463. server_->Get("/custom-events", [](const Request &, Response &res) {
  16464. res.set_chunked_content_provider(
  16465. "text/event-stream", [](size_t offset, DataSink &sink) {
  16466. if (offset == 0) {
  16467. std::string event = "event: update\ndata: updated\n\n"
  16468. "event: delete\ndata: deleted\n\n";
  16469. sink.write(event.data(), event.size());
  16470. }
  16471. return false; // End stream after sending
  16472. });
  16473. });
  16474. }
  16475. void start_server() {
  16476. port_ = server_->bind_to_any_port(HOST);
  16477. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16478. // Wait for server to start
  16479. while (!server_->is_running()) {
  16480. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16481. }
  16482. }
  16483. int get_port() const { return port_; }
  16484. void send_event(const std::string &event) {
  16485. std::lock_guard<std::mutex> lock(event_mutex_);
  16486. events_.push_back(event);
  16487. event_cv_.notify_all();
  16488. }
  16489. std::unique_ptr<Server> server_;
  16490. std::thread server_thread_;
  16491. std::mutex event_mutex_;
  16492. std::condition_variable event_cv_;
  16493. std::vector<std::string> events_;
  16494. std::atomic<bool> stop_server_{false};
  16495. std::string last_received_event_id_;
  16496. int port_ = 0;
  16497. };
  16498. // Test: Successful connection and on_open callback
  16499. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  16500. // Add a simple endpoint that sends one event and closes
  16501. server_->Get("/simple-event", [](const Request &, Response &res) {
  16502. res.set_chunked_content_provider(
  16503. "text/event-stream", [](size_t offset, DataSink &sink) {
  16504. if (offset == 0) {
  16505. std::string event = "data: hello\n\n";
  16506. sink.write(event.data(), event.size());
  16507. }
  16508. return false; // Close stream after sending
  16509. });
  16510. });
  16511. Client client("localhost", get_port());
  16512. sse::SSEClient sse(client, "/simple-event");
  16513. std::atomic<bool> open_called{false};
  16514. std::atomic<bool> message_received{false};
  16515. sse.on_open([&open_called]() { open_called.store(true); });
  16516. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  16517. if (msg.data == "hello") { message_received.store(true); }
  16518. });
  16519. sse.set_reconnect_interval(100);
  16520. sse.set_max_reconnect_attempts(1);
  16521. // Start async
  16522. sse.start_async();
  16523. // Wait for message to be processed
  16524. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16525. sse.stop();
  16526. EXPECT_TRUE(open_called.load());
  16527. EXPECT_TRUE(message_received.load());
  16528. }
  16529. // Test: on_message callback
  16530. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  16531. // Endpoint that sends multiple events then closes
  16532. server_->Get("/multi-event", [](const Request &, Response &res) {
  16533. res.set_chunked_content_provider(
  16534. "text/event-stream", [](size_t offset, DataSink &sink) {
  16535. if (offset == 0) {
  16536. std::string events = "data: message1\n\ndata: message2\n\n";
  16537. sink.write(events.data(), events.size());
  16538. }
  16539. return false;
  16540. });
  16541. });
  16542. Client client("localhost", get_port());
  16543. sse::SSEClient sse(client, "/multi-event");
  16544. std::vector<std::string> received_messages;
  16545. std::mutex messages_mutex;
  16546. sse.on_message([&](const sse::SSEMessage &msg) {
  16547. std::lock_guard<std::mutex> lock(messages_mutex);
  16548. received_messages.push_back(msg.data);
  16549. });
  16550. sse.set_reconnect_interval(100);
  16551. sse.set_max_reconnect_attempts(1);
  16552. sse.start_async();
  16553. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16554. sse.stop();
  16555. std::lock_guard<std::mutex> lock(messages_mutex);
  16556. EXPECT_GE(received_messages.size(), 2u);
  16557. if (received_messages.size() >= 2) {
  16558. EXPECT_EQ(received_messages[0], "message1");
  16559. EXPECT_EQ(received_messages[1], "message2");
  16560. }
  16561. }
  16562. // Test: on_event for specific types
  16563. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  16564. Client client("localhost", get_port());
  16565. sse::SSEClient sse(client, "/custom-events");
  16566. std::atomic<bool> update_received{false};
  16567. std::atomic<bool> delete_received{false};
  16568. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  16569. if (msg.data == "updated") { update_received.store(true); }
  16570. });
  16571. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  16572. if (msg.data == "deleted") { delete_received.store(true); }
  16573. });
  16574. sse.set_max_reconnect_attempts(1);
  16575. sse.start_async();
  16576. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  16577. sse.stop();
  16578. EXPECT_TRUE(update_received.load());
  16579. EXPECT_TRUE(delete_received.load());
  16580. }
  16581. // Test: on_error callback on connection failure
  16582. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  16583. // Connect to a non-existent port
  16584. Client client("localhost", 59999);
  16585. sse::SSEClient sse(client, "/events");
  16586. std::atomic<bool> error_called{false};
  16587. Error received_error = Error::Success;
  16588. sse.on_error([&](Error err) {
  16589. error_called.store(true);
  16590. received_error = err;
  16591. });
  16592. sse.set_reconnect_interval(50);
  16593. sse.set_max_reconnect_attempts(1);
  16594. sse.start_async();
  16595. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16596. sse.stop();
  16597. EXPECT_TRUE(error_called.load());
  16598. EXPECT_NE(received_error, Error::Success);
  16599. }
  16600. // Test: Last-Event-ID header sent on reconnect
  16601. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  16602. // Endpoint that sends event with ID
  16603. server_->Get("/event-with-id", [](const Request &, Response &res) {
  16604. res.set_chunked_content_provider(
  16605. "text/event-stream", [](size_t offset, DataSink &sink) {
  16606. if (offset == 0) {
  16607. std::string event = "id: evt-123\ndata: test\n\n";
  16608. sink.write(event.data(), event.size());
  16609. }
  16610. return false;
  16611. });
  16612. });
  16613. Client client("localhost", get_port());
  16614. sse::SSEClient sse(client, "/event-with-id");
  16615. std::atomic<bool> id_received{false};
  16616. sse.on_message([&](const sse::SSEMessage &msg) {
  16617. if (!msg.id.empty()) { id_received.store(true); }
  16618. });
  16619. sse.set_reconnect_interval(100);
  16620. sse.set_max_reconnect_attempts(1);
  16621. sse.start_async();
  16622. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16623. sse.stop();
  16624. EXPECT_TRUE(id_received.load());
  16625. EXPECT_EQ(sse.last_event_id(), "evt-123");
  16626. }
  16627. // Test: Manual stop
  16628. TEST_F(SSEIntegrationTest, ManualStop) {
  16629. // Endpoint that sends one event and stays open briefly
  16630. std::atomic<bool> handler_running{true};
  16631. server_->Get("/stay-open", [&handler_running](const Request &,
  16632. Response &res) {
  16633. res.set_chunked_content_provider(
  16634. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  16635. if (offset == 0) {
  16636. std::string event = "data: connected\n\n";
  16637. sink.write(event.data(), event.size());
  16638. }
  16639. // Keep connection open while handler_running is true
  16640. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  16641. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16642. }
  16643. return false;
  16644. });
  16645. });
  16646. Client client("localhost", get_port());
  16647. sse::SSEClient sse(client, "/stay-open");
  16648. std::atomic<bool> connected{false};
  16649. sse.on_open([&connected]() { connected.store(true); });
  16650. sse.set_reconnect_interval(100);
  16651. sse.set_max_reconnect_attempts(1);
  16652. sse.start_async();
  16653. // Wait for connection to establish
  16654. for (int i = 0; i < 20 && !connected.load(); ++i) {
  16655. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16656. }
  16657. EXPECT_TRUE(connected.load());
  16658. EXPECT_TRUE(sse.is_connected());
  16659. // Signal handler to stop
  16660. handler_running.store(false);
  16661. // Stop SSE client
  16662. sse.stop();
  16663. EXPECT_FALSE(sse.is_connected());
  16664. }
  16665. // Test: SSEClient with custom headers
  16666. TEST_F(SSEIntegrationTest, CustomHeaders) {
  16667. // Setup a server endpoint that checks for custom header
  16668. std::atomic<bool> header_received{false};
  16669. server_->Get("/header-check", [&](const Request &req, Response &res) {
  16670. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  16671. header_received.store(true);
  16672. }
  16673. res.set_chunked_content_provider("text/event-stream",
  16674. [](size_t, DataSink &) { return false; });
  16675. });
  16676. Client client("localhost", get_port());
  16677. Headers headers = {{"X-Custom-Header", "custom-value"}};
  16678. sse::SSEClient sse(client, "/header-check", headers);
  16679. sse.set_max_reconnect_attempts(1);
  16680. sse.start_async();
  16681. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16682. sse.stop();
  16683. EXPECT_TRUE(header_received.load());
  16684. }
  16685. // Test: Reconnect interval configuration
  16686. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  16687. Client client("localhost", get_port());
  16688. sse::SSEClient sse(client, "/events");
  16689. auto &result = sse.set_reconnect_interval(500);
  16690. // Builder pattern should return reference to self
  16691. EXPECT_EQ(&result, &sse);
  16692. }
  16693. // Test: Max reconnect attempts
  16694. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  16695. // Connect to non-existent port to force reconnects
  16696. Client client("localhost", 59998);
  16697. sse::SSEClient sse(client, "/events");
  16698. std::atomic<int> error_count{0};
  16699. sse.on_error([&](Error) { error_count.fetch_add(1); });
  16700. sse.set_reconnect_interval(50);
  16701. sse.set_max_reconnect_attempts(2);
  16702. auto start = std::chrono::steady_clock::now();
  16703. sse.start(); // Blocking call
  16704. auto end = std::chrono::steady_clock::now();
  16705. // Should have stopped after 2 failed attempts
  16706. EXPECT_GE(error_count.load(), 2);
  16707. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  16708. auto duration =
  16709. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  16710. #ifdef _WIN32
  16711. // Windows is much slower for socket connection failures
  16712. EXPECT_LT(duration.count(), 7000);
  16713. #else
  16714. EXPECT_LT(duration.count(), 1000);
  16715. #endif
  16716. }
  16717. // Test: Multi-line data in integration
  16718. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  16719. // Endpoint with multi-line data
  16720. server_->Get("/multiline-data", [](const Request &, Response &res) {
  16721. res.set_chunked_content_provider(
  16722. "text/event-stream", [](size_t offset, DataSink &sink) {
  16723. if (offset == 0) {
  16724. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  16725. sink.write(event.data(), event.size());
  16726. }
  16727. return false;
  16728. });
  16729. });
  16730. Client client("localhost", get_port());
  16731. sse::SSEClient sse(client, "/multiline-data");
  16732. std::string received_data;
  16733. std::mutex data_mutex;
  16734. sse.on_message([&](const sse::SSEMessage &msg) {
  16735. std::lock_guard<std::mutex> lock(data_mutex);
  16736. received_data = msg.data;
  16737. });
  16738. sse.set_reconnect_interval(100);
  16739. sse.set_max_reconnect_attempts(1);
  16740. sse.start_async();
  16741. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16742. sse.stop();
  16743. std::lock_guard<std::mutex> lock(data_mutex);
  16744. EXPECT_EQ(received_data, "line1\nline2\nline3");
  16745. }
  16746. // Test: Auto-reconnect after server disconnection
  16747. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  16748. std::atomic<int> connection_count{0};
  16749. std::atomic<int> message_count{0};
  16750. // Endpoint that sends one event and closes, forcing reconnect
  16751. server_->Get("/reconnect-test",
  16752. [&connection_count](const Request &, Response &res) {
  16753. connection_count.fetch_add(1);
  16754. res.set_chunked_content_provider(
  16755. "text/event-stream", [](size_t offset, DataSink &sink) {
  16756. if (offset == 0) {
  16757. std::string event = "data: hello\n\n";
  16758. sink.write(event.data(), event.size());
  16759. }
  16760. return false; // Close connection after sending
  16761. });
  16762. });
  16763. Client client("localhost", get_port());
  16764. sse::SSEClient sse(client, "/reconnect-test");
  16765. sse.on_message([&message_count](const sse::SSEMessage &) {
  16766. message_count.fetch_add(1);
  16767. });
  16768. sse.set_reconnect_interval(100);
  16769. sse.set_max_reconnect_attempts(3);
  16770. sse.start_async();
  16771. // Wait long enough for multiple reconnects
  16772. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16773. sse.stop();
  16774. // Should have connected multiple times (initial + reconnects)
  16775. EXPECT_GE(connection_count.load(), 2);
  16776. // Should have received messages from multiple connections
  16777. EXPECT_GE(message_count.load(), 2);
  16778. }
  16779. // Test: Last-Event-ID sent on reconnect
  16780. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  16781. std::atomic<int> connection_count{0};
  16782. std::vector<std::string> received_last_event_ids;
  16783. std::mutex id_mutex;
  16784. // Endpoint that checks Last-Event-ID header and sends event with ID
  16785. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  16786. int conn = connection_count.fetch_add(1);
  16787. // Capture the Last-Event-ID header from each connection
  16788. {
  16789. std::lock_guard<std::mutex> lock(id_mutex);
  16790. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  16791. }
  16792. res.set_chunked_content_provider(
  16793. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  16794. if (offset == 0) {
  16795. std::string event =
  16796. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  16797. sink.write(event.data(), event.size());
  16798. }
  16799. return false;
  16800. });
  16801. });
  16802. Client client("localhost", get_port());
  16803. sse::SSEClient sse(client, "/reconnect-with-id");
  16804. sse.set_reconnect_interval(100);
  16805. sse.set_max_reconnect_attempts(3);
  16806. sse.start_async();
  16807. // Wait for at least 2 connections
  16808. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16809. sse.stop();
  16810. // Verify behavior
  16811. std::lock_guard<std::mutex> lock(id_mutex);
  16812. EXPECT_GE(received_last_event_ids.size(), 2u);
  16813. // First connection should have no Last-Event-ID
  16814. if (!received_last_event_ids.empty()) {
  16815. EXPECT_EQ(received_last_event_ids[0], "");
  16816. }
  16817. // Second connection should have Last-Event-ID from first connection
  16818. if (received_last_event_ids.size() >= 2) {
  16819. EXPECT_EQ(received_last_event_ids[1], "event-0");
  16820. }
  16821. }
  16822. // Test: set_headers updates headers used on reconnect
  16823. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  16824. std::vector<std::string> received_tokens;
  16825. std::mutex token_mutex;
  16826. // Endpoint that captures Authorization header
  16827. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  16828. {
  16829. std::lock_guard<std::mutex> lock(token_mutex);
  16830. received_tokens.push_back(req.get_header_value("Authorization"));
  16831. }
  16832. res.set_chunked_content_provider(
  16833. "text/event-stream", [](size_t offset, DataSink &sink) {
  16834. if (offset == 0) {
  16835. std::string event = "data: hello\n\n";
  16836. sink.write(event.data(), event.size());
  16837. }
  16838. return false; // Close connection to trigger reconnect
  16839. });
  16840. });
  16841. Client client("localhost", get_port());
  16842. Headers headers = {{"Authorization", "Bearer old-token"}};
  16843. sse::SSEClient sse(client, "/auth-check", headers);
  16844. // Update headers on each successful connection
  16845. sse.on_open(
  16846. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  16847. sse.set_reconnect_interval(100);
  16848. sse.set_max_reconnect_attempts(3);
  16849. sse.start_async();
  16850. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16851. sse.stop();
  16852. std::lock_guard<std::mutex> lock(token_mutex);
  16853. ASSERT_GE(received_tokens.size(), 2u);
  16854. // First connection uses original header
  16855. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  16856. // Second connection uses updated header from set_headers
  16857. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  16858. }
  16859. // Test: 401 allows reconnection (so on_error can refresh headers)
  16860. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  16861. std::atomic<int> connection_count{0};
  16862. // Endpoint: returns 401 on first attempt, 200 on second
  16863. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  16864. int conn = connection_count.fetch_add(1);
  16865. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  16866. res.status = StatusCode::Unauthorized_401;
  16867. res.set_content("Unauthorized", "text/plain");
  16868. return;
  16869. }
  16870. res.set_chunked_content_provider(
  16871. "text/event-stream", [](size_t offset, DataSink &sink) {
  16872. if (offset == 0) {
  16873. std::string event = "data: authenticated\n\n";
  16874. sink.write(event.data(), event.size());
  16875. }
  16876. return false;
  16877. });
  16878. });
  16879. Client client("localhost", get_port());
  16880. Headers headers = {{"Authorization", "Bearer expired"}};
  16881. sse::SSEClient sse(client, "/auth-retry", headers);
  16882. std::atomic<bool> message_received{false};
  16883. // Refresh token on error
  16884. sse.on_error(
  16885. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  16886. sse.on_message([&](const sse::SSEMessage &msg) {
  16887. if (msg.data == "authenticated") { message_received.store(true); }
  16888. });
  16889. sse.set_reconnect_interval(100);
  16890. sse.set_max_reconnect_attempts(3);
  16891. sse.start_async();
  16892. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16893. sse.stop();
  16894. // Should have reconnected after 401 and succeeded with new token
  16895. EXPECT_GE(connection_count.load(), 2);
  16896. EXPECT_TRUE(message_received.load());
  16897. }
  16898. TEST(Issue2318Test, EmptyHostString) {
  16899. {
  16900. httplib::Client cli_empty("", PORT);
  16901. auto res = cli_empty.Get("/");
  16902. ASSERT_FALSE(res);
  16903. EXPECT_EQ(httplib::Error::Connection, res.error());
  16904. }
  16905. {
  16906. httplib::Client cli(" ", PORT);
  16907. auto res = cli.Get("/");
  16908. ASSERT_FALSE(res);
  16909. EXPECT_EQ(httplib::Error::Connection, res.error());
  16910. }
  16911. }
  16912. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16913. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  16914. Server svr;
  16915. // Set a small payload limit (1KB)
  16916. svr.set_payload_max_length(1024);
  16917. svr.Post("/test", [&](const Request &req, Response &res) {
  16918. res.set_content("Body size: " + std::to_string(req.body.size()),
  16919. "text/plain");
  16920. });
  16921. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16922. auto se = detail::scope_exit([&] {
  16923. svr.stop();
  16924. listen_thread.join();
  16925. });
  16926. svr.wait_until_ready();
  16927. // Create data that compresses well but exceeds limit when decompressed
  16928. // 8KB of repeated null bytes compresses to a very small size
  16929. std::string original_data(8 * 1024, '\0');
  16930. // Compress the data using gzip
  16931. std::string compressed_data;
  16932. detail::gzip_compressor compressor;
  16933. compressor.compress(original_data.data(), original_data.size(), true,
  16934. [&](const char *data, size_t size) {
  16935. compressed_data.append(data, size);
  16936. return true;
  16937. });
  16938. // Verify compression worked (compressed should be much smaller)
  16939. ASSERT_LT(compressed_data.size(), original_data.size());
  16940. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16941. // Send compressed data with Content-Encoding: gzip
  16942. Client cli(HOST, PORT);
  16943. Headers headers = {{"Content-Encoding", "gzip"}};
  16944. auto res =
  16945. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16946. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16948. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16949. }
  16950. #endif
  16951. // ============================================================================
  16952. // OpenSSL-Specific Tests
  16953. // ============================================================================
  16954. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16955. X509 *readCertificate(const std::string &strFileName) {
  16956. std::ifstream inStream(strFileName);
  16957. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16958. std::istreambuf_iterator<char>());
  16959. if (strCertPEM.empty()) return (nullptr);
  16960. BIO *pbCert = BIO_new(BIO_s_mem());
  16961. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16962. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16963. BIO_free(pbCert);
  16964. return (pCert);
  16965. }
  16966. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16967. std::ifstream inStream(strFileName);
  16968. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16969. std::istreambuf_iterator<char>());
  16970. if (strPrivateKeyPEM.empty()) return (nullptr);
  16971. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16972. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16973. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16974. BIO_free(pbPrivKey);
  16975. return (pPrivateKey);
  16976. }
  16977. TEST(BindServerTest, UpdateCerts) {
  16978. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16979. int port = svr.bind_to_any_port("0.0.0.0");
  16980. ASSERT_TRUE(svr.is_valid());
  16981. ASSERT_TRUE(port > 0);
  16982. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16983. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16984. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16985. ASSERT_TRUE(cert != nullptr);
  16986. ASSERT_TRUE(ca_cert != nullptr);
  16987. ASSERT_TRUE(key != nullptr);
  16988. X509_STORE *cert_store = X509_STORE_new();
  16989. X509_STORE_add_cert(cert_store, ca_cert);
  16990. // svr.update_certs(cert, key, cert_store); // deprecated
  16991. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16992. CLIENT_CA_CERT_FILE);
  16993. ASSERT_TRUE(svr.is_valid());
  16994. svr.stop();
  16995. X509_STORE_free(cert_store);
  16996. X509_free(cert);
  16997. X509_free(ca_cert);
  16998. EVP_PKEY_free(key);
  16999. }
  17000. // Test that update_certs() updates client CA list correctly
  17001. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  17002. // Start with file-based constructor
  17003. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17004. ASSERT_TRUE(svr.is_valid());
  17005. // Initially no client CA list should be set
  17006. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17007. ASSERT_TRUE(ssl_ctx != nullptr);
  17008. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  17009. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  17010. EXPECT_EQ(0, count_before);
  17011. // Now update with client CA (PEM string)
  17012. std::string cert_pem, key_pem, ca_pem;
  17013. read_file(SERVER_CERT_FILE, cert_pem);
  17014. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  17015. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  17016. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  17017. ASSERT_TRUE(svr.is_valid());
  17018. // Now client CA list should be set
  17019. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  17020. ASSERT_TRUE(ca_list_after != nullptr);
  17021. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  17022. }
  17023. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  17024. // Test that the file-path SSLServer constructor properly sets the client CA
  17025. // list that is sent to clients during the TLS handshake (CertificateRequest)
  17026. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17027. ASSERT_TRUE(svr.is_valid());
  17028. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  17029. ASSERT_TRUE(ssl_ctx != nullptr);
  17030. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  17031. ASSERT_TRUE(ca_list != nullptr);
  17032. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  17033. }
  17034. #endif
  17035. // ============================================================================
  17036. // MbedTLS-Specific Tests
  17037. // ============================================================================
  17038. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  17039. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  17040. using namespace httplib::tls;
  17041. // Track if callback was invoked
  17042. bool callback_invoked = false;
  17043. // The callback receives void* ctx which is actually MbedTlsContext*
  17044. // We can access the mbedtls_ssl_config via the context
  17045. auto setup_callback = [&callback_invoked](void *ctx) {
  17046. callback_invoked = true;
  17047. // Cast to MbedTlsContext* to access the ssl config
  17048. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  17049. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  17050. // Use static variables to hold certificate data (simplified for test)
  17051. static mbedtls_x509_crt own_cert;
  17052. static mbedtls_pk_context own_key;
  17053. static mbedtls_x509_crt ca_chain;
  17054. static bool initialized = false;
  17055. if (!initialized) {
  17056. mbedtls_x509_crt_init(&own_cert);
  17057. mbedtls_pk_init(&own_key);
  17058. mbedtls_x509_crt_init(&ca_chain);
  17059. // Load server certificate
  17060. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  17061. return false;
  17062. }
  17063. // Load server private key.
  17064. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  17065. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  17066. #if MBEDTLS_VERSION_MAJOR == 3
  17067. ,
  17068. mbedtls_ctr_drbg_random, nullptr
  17069. #endif
  17070. ) != 0) {
  17071. return false;
  17072. }
  17073. // Load CA chain for client verification
  17074. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  17075. return false;
  17076. }
  17077. initialized = true;
  17078. }
  17079. // Configure the SSL config
  17080. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  17081. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  17082. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  17083. // Set minimum TLS version using mbedTLS native API
  17084. #if MBEDTLS_VERSION_MAJOR >= 3
  17085. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  17086. #else
  17087. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  17088. MBEDTLS_SSL_MINOR_VERSION_3);
  17089. #endif
  17090. return true;
  17091. };
  17092. SSLServer svr(setup_callback);
  17093. ASSERT_TRUE(svr.is_valid());
  17094. ASSERT_TRUE(callback_invoked);
  17095. svr.Get("/test", [&](const Request &req, Response &res) {
  17096. res.set_content("test", "text/plain");
  17097. auto cert = req.peer_cert();
  17098. ASSERT_TRUE(static_cast<bool>(cert));
  17099. auto common_name = cert.subject_cn();
  17100. EXPECT_EQ("Common Name", common_name);
  17101. });
  17102. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17103. auto se = detail::scope_exit([&] {
  17104. svr.stop();
  17105. t.join();
  17106. ASSERT_FALSE(svr.is_running());
  17107. });
  17108. svr.wait_until_ready();
  17109. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  17110. cli.enable_server_certificate_verification(false);
  17111. cli.set_connection_timeout(30);
  17112. auto res = cli.Get("/test");
  17113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17114. ASSERT_EQ(StatusCode::OK_200, res->status);
  17115. }
  17116. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  17117. // context (owning mbedtls_ssl_config) before shutting down a still-open
  17118. // keep-alive SSL session, which reads through that config in
  17119. // mbedtls_ssl_close_notify.
  17120. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  17121. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17122. ASSERT_TRUE(svr.is_valid());
  17123. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17124. res.set_content("test", "text/plain");
  17125. });
  17126. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  17127. auto se = detail::scope_exit([&] {
  17128. svr.stop();
  17129. t.join();
  17130. ASSERT_FALSE(svr.is_running());
  17131. });
  17132. svr.wait_until_ready();
  17133. {
  17134. SSLClient cli(HOST, PORT);
  17135. cli.enable_server_certificate_verification(false);
  17136. cli.set_keep_alive(true);
  17137. auto res = cli.Get("/test");
  17138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17139. ASSERT_EQ(StatusCode::OK_200, res->status);
  17140. // cli is destructed here with the keep-alive SSL session still open.
  17141. }
  17142. }
  17143. #endif
  17144. // WebSocket Tests
  17145. TEST(WebSocketTest, RSVBitsMustBeZero) {
  17146. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  17147. // defining the meaning of these bits has been negotiated.
  17148. auto make_frame = [](uint8_t first_byte) {
  17149. std::string frame;
  17150. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  17151. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  17152. frame += "Hello";
  17153. return frame;
  17154. };
  17155. // RSV1 set (0x40)
  17156. {
  17157. detail::BufferStream strm;
  17158. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  17159. ws::Opcode opcode;
  17160. std::string payload;
  17161. bool fin;
  17162. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17163. false, 1024));
  17164. }
  17165. // RSV2 set (0x20)
  17166. {
  17167. detail::BufferStream strm;
  17168. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  17169. ws::Opcode opcode;
  17170. std::string payload;
  17171. bool fin;
  17172. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17173. false, 1024));
  17174. }
  17175. // RSV3 set (0x10)
  17176. {
  17177. detail::BufferStream strm;
  17178. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  17179. ws::Opcode opcode;
  17180. std::string payload;
  17181. bool fin;
  17182. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17183. false, 1024));
  17184. }
  17185. // No RSV bits set - should succeed
  17186. {
  17187. detail::BufferStream strm;
  17188. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  17189. ws::Opcode opcode;
  17190. std::string payload;
  17191. bool fin;
  17192. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17193. false, 1024));
  17194. EXPECT_EQ(ws::Opcode::Text, opcode);
  17195. EXPECT_EQ("Hello", payload);
  17196. EXPECT_TRUE(fin);
  17197. }
  17198. }
  17199. TEST(WebSocketTest, ControlFrameValidation) {
  17200. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  17201. // payload length <= 125.
  17202. // Ping with FIN=0 - must be rejected
  17203. {
  17204. detail::BufferStream strm;
  17205. std::string frame;
  17206. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  17207. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17208. strm.write(frame.data(), frame.size());
  17209. ws::Opcode opcode;
  17210. std::string payload;
  17211. bool fin;
  17212. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17213. false, 1024));
  17214. }
  17215. // Close with FIN=0 - must be rejected
  17216. {
  17217. detail::BufferStream strm;
  17218. std::string frame;
  17219. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  17220. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  17221. strm.write(frame.data(), frame.size());
  17222. ws::Opcode opcode;
  17223. std::string payload;
  17224. bool fin;
  17225. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17226. false, 1024));
  17227. }
  17228. // Ping with payload_len=126 (extended length) - must be rejected
  17229. {
  17230. detail::BufferStream strm;
  17231. std::string frame;
  17232. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17233. frame += static_cast<char>(126); // payload_len=126 (>125)
  17234. frame += static_cast<char>(0x00); // extended length high byte
  17235. frame += static_cast<char>(126); // extended length low byte
  17236. frame += std::string(126, 'x');
  17237. strm.write(frame.data(), frame.size());
  17238. ws::Opcode opcode;
  17239. std::string payload;
  17240. bool fin;
  17241. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17242. false, 1024));
  17243. }
  17244. // Ping with FIN=1 and payload_len=125 - should succeed
  17245. {
  17246. detail::BufferStream strm;
  17247. std::string frame;
  17248. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  17249. frame += static_cast<char>(125); // payload_len=125
  17250. frame += std::string(125, 'x');
  17251. strm.write(frame.data(), frame.size());
  17252. ws::Opcode opcode;
  17253. std::string payload;
  17254. bool fin;
  17255. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17256. false, 1024));
  17257. EXPECT_EQ(ws::Opcode::Ping, opcode);
  17258. EXPECT_EQ(125u, payload.size());
  17259. EXPECT_TRUE(fin);
  17260. }
  17261. }
  17262. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  17263. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  17264. // length MUST be 0.
  17265. // MSB set - must be rejected
  17266. {
  17267. detail::BufferStream strm;
  17268. std::string frame;
  17269. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17270. frame += static_cast<char>(127); // 64-bit extended length
  17271. frame += static_cast<char>(0x80); // MSB set (invalid)
  17272. frame += std::string(7, '\0'); // remaining 7 bytes of length
  17273. strm.write(frame.data(), frame.size());
  17274. ws::Opcode opcode;
  17275. std::string payload;
  17276. bool fin;
  17277. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17278. false, 1024));
  17279. }
  17280. // MSB clear - should pass length parsing (will be rejected by max_len,
  17281. // but that's a different check; use a small length to verify)
  17282. {
  17283. detail::BufferStream strm;
  17284. std::string frame;
  17285. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  17286. frame += static_cast<char>(127); // 64-bit extended length
  17287. frame += std::string(7, '\0'); // high bytes = 0
  17288. frame += static_cast<char>(0x03); // length = 3
  17289. frame += "abc";
  17290. strm.write(frame.data(), frame.size());
  17291. ws::Opcode opcode;
  17292. std::string payload;
  17293. bool fin;
  17294. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  17295. false, 1024));
  17296. EXPECT_EQ(ws::Opcode::Text, opcode);
  17297. EXPECT_EQ("abc", payload);
  17298. }
  17299. }
  17300. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  17301. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  17302. // Valid UTF-8
  17303. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  17304. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  17305. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  17306. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  17307. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  17308. // Invalid UTF-8
  17309. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  17310. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  17311. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  17312. EXPECT_FALSE(
  17313. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  17314. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  17315. }
  17316. TEST(WebSocketTest, ConnectAndDisconnect) {
  17317. Server svr;
  17318. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17319. std::string msg;
  17320. while (ws.read(msg)) {}
  17321. });
  17322. auto port = svr.bind_to_any_port(HOST);
  17323. std::thread t([&]() { svr.listen_after_bind(); });
  17324. svr.wait_until_ready();
  17325. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17326. auto res = client.connect();
  17327. ASSERT_TRUE(res);
  17328. EXPECT_EQ(Error::Success, res.error());
  17329. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  17330. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  17331. EXPECT_TRUE(client.is_open());
  17332. client.close();
  17333. EXPECT_FALSE(client.is_open());
  17334. svr.stop();
  17335. t.join();
  17336. }
  17337. TEST(WebSocketTest, ValidURL) {
  17338. ws::WebSocketClient ws1("ws://localhost:8080/path");
  17339. EXPECT_TRUE(ws1.is_valid());
  17340. ws::WebSocketClient ws2("ws://example.com/path");
  17341. EXPECT_TRUE(ws2.is_valid());
  17342. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  17343. EXPECT_TRUE(ws3.is_valid());
  17344. #ifdef CPPHTTPLIB_SSL_ENABLED
  17345. ws::WebSocketClient wss1("wss://example.com/path");
  17346. EXPECT_TRUE(wss1.is_valid());
  17347. ws::WebSocketClient wss2("wss://example.com:443/path");
  17348. EXPECT_TRUE(wss2.is_valid());
  17349. #endif
  17350. }
  17351. TEST(WebSocketTest, InvalidURL) {
  17352. // No scheme
  17353. ws::WebSocketClient ws1("localhost:8080/path");
  17354. EXPECT_FALSE(ws1.is_valid());
  17355. // No path
  17356. ws::WebSocketClient ws2("ws://localhost:8080");
  17357. EXPECT_FALSE(ws2.is_valid());
  17358. // Empty string
  17359. ws::WebSocketClient ws3("");
  17360. EXPECT_FALSE(ws3.is_valid());
  17361. // Missing host
  17362. ws::WebSocketClient ws4("ws://:8080/path");
  17363. EXPECT_FALSE(ws4.is_valid());
  17364. // Port number overflow — should not crash
  17365. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  17366. EXPECT_FALSE(ws5.is_valid());
  17367. // Port out of range
  17368. ws::WebSocketClient ws6("ws://localhost:99999/path");
  17369. EXPECT_FALSE(ws6.is_valid());
  17370. }
  17371. TEST(WebSocketTest, UnsupportedScheme) {
  17372. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17373. ws::WebSocketClient ws1("http://localhost:8080/path");
  17374. EXPECT_FALSE(ws1.is_valid());
  17375. ws::WebSocketClient ws2("https://localhost:8080/path");
  17376. EXPECT_FALSE(ws2.is_valid());
  17377. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  17378. EXPECT_FALSE(ws3.is_valid());
  17379. #else
  17380. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  17381. std::invalid_argument);
  17382. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  17383. std::invalid_argument);
  17384. #endif
  17385. }
  17386. TEST(WebSocketTest, ConnectWhenInvalid) {
  17387. ws::WebSocketClient ws("not a valid url");
  17388. EXPECT_FALSE(ws.is_valid());
  17389. auto res = ws.connect();
  17390. EXPECT_FALSE(res);
  17391. EXPECT_EQ(Error::Connection, res.error());
  17392. EXPECT_EQ(-1, res.status());
  17393. }
  17394. TEST(WebSocketTest, ConnectRefusedReportsError) {
  17395. // Grab a port that is free, then close it again so nothing listens there
  17396. Server svr;
  17397. auto port = svr.bind_to_any_port(HOST);
  17398. svr.stop();
  17399. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17400. auto res = client.connect();
  17401. ASSERT_FALSE(res);
  17402. EXPECT_EQ(Error::Connection, res.error());
  17403. EXPECT_EQ(-1, res.status());
  17404. }
  17405. TEST(WebSocketTest, DefaultPort) {
  17406. ws::WebSocketClient ws1("ws://example.com/path");
  17407. EXPECT_TRUE(ws1.is_valid());
  17408. // ws:// defaults to port 80 (verified by successful parse)
  17409. #ifdef CPPHTTPLIB_SSL_ENABLED
  17410. ws::WebSocketClient ws2("wss://example.com/path");
  17411. EXPECT_TRUE(ws2.is_valid());
  17412. // wss:// defaults to port 443 (verified by successful parse)
  17413. #endif
  17414. }
  17415. TEST(WebSocketTest, IPv6LiteralAddress) {
  17416. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  17417. EXPECT_TRUE(ws1.is_valid());
  17418. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  17419. EXPECT_TRUE(ws2.is_valid());
  17420. }
  17421. TEST(WebSocketTest, ComplexPath) {
  17422. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  17423. EXPECT_TRUE(ws1.is_valid());
  17424. ws::WebSocketClient ws2("ws://localhost:8080/");
  17425. EXPECT_TRUE(ws2.is_valid());
  17426. }
  17427. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  17428. Server svr;
  17429. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17430. std::string msg;
  17431. while (ws.read(msg)) {}
  17432. });
  17433. auto port = svr.bind_to_any_port(HOST);
  17434. std::thread t([&]() { svr.listen_after_bind(); });
  17435. svr.wait_until_ready();
  17436. auto another_host = "example.com";
  17437. auto wrong_ip = "192.0.2.1";
  17438. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17439. client.set_hostname_addr_map({{another_host, wrong_ip}});
  17440. ASSERT_TRUE(client.connect());
  17441. EXPECT_TRUE(client.is_open());
  17442. client.close();
  17443. svr.stop();
  17444. t.join();
  17445. }
  17446. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  17447. Server svr;
  17448. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17449. std::string msg;
  17450. while (ws.read(msg)) {}
  17451. });
  17452. auto port = svr.bind_to_any_port(HOST);
  17453. std::thread t([&]() { svr.listen_after_bind(); });
  17454. svr.wait_until_ready();
  17455. auto wrong_ip = "192.0.2.1";
  17456. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17457. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  17458. client.set_connection_timeout(1);
  17459. client.set_read_timeout(1);
  17460. client.set_write_timeout(1);
  17461. EXPECT_FALSE(client.connect());
  17462. EXPECT_FALSE(client.is_open());
  17463. svr.stop();
  17464. t.join();
  17465. }
  17466. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  17467. // A mapped value that is not an IP literal must be resolved. HOST resolves
  17468. // from the hosts file, so this test needs no external DNS. "target.invalid"
  17469. // (RFC 6761) is only a map key and the Host header value.
  17470. auto host = "target.invalid";
  17471. Server svr;
  17472. std::string received_host;
  17473. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17474. received_host = req.get_header_value("Host");
  17475. std::string msg;
  17476. while (ws.read(msg)) {}
  17477. });
  17478. auto port = svr.bind_to_any_port(HOST);
  17479. std::thread t([&]() { svr.listen_after_bind(); });
  17480. // ASSERT_* below returns from the test body, which would leave t joinable
  17481. // and make ~thread call std::terminate.
  17482. auto se = detail::scope_exit([&] {
  17483. svr.stop();
  17484. if (t.joinable()) { t.join(); }
  17485. });
  17486. svr.wait_until_ready();
  17487. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  17488. std::to_string(port) + "/ws");
  17489. client.set_hostname_addr_map({{host, HOST}});
  17490. ASSERT_TRUE(client.connect());
  17491. EXPECT_TRUE(client.is_open());
  17492. client.close();
  17493. svr.stop();
  17494. t.join();
  17495. // The mapping only redirects the connection; the identity stays host_.
  17496. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  17497. }
  17498. class WebSocketIntegrationTest : public ::testing::Test {
  17499. protected:
  17500. void SetUp() override {
  17501. server_ = httplib::detail::make_unique<Server>();
  17502. setup_server();
  17503. start_server();
  17504. }
  17505. void TearDown() override {
  17506. server_->stop();
  17507. if (server_thread_.joinable()) { server_thread_.join(); }
  17508. }
  17509. void setup_server() {
  17510. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17511. std::string msg;
  17512. ws::ReadResult ret;
  17513. while ((ret = ws.read(msg))) {
  17514. if (ret == ws::Binary) {
  17515. ws.send(msg.data(), msg.size());
  17516. } else {
  17517. ws.send(msg);
  17518. }
  17519. }
  17520. });
  17521. server_->WebSocket("/ws-echo-string",
  17522. [](const Request &, ws::WebSocket &ws) {
  17523. std::string msg;
  17524. while (ws.read(msg)) {
  17525. ws.send("echo: " + msg);
  17526. }
  17527. });
  17528. server_->WebSocket(
  17529. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  17530. // Echo back request metadata
  17531. ws.send("path:" + req.path);
  17532. ws.send("header:" + req.get_header_value("X-Test-Header"));
  17533. std::string msg;
  17534. while (ws.read(msg)) {}
  17535. });
  17536. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  17537. std::string msg;
  17538. ws.read(msg); // wait for a message
  17539. ws.close();
  17540. });
  17541. server_->WebSocket("/ws-close-status",
  17542. [](const Request &, ws::WebSocket &ws) {
  17543. std::string msg;
  17544. ws.read(msg); // wait for a message
  17545. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  17546. });
  17547. server_->WebSocket(
  17548. "/ws-subprotocol",
  17549. [](const Request &, ws::WebSocket &ws) {
  17550. std::string msg;
  17551. while (ws.read(msg)) {
  17552. ws.send(msg);
  17553. }
  17554. },
  17555. [](const std::vector<std::string> &protocols) -> std::string {
  17556. for (const auto &p : protocols) {
  17557. if (p == "graphql-ws") { return p; }
  17558. }
  17559. return "";
  17560. });
  17561. }
  17562. void start_server() {
  17563. port_ = server_->bind_to_any_port(HOST);
  17564. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17565. server_->wait_until_ready();
  17566. }
  17567. std::unique_ptr<Server> server_;
  17568. std::thread server_thread_;
  17569. int port_ = 0;
  17570. };
  17571. TEST_F(WebSocketIntegrationTest, TextEcho) {
  17572. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17573. "/ws-echo");
  17574. ASSERT_TRUE(client.connect());
  17575. ASSERT_TRUE(client.is_open());
  17576. ASSERT_TRUE(client.send("Hello WebSocket"));
  17577. std::string msg;
  17578. EXPECT_EQ(ws::Text, client.read(msg));
  17579. EXPECT_EQ("Hello WebSocket", msg);
  17580. client.close();
  17581. }
  17582. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  17583. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17584. "/ws-echo");
  17585. ASSERT_TRUE(client.connect());
  17586. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  17587. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  17588. std::string msg;
  17589. EXPECT_EQ(ws::Binary, client.read(msg));
  17590. EXPECT_EQ(binary_data, msg);
  17591. client.close();
  17592. }
  17593. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  17594. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17595. "/ws-echo");
  17596. ASSERT_TRUE(client.connect());
  17597. for (int i = 0; i < 10; i++) {
  17598. auto text = "message " + std::to_string(i);
  17599. ASSERT_TRUE(client.send(text));
  17600. std::string msg;
  17601. ASSERT_TRUE(client.read(msg));
  17602. EXPECT_EQ(text, msg);
  17603. }
  17604. client.close();
  17605. }
  17606. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  17607. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17608. "/ws-close");
  17609. ASSERT_TRUE(client.connect());
  17610. // Send a message to trigger the server to close
  17611. ASSERT_TRUE(client.send("trigger close"));
  17612. // The server will close, so read should return false
  17613. std::string msg;
  17614. EXPECT_FALSE(client.read(msg));
  17615. EXPECT_FALSE(client.is_open());
  17616. }
  17617. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  17618. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17619. "/ws-echo");
  17620. ASSERT_TRUE(client.connect());
  17621. // 128KB message
  17622. std::string large_data(128 * 1024, 'X');
  17623. ASSERT_TRUE(client.send(large_data));
  17624. std::string msg;
  17625. ASSERT_TRUE(client.read(msg));
  17626. EXPECT_EQ(large_data, msg);
  17627. client.close();
  17628. }
  17629. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  17630. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17631. "/ws-echo");
  17632. ASSERT_TRUE(client.connect());
  17633. const int num_threads = 4;
  17634. std::vector<std::thread> threads;
  17635. std::atomic<int> send_count{0};
  17636. for (int t = 0; t < num_threads; t++) {
  17637. threads.emplace_back([&client, &send_count, t]() {
  17638. for (int i = 0; i < 5; i++) {
  17639. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  17640. if (client.send(text)) { send_count++; }
  17641. }
  17642. });
  17643. }
  17644. for (auto &th : threads) {
  17645. th.join();
  17646. }
  17647. int received = 0;
  17648. std::string msg;
  17649. while (received < send_count.load()) {
  17650. if (!client.read(msg)) { break; }
  17651. received++;
  17652. }
  17653. EXPECT_EQ(send_count.load(), received);
  17654. client.close();
  17655. }
  17656. TEST_F(WebSocketIntegrationTest, ReadString) {
  17657. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17658. "/ws-echo-string");
  17659. ASSERT_TRUE(client.connect());
  17660. ASSERT_TRUE(client.send("hello"));
  17661. std::string msg;
  17662. ASSERT_TRUE(client.read(msg));
  17663. EXPECT_EQ("echo: hello", msg);
  17664. ASSERT_TRUE(client.send("world"));
  17665. ASSERT_TRUE(client.read(msg));
  17666. EXPECT_EQ("echo: world", msg);
  17667. client.close();
  17668. }
  17669. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  17670. Headers headers = {{"X-Test-Header", "test-value"}};
  17671. ws::WebSocketClient client(
  17672. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  17673. ASSERT_TRUE(client.connect());
  17674. std::string msg;
  17675. ASSERT_TRUE(client.read(msg));
  17676. EXPECT_EQ("path:/ws-request-info", msg);
  17677. ASSERT_TRUE(client.read(msg));
  17678. EXPECT_EQ("header:test-value", msg);
  17679. client.close();
  17680. }
  17681. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  17682. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17683. "/ws-echo");
  17684. client.set_read_timeout(1, 0); // 1 second
  17685. ASSERT_TRUE(client.connect());
  17686. // Don't send anything — server echo handler waits for a message,
  17687. // so read() should time out and return false.
  17688. std::string msg;
  17689. EXPECT_FALSE(client.read(msg));
  17690. }
  17691. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  17692. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17693. "/ws-echo");
  17694. client.set_read_timeout(5, 0);
  17695. ASSERT_TRUE(client.connect());
  17696. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17697. // The server should reject it and close the connection.
  17698. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  17699. client.send(oversized);
  17700. // The server's read() should have failed due to payload limit,
  17701. // so our read() should return false (connection closed).
  17702. std::string msg;
  17703. EXPECT_FALSE(client.read(msg));
  17704. }
  17705. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  17706. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17707. "/ws-echo");
  17708. client.set_read_timeout(10, 0);
  17709. ASSERT_TRUE(client.connect());
  17710. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17711. // This should succeed.
  17712. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  17713. ASSERT_TRUE(client.send(at_limit));
  17714. std::string msg;
  17715. ASSERT_TRUE(client.read(msg));
  17716. EXPECT_EQ(at_limit.size(), msg.size());
  17717. client.close();
  17718. }
  17719. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  17720. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17721. "/nonexistent");
  17722. auto res = client.connect();
  17723. EXPECT_FALSE(res);
  17724. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  17725. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  17726. EXPECT_FALSE(client.is_open());
  17727. }
  17728. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  17729. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17730. "/ws-echo");
  17731. ASSERT_TRUE(client.connect());
  17732. ASSERT_TRUE(client.send(""));
  17733. std::string msg;
  17734. EXPECT_EQ(ws::Text, client.read(msg));
  17735. EXPECT_EQ("", msg);
  17736. client.close();
  17737. }
  17738. TEST_F(WebSocketIntegrationTest, Reconnect) {
  17739. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17740. "/ws-echo");
  17741. // First connection
  17742. ASSERT_TRUE(client.connect());
  17743. ASSERT_TRUE(client.send("first"));
  17744. std::string msg;
  17745. ASSERT_TRUE(client.read(msg));
  17746. EXPECT_EQ("first", msg);
  17747. client.close();
  17748. EXPECT_FALSE(client.is_open());
  17749. // Reconnect using the same client object
  17750. ASSERT_TRUE(client.connect());
  17751. ASSERT_TRUE(client.is_open());
  17752. ASSERT_TRUE(client.send("second"));
  17753. ASSERT_TRUE(client.read(msg));
  17754. EXPECT_EQ("second", msg);
  17755. client.close();
  17756. }
  17757. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  17758. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17759. "/ws-close-status");
  17760. ASSERT_TRUE(client.connect());
  17761. // Trigger the server to close with GoingAway status
  17762. ASSERT_TRUE(client.send("trigger"));
  17763. // read() should return false after receiving the close frame
  17764. std::string msg;
  17765. EXPECT_FALSE(client.read(msg));
  17766. EXPECT_FALSE(client.is_open());
  17767. }
  17768. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  17769. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17770. "/ws-echo");
  17771. ASSERT_TRUE(client.connect());
  17772. client.close(ws::CloseStatus::GoingAway, "client leaving");
  17773. EXPECT_FALSE(client.is_open());
  17774. }
  17775. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  17776. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  17777. ws::WebSocketClient client(
  17778. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17779. ASSERT_TRUE(client.connect());
  17780. // Server should have selected graphql-ws
  17781. EXPECT_EQ("graphql-ws", client.subprotocol());
  17782. client.close();
  17783. }
  17784. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  17785. Headers headers;
  17786. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  17787. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  17788. ws::WebSocketClient client(
  17789. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17790. ASSERT_TRUE(client.connect());
  17791. // The offer on the second field line counts too, so graphql-ws is selected
  17792. EXPECT_EQ("graphql-ws", client.subprotocol());
  17793. client.close();
  17794. }
  17795. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  17796. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  17797. ws::WebSocketClient client(
  17798. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17799. ASSERT_TRUE(client.connect());
  17800. // Server should not have selected any subprotocol
  17801. EXPECT_TRUE(client.subprotocol().empty());
  17802. client.close();
  17803. }
  17804. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  17805. // Connect without requesting any subprotocol
  17806. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17807. "/ws-subprotocol");
  17808. ASSERT_TRUE(client.connect());
  17809. EXPECT_TRUE(client.subprotocol().empty());
  17810. client.close();
  17811. }
  17812. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  17813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17814. "/ws-echo");
  17815. client.set_tcp_nodelay(true);
  17816. client.set_connection_timeout(3, 0);
  17817. bool socket_options_called = false;
  17818. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  17819. ASSERT_TRUE(client.connect());
  17820. ASSERT_TRUE(client.is_open());
  17821. EXPECT_TRUE(socket_options_called);
  17822. ASSERT_TRUE(client.send("hello"));
  17823. std::string msg;
  17824. auto result = client.read(msg);
  17825. EXPECT_EQ(result, ws::ReadResult::Text);
  17826. EXPECT_EQ(msg, "hello");
  17827. client.close();
  17828. }
  17829. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  17830. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17831. "/ws-echo");
  17832. client.set_connection_timeout(std::chrono::seconds(3));
  17833. client.set_write_timeout(std::chrono::seconds(3));
  17834. // A sub-second remainder exercises the seconds/microseconds split.
  17835. client.set_read_timeout(std::chrono::milliseconds(1500));
  17836. ASSERT_TRUE(client.connect());
  17837. auto start = std::chrono::steady_clock::now();
  17838. std::string msg;
  17839. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  17840. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17841. std::chrono::steady_clock::now() - start)
  17842. .count();
  17843. // Above 1s so that dropping the microseconds half of the split fails here,
  17844. // and well under the 300s default so that ignoring the setter fails too.
  17845. EXPECT_GE(elapsed, 1400);
  17846. EXPECT_LT(elapsed, 30000);
  17847. }
  17848. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  17849. Server svr;
  17850. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  17851. if (!req.has_header("Authorization")) {
  17852. res.status = StatusCode::Unauthorized_401;
  17853. res.set_content("Unauthorized", "text/plain");
  17854. return Server::HandlerResponse::Handled;
  17855. }
  17856. return Server::HandlerResponse::Unhandled;
  17857. });
  17858. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17859. std::string msg;
  17860. while (ws.read(msg)) {
  17861. ws.send(msg);
  17862. }
  17863. });
  17864. auto port = svr.bind_to_any_port("localhost");
  17865. std::thread t([&]() { svr.listen_after_bind(); });
  17866. svr.wait_until_ready();
  17867. // Without Authorization header - should be rejected before upgrade
  17868. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  17869. EXPECT_FALSE(client1.connect());
  17870. // With Authorization header - should succeed
  17871. Headers headers = {{"Authorization", "Bearer token123"}};
  17872. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  17873. headers);
  17874. ASSERT_TRUE(client2.connect());
  17875. ASSERT_TRUE(client2.send("hello"));
  17876. std::string msg;
  17877. ASSERT_TRUE(client2.read(msg));
  17878. EXPECT_EQ("hello", msg);
  17879. client2.close();
  17880. svr.stop();
  17881. t.join();
  17882. }
  17883. TEST(WebSocketTest, QueryStringInHandshake) {
  17884. Server svr;
  17885. std::mutex mtx;
  17886. std::string received_target;
  17887. std::string received_token;
  17888. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17889. {
  17890. std::lock_guard<std::mutex> lock(mtx);
  17891. received_target = req.target;
  17892. if (req.has_param("token")) {
  17893. received_token = req.get_param_value("token");
  17894. }
  17895. }
  17896. std::string msg;
  17897. while (ws.read(msg)) {
  17898. ws.send(msg);
  17899. }
  17900. });
  17901. auto port = svr.bind_to_any_port("localhost");
  17902. std::thread t([&]() { svr.listen_after_bind(); });
  17903. svr.wait_until_ready();
  17904. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  17905. "/ws?token=ABC&session=123");
  17906. ASSERT_TRUE(client.connect());
  17907. // Round-trip ensures the handler has run and captured the request.
  17908. ASSERT_TRUE(client.send("hello"));
  17909. std::string msg;
  17910. ASSERT_TRUE(client.read(msg));
  17911. EXPECT_EQ("hello", msg);
  17912. client.close();
  17913. {
  17914. std::lock_guard<std::mutex> lock(mtx);
  17915. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  17916. EXPECT_EQ("ABC", received_token);
  17917. }
  17918. svr.stop();
  17919. t.join();
  17920. }
  17921. // Run a handshake against a throwaway server and hand the request the server
  17922. // received back to the caller, so tests can assert on the headers the client
  17923. // actually put on the wire.
  17924. static void capture_websocket_handshake_request(
  17925. const Headers &client_headers,
  17926. std::function<void(const Request &, int port)> verify) {
  17927. Server svr;
  17928. std::mutex mtx;
  17929. Request received;
  17930. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17931. {
  17932. std::lock_guard<std::mutex> lock(mtx);
  17933. received = req;
  17934. }
  17935. std::string msg;
  17936. while (ws.read(msg)) {
  17937. ws.send(msg);
  17938. }
  17939. });
  17940. auto port = svr.bind_to_any_port("localhost");
  17941. std::thread t([&]() { svr.listen_after_bind(); });
  17942. auto se = detail::scope_exit([&] {
  17943. svr.stop();
  17944. t.join();
  17945. });
  17946. svr.wait_until_ready();
  17947. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  17948. client_headers);
  17949. ASSERT_TRUE(client.connect());
  17950. ASSERT_TRUE(client.send("hello"));
  17951. std::string msg;
  17952. ASSERT_TRUE(client.read(msg));
  17953. client.close();
  17954. {
  17955. std::lock_guard<std::mutex> lock(mtx);
  17956. verify(received, port);
  17957. }
  17958. }
  17959. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  17960. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  17961. // Non-default port must be present in the Host header. Default ports
  17962. // (80/443) are omitted; that logic is covered by
  17963. // MakeHostAndPortStringTest.
  17964. EXPECT_EQ("localhost:" + std::to_string(port),
  17965. req.get_header_value("Host"));
  17966. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  17967. req.get_header_value("User-Agent"));
  17968. EXPECT_FALSE(req.has_header("Accept"));
  17969. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  17970. EXPECT_FALSE(req.has_header("Content-Length"));
  17971. });
  17972. }
  17973. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  17974. capture_websocket_handshake_request(
  17975. {{"Host", "example.com"},
  17976. {"User-Agent", "custom-agent"},
  17977. {"X-Custom", "value"}},
  17978. [](const Request &req, int) {
  17979. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17980. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17981. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17982. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17983. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17984. });
  17985. }
  17986. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17987. capture_websocket_handshake_request(
  17988. {{"Upgrade", "bogus"},
  17989. {"Connection", "close"},
  17990. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17991. {"Sec-WebSocket-Version", "8"}},
  17992. [](const Request &req, int) {
  17993. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17994. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17995. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17996. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17997. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17998. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17999. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  18000. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  18001. req.get_header_value("Sec-WebSocket-Key"));
  18002. });
  18003. }
  18004. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  18005. // A header the client refuses to send must abort the handshake before any
  18006. // part of it reaches the wire; a lone request line would otherwise sit in
  18007. // the peer's buffer as a truncated request.
  18008. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18009. ASSERT_NE(INVALID_SOCKET, srv);
  18010. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  18011. sockaddr_in addr{};
  18012. addr.sin_family = AF_INET;
  18013. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  18014. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18015. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18016. ASSERT_EQ(0, ::listen(srv, 1));
  18017. sockaddr_in bound{};
  18018. socklen_t bound_len = sizeof(bound);
  18019. ASSERT_EQ(
  18020. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  18021. auto port = ntohs(bound.sin_port);
  18022. ssize_t received = -1;
  18023. std::thread t([&] {
  18024. // Bound every blocking call so a regression fails the test with a bad
  18025. // value instead of hanging the suite.
  18026. fd_set rfds;
  18027. FD_ZERO(&rfds);
  18028. FD_SET(srv, &rfds);
  18029. timeval tv{5, 0};
  18030. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  18031. 0) {
  18032. return;
  18033. }
  18034. sockaddr_in cli_addr{};
  18035. socklen_t cli_len = sizeof(cli_addr);
  18036. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18037. if (cli == INVALID_SOCKET) { return; }
  18038. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  18039. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18040. char buf[4096];
  18041. received = ::recv(cli, buf, sizeof(buf), 0);
  18042. });
  18043. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  18044. // connect() has already shut the socket down by the time it returns false,
  18045. // so the peer sees EOF without waiting for the client to be destroyed.
  18046. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  18047. {{"X-Bad", "a\r\nInjected: 1"}});
  18048. EXPECT_FALSE(client.connect());
  18049. t.join();
  18050. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  18051. EXPECT_EQ(0, received);
  18052. }
  18053. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  18054. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  18055. // contains "upgrade" as a substring is a different token and must not
  18056. // start a WebSocket handshake.
  18057. auto make_request = [](const std::vector<std::string> &connection_values) {
  18058. Request req;
  18059. req.method = "GET";
  18060. req.headers.emplace("Upgrade", "websocket");
  18061. for (const auto &value : connection_values) {
  18062. req.headers.emplace("Connection", value);
  18063. }
  18064. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18065. req.headers.emplace("Sec-WebSocket-Version", "13");
  18066. return req;
  18067. };
  18068. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  18069. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  18070. EXPECT_TRUE(
  18071. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  18072. EXPECT_TRUE(
  18073. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  18074. EXPECT_TRUE(
  18075. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  18076. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  18077. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  18078. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  18079. EXPECT_FALSE(
  18080. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  18081. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  18082. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18083. }
  18084. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  18085. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  18086. // asks recipients to match each protocol-name case-insensitively, and RFC
  18087. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  18088. // client naming websocket alongside another protocol, or on a second field
  18089. // line, is offering websocket; a value that merely contains "websocket" as a
  18090. // substring is a different protocol name and is not.
  18091. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  18092. Request req;
  18093. req.method = "GET";
  18094. for (const auto &value : upgrade_values) {
  18095. req.headers.emplace("Upgrade", value);
  18096. }
  18097. req.headers.emplace("Connection", "Upgrade");
  18098. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  18099. req.headers.emplace("Sec-WebSocket-Version", "13");
  18100. return req;
  18101. };
  18102. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  18103. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  18104. EXPECT_TRUE(
  18105. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  18106. EXPECT_TRUE(
  18107. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  18108. EXPECT_TRUE(
  18109. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  18110. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  18111. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  18112. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  18113. EXPECT_FALSE(
  18114. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  18115. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  18116. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  18117. }
  18118. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  18119. Server svr;
  18120. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  18121. auto port = svr.bind_to_any_port("localhost");
  18122. std::thread t([&]() { svr.listen_after_bind(); });
  18123. auto se = detail::scope_exit([&] {
  18124. svr.stop();
  18125. t.join();
  18126. });
  18127. svr.wait_until_ready();
  18128. Headers headers = {{"Upgrade", "websocket"},
  18129. {"Connection", "notupgrade"},
  18130. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  18131. {"Sec-WebSocket-Version", "13"}};
  18132. Client cli("localhost", port);
  18133. auto res = cli.Get("/ws", headers);
  18134. // The route exists only as a WebSocket route, so a request that fails the
  18135. // handshake check falls through to ordinary routing.
  18136. ASSERT_TRUE(res);
  18137. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  18138. }
  18139. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  18140. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  18141. // Connection value is the only thing left for the client to reject.
  18142. Server svr;
  18143. svr.Get("/ws", [](const Request &req, Response &res) {
  18144. res.status = StatusCode::SwitchingProtocol_101;
  18145. res.set_header("Upgrade", "websocket");
  18146. res.set_header("Connection", "notupgrade");
  18147. res.set_header("Sec-WebSocket-Accept",
  18148. detail::websocket_accept_key(
  18149. req.get_header_value("Sec-WebSocket-Key")));
  18150. });
  18151. auto port = svr.bind_to_any_port("localhost");
  18152. std::thread t([&]() { svr.listen_after_bind(); });
  18153. auto se = detail::scope_exit([&] {
  18154. svr.stop();
  18155. t.join();
  18156. });
  18157. svr.wait_until_ready();
  18158. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18159. auto res = client.connect();
  18160. EXPECT_FALSE(res);
  18161. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  18162. EXPECT_FALSE(client.is_open());
  18163. }
  18164. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  18165. // The socket path doubles as the URL host, so it must not contain '/'.
  18166. const char *shard = getenv("GTEST_SHARD_INDEX");
  18167. const std::string sock_path =
  18168. shard ? std::string("httplib-ws-") + shard + ".sock"
  18169. : std::string("httplib-ws.sock");
  18170. std::remove(sock_path.c_str());
  18171. Server svr;
  18172. std::mutex mtx;
  18173. std::string received_host;
  18174. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18175. {
  18176. std::lock_guard<std::mutex> lock(mtx);
  18177. received_host = req.get_header_value("Host");
  18178. }
  18179. std::string msg;
  18180. while (ws.read(msg)) {
  18181. ws.send(msg);
  18182. }
  18183. });
  18184. svr.set_address_family(AF_UNIX);
  18185. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  18186. auto se = detail::scope_exit([&] {
  18187. svr.stop();
  18188. t.join();
  18189. std::remove(sock_path.c_str());
  18190. });
  18191. svr.wait_until_ready();
  18192. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  18193. client.set_address_family(AF_UNIX);
  18194. ASSERT_TRUE(client.connect());
  18195. ASSERT_TRUE(client.send("hello"));
  18196. std::string msg;
  18197. ASSERT_TRUE(client.read(msg));
  18198. client.close();
  18199. {
  18200. std::lock_guard<std::mutex> lock(mtx);
  18201. // There is no host:port for a Unix socket, so the same "localhost"
  18202. // placeholder the HTTP client uses is expected.
  18203. EXPECT_EQ("localhost", received_host);
  18204. }
  18205. }
  18206. // Two threads must never parse WebSocket frames from the same stream.
  18207. // close() used to read the peer's Close reply with its own frame read, so it
  18208. // raced a reader thread that was in the middle of a payload: the payload loop
  18209. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  18210. // so bytes taken by close() were replaced with bytes from further along the
  18211. // stream. The message kept its length and silently changed content.
  18212. //
  18213. // The raw peer below sends a frame header plus part of the payload, waits for
  18214. // the handler to call close(), and only then sends the rest. Whichever thread
  18215. // would win the race for those bytes, the message must arrive intact, because
  18216. // close() must not touch the stream while read() owns it.
  18217. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  18218. #ifndef _WIN32
  18219. signal(SIGPIPE, SIG_IGN);
  18220. #endif
  18221. const size_t payload_len = 120; // fits the 7-bit length field
  18222. const size_t prefix_len = 8;
  18223. const int attempts = 8;
  18224. std::string expected(payload_len, '\0');
  18225. for (size_t i = 0; i < payload_len; i++) {
  18226. expected[i] = static_cast<char>('a' + i % 26);
  18227. }
  18228. std::atomic<bool> peer_stalled{false};
  18229. std::atomic<bool> handler_done{false};
  18230. std::mutex received_mutex;
  18231. std::vector<std::string> received;
  18232. // Bound every wait, so a regression fails the test instead of hanging the
  18233. // suite.
  18234. auto wait_for = [](const std::atomic<bool> &flag) {
  18235. for (int i = 0; i < 500 && !flag; i++) {
  18236. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18237. }
  18238. };
  18239. Server svr;
  18240. svr.set_websocket_ping_interval(0);
  18241. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  18242. std::thread reader([&]() {
  18243. std::string msg;
  18244. while (ws.read(msg)) {
  18245. std::lock_guard<std::mutex> guard(received_mutex);
  18246. received.push_back(msg);
  18247. }
  18248. });
  18249. // Wait until the peer stalls mid-payload, so the reader thread is parked
  18250. // inside read_websocket_frame() when close() runs.
  18251. wait_for(peer_stalled);
  18252. ws.close();
  18253. reader.join();
  18254. handler_done = true;
  18255. });
  18256. auto port = svr.bind_to_any_port("127.0.0.1");
  18257. std::thread t([&]() { svr.listen_after_bind(); });
  18258. auto se = detail::scope_exit([&] {
  18259. svr.stop();
  18260. t.join();
  18261. });
  18262. svr.wait_until_ready();
  18263. auto send_bytes = [](socket_t s, const std::string &data) {
  18264. #ifdef _WIN32
  18265. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  18266. #else
  18267. auto n = ::send(s, data.data(), data.size(), 0);
  18268. #endif
  18269. return n == static_cast<decltype(n)>(data.size());
  18270. };
  18271. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  18272. // Every length used here fits the 7-bit length field.
  18273. auto masked_header = [](uint8_t first_byte, size_t len) {
  18274. std::string h;
  18275. h += static_cast<char>(first_byte);
  18276. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  18277. h.append(4, '\0'); // mask key
  18278. return h;
  18279. };
  18280. for (int attempt = 0; attempt < attempts; attempt++) {
  18281. peer_stalled = false;
  18282. handler_done = false;
  18283. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  18284. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  18285. auto se_sock = detail::scope_exit([&] {
  18286. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  18287. });
  18288. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18289. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18290. sockaddr_in addr{};
  18291. addr.sin_family = AF_INET;
  18292. addr.sin_port = htons(static_cast<uint16_t>(port));
  18293. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18294. ASSERT_EQ(
  18295. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  18296. << "attempt " << attempt;
  18297. ASSERT_TRUE(send_bytes(sock,
  18298. "GET /ws HTTP/1.1\r\n"
  18299. "Host: 127.0.0.1\r\n"
  18300. "Upgrade: websocket\r\n"
  18301. "Connection: Upgrade\r\n"
  18302. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  18303. "Sec-WebSocket-Version: 13\r\n"
  18304. "\r\n"))
  18305. << "attempt " << attempt;
  18306. std::string response;
  18307. while (response.find("\r\n\r\n") == std::string::npos) {
  18308. char buf[512];
  18309. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  18310. if (n <= 0) { break; }
  18311. response.append(buf, static_cast<size_t>(n));
  18312. }
  18313. ASSERT_NE(std::string::npos, response.find(" 101 "))
  18314. << "attempt " << attempt;
  18315. // Send the header of a Binary message but only the first prefix_len bytes
  18316. // of its payload, leaving the reader thread stalled inside the payload.
  18317. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  18318. expected.substr(0, prefix_len)))
  18319. << "attempt " << attempt;
  18320. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18321. peer_stalled = true;
  18322. // Let close() send its Close frame and park in its own read before the
  18323. // rest of the payload arrives, so both threads are waiting for it.
  18324. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18325. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  18326. close_frame += static_cast<char>(0x03); // status 1000
  18327. close_frame += static_cast<char>(0xE8);
  18328. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  18329. << "attempt " << attempt;
  18330. // Closing the peer releases the reader thread even on the buggy path,
  18331. // where it waits for bytes another thread already consumed.
  18332. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18333. detail::close_socket(sock);
  18334. sock = INVALID_SOCKET;
  18335. wait_for(handler_done);
  18336. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  18337. }
  18338. std::lock_guard<std::mutex> guard(received_mutex);
  18339. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  18340. << "a message in flight when close() ran was dropped";
  18341. for (size_t i = 0; i < received.size(); i++) {
  18342. EXPECT_EQ(expected, received[i]) << "message " << i;
  18343. }
  18344. }
  18345. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18346. class WebSocketSSLIntegrationTest : public ::testing::Test {
  18347. protected:
  18348. void SetUp() override {
  18349. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  18350. SERVER_PRIVATE_KEY_FILE);
  18351. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18352. std::string msg;
  18353. ws::ReadResult ret;
  18354. while ((ret = ws.read(msg))) {
  18355. if (ret == ws::Binary) {
  18356. ws.send(msg.data(), msg.size());
  18357. } else {
  18358. ws.send(msg);
  18359. }
  18360. }
  18361. });
  18362. port_ = server_->bind_to_any_port(HOST);
  18363. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18364. server_->wait_until_ready();
  18365. }
  18366. void TearDown() override {
  18367. server_->stop();
  18368. if (server_thread_.joinable()) { server_thread_.join(); }
  18369. }
  18370. std::unique_ptr<SSLServer> server_;
  18371. std::thread server_thread_;
  18372. int port_ = 0;
  18373. };
  18374. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  18375. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18376. "/ws-echo");
  18377. client.enable_server_certificate_verification(false);
  18378. ASSERT_TRUE(client.connect());
  18379. ASSERT_TRUE(client.is_open());
  18380. ASSERT_TRUE(client.send("Hello WSS"));
  18381. std::string msg;
  18382. EXPECT_EQ(ws::Text, client.read(msg));
  18383. EXPECT_EQ("Hello WSS", msg);
  18384. client.close();
  18385. }
  18386. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  18387. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  18388. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  18389. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  18390. // client (without calling close() first) is the only path that runs
  18391. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  18392. // bug exactly.
  18393. //
  18394. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  18395. // when linked against an instrumented libssl; run under Valgrind to catch it
  18396. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  18397. // suite (the freed session otherwise stalls on the close handshake) — this test
  18398. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  18399. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  18400. {
  18401. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18402. "/ws-echo");
  18403. client.enable_server_certificate_verification(false);
  18404. client.set_read_timeout(2, 0);
  18405. client.set_write_timeout(2, 0);
  18406. ASSERT_TRUE(client.connect());
  18407. ASSERT_TRUE(client.is_open());
  18408. ASSERT_TRUE(client.send("still open"));
  18409. // Intentionally do NOT call client.close(): leaving scope runs
  18410. // shutdown_and_close() with the WebSocket still open, which must send the
  18411. // close frame while the TLS session is still alive.
  18412. }
  18413. }
  18414. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  18415. // shutdown_and_close() at the start of connect(), reproducing the same
  18416. // use-after-free within the test body rather than at scope exit. The second
  18417. // connect must succeed and echo, proving the close handshake ran over a live
  18418. // session. See the note above about memory-tool requirements.
  18419. TEST_F(WebSocketSSLIntegrationTest,
  18420. ReconnectWhileOpenSendsCloseOverLiveSession) {
  18421. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  18422. "/ws-echo");
  18423. client.enable_server_certificate_verification(false);
  18424. client.set_read_timeout(2, 0);
  18425. client.set_write_timeout(2, 0);
  18426. ASSERT_TRUE(client.connect());
  18427. ASSERT_TRUE(client.is_open());
  18428. ASSERT_TRUE(client.send("still open"));
  18429. // Reconnect without closing first: connect() calls shutdown_and_close() on
  18430. // the still-open connection, which must not touch a freed TLS session.
  18431. ASSERT_TRUE(client.connect());
  18432. ASSERT_TRUE(client.is_open());
  18433. ASSERT_TRUE(client.send("after reconnect"));
  18434. std::string msg;
  18435. EXPECT_EQ(ws::Text, client.read(msg));
  18436. EXPECT_EQ("after reconnect", msg);
  18437. client.close();
  18438. }
  18439. #endif
  18440. #ifdef CPPHTTPLIB_SSL_ENABLED
  18441. class WebSocketSSLCATest : public ::testing::Test {
  18442. protected:
  18443. void SetUp() override {
  18444. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  18445. SERVER_PRIVATE_KEY_FILE);
  18446. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18447. std::string msg;
  18448. while (ws.read(msg)) {
  18449. ws.send(msg);
  18450. }
  18451. });
  18452. port_ = server_->bind_to_any_port("127.0.0.1");
  18453. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18454. server_->wait_until_ready();
  18455. }
  18456. void TearDown() override {
  18457. server_->stop();
  18458. if (server_thread_.joinable()) { server_thread_.join(); }
  18459. }
  18460. std::string url() const {
  18461. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  18462. }
  18463. std::unique_ptr<SSLServer> server_;
  18464. std::thread server_thread_;
  18465. int port_ = 0;
  18466. };
  18467. // A custom CA loaded as PEM verifies the server with full certificate
  18468. // verification enabled
  18469. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  18470. ws::WebSocketClient client(url());
  18471. std::string cert;
  18472. read_file(SERVER_CERT2_FILE, cert);
  18473. client.load_ca_cert_store(cert.c_str(), cert.size());
  18474. ASSERT_TRUE(client.connect());
  18475. ASSERT_TRUE(client.send("hello"));
  18476. std::string msg;
  18477. EXPECT_EQ(ws::Text, client.read(msg));
  18478. EXPECT_EQ("hello", msg);
  18479. client.close();
  18480. }
  18481. // A custom CA that does not cover the server must fail verification (the
  18482. // custom CA is exclusive; system certs are not loaded alongside it)
  18483. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  18484. ws::WebSocketClient client(url());
  18485. std::string cert;
  18486. read_file(CLIENT_CA_CERT_FILE, cert);
  18487. client.load_ca_cert_store(cert.c_str(), cert.size());
  18488. auto res = client.connect();
  18489. ASSERT_FALSE(res);
  18490. EXPECT_EQ(Error::SSLServerVerification, res.error());
  18491. EXPECT_EQ(-1, res.status());
  18492. EXPECT_NE(0u, res.ssl_backend_error());
  18493. }
  18494. // The same CA as a file path rather than PEM in memory
  18495. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  18496. ws::WebSocketClient client(url());
  18497. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18498. ASSERT_TRUE(client.connect());
  18499. ASSERT_TRUE(client.send("hello"));
  18500. std::string msg;
  18501. EXPECT_EQ(ws::Text, client.read(msg));
  18502. EXPECT_EQ("hello", msg);
  18503. client.close();
  18504. }
  18505. // ...and a CA file that does not cover the server still fails, so it is the
  18506. // path above that decides the outcome
  18507. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  18508. ws::WebSocketClient client(url());
  18509. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18510. ASSERT_FALSE(client.connect());
  18511. }
  18512. // Regression test: reconnecting with a native custom CA store used to reuse
  18513. // a store handle the previous TLS context had already freed (use-after-free
  18514. // under the OpenSSL backend). The context now lives as long as the client.
  18515. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  18516. ws::WebSocketClient client(url());
  18517. std::string cert;
  18518. read_file(SERVER_CERT2_FILE, cert);
  18519. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  18520. ASSERT_TRUE(client.connect());
  18521. client.close();
  18522. ASSERT_TRUE(client.connect());
  18523. ASSERT_TRUE(client.send("again"));
  18524. std::string msg;
  18525. EXPECT_EQ(ws::Text, client.read(msg));
  18526. EXPECT_EQ("again", msg);
  18527. client.close();
  18528. }
  18529. // Regression test: a certificate with a trusted chain but no identity match
  18530. // for the server IP must be rejected. The Mbed TLS backend used to skip
  18531. // verification entirely for IP hosts, so this connection succeeded there.
  18532. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  18533. // chain verification while the identity check must still fail.
  18534. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  18535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18536. ASSERT_TRUE(svr.is_valid());
  18537. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18538. std::string msg;
  18539. while (ws.read(msg)) {
  18540. ws.send(msg);
  18541. }
  18542. });
  18543. auto port = svr.bind_to_any_port("127.0.0.1");
  18544. auto t = std::thread([&]() { svr.listen_after_bind(); });
  18545. auto se = detail::scope_exit([&] {
  18546. svr.stop();
  18547. t.join();
  18548. });
  18549. svr.wait_until_ready();
  18550. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  18551. "/echo");
  18552. std::string cert;
  18553. read_file(SERVER_CERT_FILE, cert);
  18554. client.load_ca_cert_store(cert.c_str(), cert.size());
  18555. ASSERT_FALSE(client.connect());
  18556. }
  18557. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  18558. // SNI, so nothing binds the host name to the TLS session. These bind the
  18559. // server to "localhost" instead, the only shape that exercises the SNI and
  18560. // hostname-verification path with certificate verification left enabled.
  18561. class WebSocketSSLDnsHostTest : public ::testing::Test {
  18562. protected:
  18563. void Start(const char *cert_file) {
  18564. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  18565. SERVER_PRIVATE_KEY_FILE);
  18566. ASSERT_TRUE(server_->is_valid());
  18567. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  18568. std::string msg;
  18569. while (ws.read(msg)) {
  18570. ws.send(msg);
  18571. }
  18572. });
  18573. port_ = server_->bind_to_any_port("localhost");
  18574. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18575. server_->wait_until_ready();
  18576. }
  18577. void TearDown() override {
  18578. if (server_) { server_->stop(); }
  18579. if (server_thread_.joinable()) { server_thread_.join(); }
  18580. }
  18581. std::string url() const {
  18582. return "wss://localhost:" + std::to_string(port_) + "/echo";
  18583. }
  18584. std::unique_ptr<SSLServer> server_;
  18585. std::thread server_thread_;
  18586. int port_ = 0;
  18587. };
  18588. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  18589. // out and the connection is usable
  18590. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  18591. Start(SERVER_CERT2_FILE);
  18592. ws::WebSocketClient client(url());
  18593. client.set_ca_cert_path(SERVER_CERT2_FILE);
  18594. ASSERT_TRUE(client.connect());
  18595. ASSERT_TRUE(client.send("hello"));
  18596. std::string msg;
  18597. EXPECT_EQ(ws::Text, client.read(msg));
  18598. EXPECT_EQ("hello", msg);
  18599. client.close();
  18600. }
  18601. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  18602. // while the identity check must still reject "localhost"
  18603. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  18604. Start(SERVER_CERT_FILE);
  18605. ws::WebSocketClient client(url());
  18606. client.set_ca_cert_path(SERVER_CERT_FILE);
  18607. auto res = client.connect();
  18608. ASSERT_FALSE(res);
  18609. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  18610. EXPECT_EQ(-1, res.status());
  18611. }
  18612. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  18613. // disabled: the chain is still checked, only the identity check is skipped
  18614. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  18615. Start(SERVER_CERT_FILE);
  18616. ws::WebSocketClient client(url());
  18617. client.set_ca_cert_path(SERVER_CERT_FILE);
  18618. client.enable_server_hostname_verification(false);
  18619. ASSERT_TRUE(client.connect());
  18620. ASSERT_TRUE(client.send("hello"));
  18621. std::string msg;
  18622. EXPECT_EQ(ws::Text, client.read(msg));
  18623. EXPECT_EQ("hello", msg);
  18624. client.close();
  18625. }
  18626. // A CA that did not sign the server certificate fails the chain, even though
  18627. // the name would match
  18628. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  18629. Start(SERVER_CERT2_FILE);
  18630. ws::WebSocketClient client(url());
  18631. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  18632. ASSERT_FALSE(client.connect());
  18633. }
  18634. // With verification disabled, neither the chain nor the name is checked
  18635. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  18636. Start(SERVER_CERT_FILE);
  18637. ws::WebSocketClient client(url());
  18638. client.enable_server_certificate_verification(false);
  18639. ASSERT_TRUE(client.connect());
  18640. ASSERT_TRUE(client.send("hello"));
  18641. std::string msg;
  18642. EXPECT_EQ(ws::Text, client.read(msg));
  18643. EXPECT_EQ("hello", msg);
  18644. client.close();
  18645. }
  18646. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  18647. protected:
  18648. void SetUp() override {
  18649. server_ = httplib::detail::make_unique<SSLServer>(
  18650. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18651. ASSERT_TRUE(server_->is_valid());
  18652. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  18653. std::string msg;
  18654. while (ws.read(msg)) {
  18655. ws.send(msg);
  18656. }
  18657. });
  18658. port_ = server_->bind_to_any_port("localhost");
  18659. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18660. server_->wait_until_ready();
  18661. }
  18662. void TearDown() override {
  18663. server_->stop();
  18664. if (server_thread_.joinable()) { server_thread_.join(); }
  18665. }
  18666. std::string url() const {
  18667. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  18668. }
  18669. void ConnectWithClientCert(const std::string &client_cert_file,
  18670. const std::string &client_private_key_file,
  18671. const char *private_key_password) {
  18672. std::string cert_pem, key_pem;
  18673. read_file(client_cert_file, cert_pem);
  18674. read_file(client_private_key_file, key_pem);
  18675. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  18676. key_pem.c_str(), key_pem.size(),
  18677. private_key_password};
  18678. ws::WebSocketClient client(url(), pem);
  18679. ASSERT_TRUE(client.is_valid());
  18680. client.enable_server_certificate_verification(false);
  18681. ASSERT_TRUE(client.connect());
  18682. ASSERT_TRUE(client.send("hello"));
  18683. std::string msg;
  18684. EXPECT_EQ(ws::Text, client.read(msg));
  18685. EXPECT_EQ("hello", msg);
  18686. client.close();
  18687. }
  18688. std::unique_ptr<SSLServer> server_;
  18689. std::thread server_thread_;
  18690. int port_ = 0;
  18691. };
  18692. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  18693. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  18694. }
  18695. // Control for the tests above: the fixture's server really does require a
  18696. // client certificate, so it is the PEM the constructor installed that decides
  18697. // the outcome.
  18698. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  18699. ws::WebSocketClient client(url());
  18700. ASSERT_TRUE(client.is_valid());
  18701. client.enable_server_certificate_verification(false);
  18702. EXPECT_FALSE(client.connect());
  18703. }
  18704. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  18705. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  18706. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  18707. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  18708. }
  18709. #endif
  18710. #if !defined(_WIN32)
  18711. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  18712. auto secret_dir = std::string("./symlink_test_secret");
  18713. auto served_dir = std::string("./symlink_test_served");
  18714. auto secret_file = secret_dir + "/secret.txt";
  18715. auto symlink_path = served_dir + "/escape";
  18716. // Setup: create directories and files
  18717. mkdir(secret_dir.c_str(), 0755);
  18718. mkdir(served_dir.c_str(), 0755);
  18719. {
  18720. std::ofstream ofs(secret_file);
  18721. ofs << "SECRET_DATA";
  18722. }
  18723. // Create symlink using absolute path so it resolves correctly
  18724. #ifdef PATH_MAX
  18725. char abs_secret[PATH_MAX];
  18726. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  18727. #else
  18728. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  18729. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  18730. ASSERT_NE(nullptr, abs_secret);
  18731. #endif
  18732. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  18733. auto se = detail::scope_exit([&] {
  18734. unlink(symlink_path.c_str());
  18735. unlink(secret_file.c_str());
  18736. rmdir(served_dir.c_str());
  18737. rmdir(secret_dir.c_str());
  18738. });
  18739. Server svr;
  18740. svr.set_mount_point("/", served_dir);
  18741. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18742. auto se2 = detail::scope_exit([&] {
  18743. svr.stop();
  18744. listen_thread.join();
  18745. });
  18746. svr.wait_until_ready();
  18747. Client cli("localhost", PORT);
  18748. // Symlink pointing outside base dir should be blocked
  18749. auto res = cli.Get("/escape/secret.txt");
  18750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18751. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18752. }
  18753. #endif
  18754. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  18755. // A GET request with Content-Length to a static file handler must have its
  18756. // body drained before the keep-alive connection is reused. Otherwise the
  18757. // unread body bytes are interpreted as the next HTTP request.
  18758. //
  18759. // The body is sent AFTER receiving the first response (as in the original
  18760. // PoC) so that the stream_line_reader cannot buffer it together with the
  18761. // headers of the first request.
  18762. Server svr;
  18763. svr.set_mount_point("/", "./www");
  18764. std::atomic<int> smuggled_count(0);
  18765. svr.Get("/smuggled", [&](const Request &, Response &res) {
  18766. smuggled_count++;
  18767. res.set_content("oops", "text/plain");
  18768. });
  18769. auto port = svr.bind_to_any_port("localhost");
  18770. thread t = thread([&] { svr.listen_after_bind(); });
  18771. auto se = detail::scope_exit([&] {
  18772. svr.stop();
  18773. t.join();
  18774. });
  18775. svr.wait_until_ready();
  18776. auto error = Error::Success;
  18777. auto sock = detail::create_client_socket(
  18778. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  18779. /*connection_timeout_sec=*/2, 0,
  18780. /*read_timeout_sec=*/2, 0,
  18781. /*write_timeout_sec=*/2, 0, std::string(), error);
  18782. ASSERT_NE(INVALID_SOCKET, sock);
  18783. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18784. // The "smuggled" request will be sent as the body of the outer GET
  18785. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  18786. "Host: localhost\r\n"
  18787. "Connection: close\r\n"
  18788. "\r\n";
  18789. // Step 1: Send only the outer request headers (no body yet)
  18790. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  18791. "Host: localhost\r\n"
  18792. "Content-Length: " +
  18793. std::to_string(smuggled.size()) +
  18794. "\r\n"
  18795. "\r\n";
  18796. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  18797. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  18798. // Step 2: Read the first response (server serves file without reading body)
  18799. std::string first_response;
  18800. char buf[4096];
  18801. for (;;) {
  18802. auto n = recv(sock, buf, sizeof(buf), 0);
  18803. if (n <= 0) break;
  18804. first_response.append(buf, static_cast<size_t>(n));
  18805. // Stop once we have a complete response (headers + body)
  18806. auto hdr_end = first_response.find("\r\n\r\n");
  18807. if (hdr_end != std::string::npos) {
  18808. // Check for Content-Length to know when the body is complete
  18809. auto cl_pos = first_response.find("Content-Length:");
  18810. if (cl_pos != std::string::npos) {
  18811. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  18812. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  18813. auto cl = std::stoul(
  18814. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  18815. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  18816. } else {
  18817. break; // No Content-Length, assume headers-only response
  18818. }
  18819. }
  18820. }
  18821. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  18822. // Step 3: Now send the body, which looks like a new HTTP request.
  18823. // On a vulnerable server the keep-alive loop reads this as a second request.
  18824. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  18825. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  18826. // Step 4: Try to read a second response (should NOT exist after fix)
  18827. std::string second_response;
  18828. for (;;) {
  18829. auto n = recv(sock, buf, sizeof(buf), 0);
  18830. if (n <= 0) break;
  18831. second_response.append(buf, static_cast<size_t>(n));
  18832. }
  18833. // The smuggled request must NOT have been processed
  18834. EXPECT_EQ(0, smuggled_count.load());
  18835. }
  18836. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18837. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  18838. // must be rejected with 400 Bad Request.
  18839. Server svr;
  18840. svr.Post("/test", [&](const Request &, Response &res) {
  18841. res.set_content("ok", "text/plain");
  18842. });
  18843. thread t = thread([&] { svr.listen(HOST, PORT); });
  18844. auto se = detail::scope_exit([&] {
  18845. svr.stop();
  18846. t.join();
  18847. ASSERT_FALSE(svr.is_running());
  18848. });
  18849. svr.wait_until_ready();
  18850. // Exact "chunked"
  18851. {
  18852. auto req = "POST /test HTTP/1.1\r\n"
  18853. "Host: localhost\r\n"
  18854. "Content-Length: 5\r\n"
  18855. "Transfer-Encoding: chunked\r\n"
  18856. "Connection: close\r\n"
  18857. "\r\n"
  18858. "hello";
  18859. std::string response;
  18860. ASSERT_TRUE(send_request(1, req, &response));
  18861. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18862. response.substr(0, response.find("\r\n")));
  18863. }
  18864. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  18865. {
  18866. auto req = "POST /test HTTP/1.1\r\n"
  18867. "Host: localhost\r\n"
  18868. "Content-Length: 5\r\n"
  18869. "Transfer-Encoding: gzip, chunked\r\n"
  18870. "Connection: close\r\n"
  18871. "\r\n"
  18872. "hello";
  18873. std::string response;
  18874. ASSERT_TRUE(send_request(1, req, &response));
  18875. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18876. response.substr(0, response.find("\r\n")));
  18877. }
  18878. }
  18879. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  18880. Server svr;
  18881. svr.Post("/test", [&](const Request &, Response &res) {
  18882. res.set_content("ok", "text/plain");
  18883. });
  18884. thread t = thread([&] { svr.listen(HOST, PORT); });
  18885. auto se = detail::scope_exit([&] {
  18886. svr.stop();
  18887. t.join();
  18888. ASSERT_FALSE(svr.is_running());
  18889. });
  18890. svr.wait_until_ready();
  18891. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  18892. // length cannot be determined, so the server must answer 400 and close
  18893. // rather than treat the request as bodyless and leave the body in the
  18894. // socket for the next request to pick up.
  18895. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  18896. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  18897. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  18898. std::string response;
  18899. ASSERT_TRUE(send_request(1, req, &response));
  18900. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18901. response.substr(0, response.find("\r\n")))
  18902. << transfer_encoding;
  18903. }
  18904. // RFC 9110 5.3: the codings may also be split across several
  18905. // Transfer-Encoding lines, which combine in the order they were received.
  18906. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  18907. // just like the single-line "chunked, gzip" above.
  18908. {
  18909. auto req = "POST /test HTTP/1.1\r\n"
  18910. "Host: localhost\r\n"
  18911. "Transfer-Encoding: chunked\r\n"
  18912. "Transfer-Encoding: gzip\r\n"
  18913. "\r\n"
  18914. "0\r\n\r\n";
  18915. std::string response;
  18916. ASSERT_TRUE(send_request(1, req, &response));
  18917. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18918. response.substr(0, response.find("\r\n")));
  18919. }
  18920. // A sequence ending in chunked stays valid.
  18921. auto req = "POST /test HTTP/1.1\r\n"
  18922. "Host: localhost\r\n"
  18923. "Transfer-Encoding: gzip, chunked\r\n"
  18924. "Connection: close\r\n"
  18925. "\r\n"
  18926. "0\r\n\r\n";
  18927. std::string response;
  18928. ASSERT_TRUE(send_request(1, req, &response));
  18929. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18930. // ...including when it is spread over several lines.
  18931. auto split_req = "POST /test HTTP/1.1\r\n"
  18932. "Host: localhost\r\n"
  18933. "Transfer-Encoding: gzip\r\n"
  18934. "Transfer-Encoding: chunked\r\n"
  18935. "Connection: close\r\n"
  18936. "\r\n"
  18937. "0\r\n\r\n";
  18938. std::string split_response;
  18939. ASSERT_TRUE(send_request(1, split_req, &split_response));
  18940. EXPECT_EQ("HTTP/1.1 200 OK",
  18941. split_response.substr(0, split_response.find("\r\n")));
  18942. }
  18943. // Regression for issue #2450: a DELETE without Content-Length on a
  18944. // keep-alive connection must not let the post-response drain consume the
  18945. // next request's bytes.
  18946. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  18947. Server svr;
  18948. std::atomic<int> delete_count(0);
  18949. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  18950. delete_count++;
  18951. res.status = StatusCode::NoContent_204;
  18952. });
  18953. auto port = svr.bind_to_any_port(HOST);
  18954. thread t = thread([&] { svr.listen_after_bind(); });
  18955. auto se = detail::scope_exit([&] {
  18956. svr.stop();
  18957. t.join();
  18958. });
  18959. svr.wait_until_ready();
  18960. auto error = Error::Success;
  18961. auto sock = detail::create_client_socket(
  18962. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18963. /*connection_timeout_sec=*/2, 0,
  18964. /*read_timeout_sec=*/2, 0,
  18965. /*write_timeout_sec=*/2, 0, std::string(), error);
  18966. ASSERT_NE(INVALID_SOCKET, sock);
  18967. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18968. auto send_request_and_read_response = [&](const std::string &req,
  18969. std::string &out) -> bool {
  18970. auto sent = send(sock, req.data(), req.size(), 0);
  18971. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  18972. char buf[4096];
  18973. for (;;) {
  18974. auto n = recv(sock, buf, sizeof(buf), 0);
  18975. if (n <= 0) { return !out.empty(); }
  18976. out.append(buf, static_cast<size_t>(n));
  18977. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  18978. }
  18979. };
  18980. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  18981. "Host: localhost\r\n"
  18982. "\r\n";
  18983. std::string resp1;
  18984. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  18985. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  18986. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  18987. "Host: localhost\r\n"
  18988. "Connection: close\r\n"
  18989. "\r\n";
  18990. std::string resp2;
  18991. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  18992. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  18993. EXPECT_EQ(2, delete_count.load());
  18994. }
  18995. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  18996. Server svr;
  18997. svr.Post("/ingest", [&](const Request &, Response &res,
  18998. const ContentReader &content_reader) {
  18999. auto consumed = content_reader([](const char *, size_t) { return false; });
  19000. EXPECT_FALSE(consumed);
  19001. res.status = StatusCode::Conflict_409;
  19002. res.set_header("Connection", "close");
  19003. });
  19004. auto port = svr.bind_to_any_port(HOST);
  19005. thread t = thread([&] { svr.listen_after_bind(); });
  19006. auto se = detail::scope_exit([&] {
  19007. svr.stop();
  19008. t.join();
  19009. });
  19010. svr.wait_until_ready();
  19011. auto error = Error::Success;
  19012. auto sock = detail::create_client_socket(
  19013. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19014. /*connection_timeout_sec=*/2, 0,
  19015. /*read_timeout_sec=*/1, 0,
  19016. /*write_timeout_sec=*/2, 0, std::string(), error);
  19017. ASSERT_NE(INVALID_SOCKET, sock);
  19018. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  19019. std::string request = "POST /ingest HTTP/1.1\r\n"
  19020. "Host: localhost\r\n"
  19021. "Transfer-Encoding: chunked\r\n"
  19022. "\r\n"
  19023. "4\r\n"
  19024. "data\r\n";
  19025. auto sent = send(sock, request.data(), request.size(), 0);
  19026. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  19027. std::string response;
  19028. ssize_t received = 0;
  19029. do {
  19030. char buf[4096];
  19031. received = recv(sock, buf, sizeof(buf), 0);
  19032. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  19033. } while (received > 0);
  19034. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  19035. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  19036. EXPECT_EQ(0, received);
  19037. }
  19038. namespace no_proxy_test {
  19039. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  19040. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  19041. // calling listen().
  19042. class ScopedServer {
  19043. public:
  19044. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  19045. ~ScopedServer() {
  19046. svr_.stop();
  19047. if (th_.joinable()) { th_.join(); }
  19048. }
  19049. Server &svr() { return svr_; }
  19050. int port() const { return port_; }
  19051. void listen() {
  19052. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19053. svr_.wait_until_ready();
  19054. }
  19055. private:
  19056. Server svr_;
  19057. std::thread th_;
  19058. int port_ = 0;
  19059. };
  19060. class ProxyAndTargetServers {
  19061. public:
  19062. ProxyAndTargetServers() {
  19063. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  19064. proxy_hits_++;
  19065. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19066. res.set_content("via-proxy", "text/plain");
  19067. });
  19068. target_.Get(".*", [this](const Request &req, Response &res) {
  19069. target_hits_++;
  19070. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  19071. res.set_content("direct", "text/plain");
  19072. });
  19073. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  19074. target_port_ = target_.bind_to_any_port("127.0.0.1");
  19075. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  19076. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  19077. proxy_mock_.wait_until_ready();
  19078. target_.wait_until_ready();
  19079. }
  19080. ~ProxyAndTargetServers() {
  19081. proxy_mock_.stop();
  19082. target_.stop();
  19083. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  19084. if (target_thread_.joinable()) { target_thread_.join(); }
  19085. }
  19086. Server &proxy_mock() { return proxy_mock_; }
  19087. Server &target() { return target_; }
  19088. int proxy_port() const { return proxy_port_; }
  19089. int target_port() const { return target_port_; }
  19090. int proxy_hits() const { return proxy_hits_.load(); }
  19091. int target_hits() const { return target_hits_.load(); }
  19092. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  19093. void reset_counters() {
  19094. proxy_hits_ = 0;
  19095. target_hits_ = 0;
  19096. last_had_proxy_authz_ = false;
  19097. }
  19098. private:
  19099. Server proxy_mock_;
  19100. Server target_;
  19101. std::thread proxy_thread_;
  19102. std::thread target_thread_;
  19103. int proxy_port_ = 0;
  19104. int target_port_ = 0;
  19105. std::atomic<int> proxy_hits_{0};
  19106. std::atomic<int> target_hits_{0};
  19107. std::atomic<bool> last_had_proxy_authz_{false};
  19108. };
  19109. inline std::unique_ptr<Client> make_client(const std::string &host,
  19110. ProxyAndTargetServers &s) {
  19111. auto cli = detail::make_unique<Client>(host, s.target_port());
  19112. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  19113. cli->set_proxy("127.0.0.1", s.proxy_port());
  19114. return cli;
  19115. }
  19116. } // namespace no_proxy_test
  19117. using no_proxy_test::make_client;
  19118. using no_proxy_test::ProxyAndTargetServers;
  19119. TEST(NoProxyTest, ExactHostnameBypasses) {
  19120. ProxyAndTargetServers s;
  19121. auto cli = make_client("example.com", s);
  19122. cli->set_no_proxy({"example.com"});
  19123. auto res = cli->Get("/");
  19124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19125. EXPECT_EQ(0, s.proxy_hits());
  19126. EXPECT_EQ(1, s.target_hits());
  19127. }
  19128. TEST(NoProxyTest, SubdomainBypasses) {
  19129. ProxyAndTargetServers s;
  19130. auto cli = make_client("foo.example.com", s);
  19131. cli->set_no_proxy({"example.com"});
  19132. auto res = cli->Get("/");
  19133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19134. EXPECT_EQ(0, s.proxy_hits());
  19135. EXPECT_EQ(1, s.target_hits());
  19136. }
  19137. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  19138. // Regression guard: "evilexample.com" must not be considered a subdomain
  19139. // of "example.com". Without the dot-boundary rule, a naive endsWith
  19140. // check would let traffic bypass the proxy and leak credentials direct
  19141. // to the attacker host.
  19142. ProxyAndTargetServers s;
  19143. auto cli = make_client("evilexample.com", s);
  19144. cli->set_no_proxy({"example.com"});
  19145. auto res = cli->Get("/");
  19146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19147. EXPECT_GE(s.proxy_hits(), 1);
  19148. EXPECT_EQ(0, s.target_hits());
  19149. }
  19150. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  19151. ProxyAndTargetServers s;
  19152. auto cli = make_client("example.com.evil.com", s);
  19153. cli->set_no_proxy({"example.com"});
  19154. auto res = cli->Get("/");
  19155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19156. EXPECT_GE(s.proxy_hits(), 1);
  19157. EXPECT_EQ(0, s.target_hits());
  19158. }
  19159. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  19160. ProxyAndTargetServers s;
  19161. auto cli = make_client("example.com", s);
  19162. cli->set_no_proxy({".example.com"});
  19163. auto res = cli->Get("/");
  19164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19165. EXPECT_EQ(0, s.proxy_hits());
  19166. EXPECT_EQ(1, s.target_hits());
  19167. }
  19168. TEST(NoProxyTest, CaseInsensitiveHostname) {
  19169. ProxyAndTargetServers s;
  19170. auto cli = make_client("Example.COM", s);
  19171. cli->set_no_proxy({"EXAMPLE.com"});
  19172. auto res = cli->Get("/");
  19173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19174. EXPECT_EQ(0, s.proxy_hits());
  19175. EXPECT_EQ(1, s.target_hits());
  19176. }
  19177. TEST(NoProxyTest, TrailingDotIsNormalized) {
  19178. ProxyAndTargetServers s;
  19179. auto cli = make_client("example.com.", s);
  19180. cli->set_no_proxy({"example.com"});
  19181. auto res = cli->Get("/");
  19182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19183. EXPECT_EQ(0, s.proxy_hits());
  19184. EXPECT_EQ(1, s.target_hits());
  19185. }
  19186. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  19187. // Trailing dots must be normalized on BOTH sides — host and entry.
  19188. // An implementation that only strips the host-side trailing dot would
  19189. // fail to match host "example.com" against entry "example.com." because
  19190. // a literal substring search would compare 11 chars against 12.
  19191. ProxyAndTargetServers s;
  19192. auto cli = make_client("example.com", s);
  19193. cli->set_no_proxy({"example.com."});
  19194. auto res = cli->Get("/");
  19195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19196. EXPECT_EQ(0, s.proxy_hits());
  19197. EXPECT_EQ(1, s.target_hits());
  19198. }
  19199. TEST(NoProxyTest, WildcardBypassesEverything) {
  19200. ProxyAndTargetServers s;
  19201. auto cli = make_client("anything.invalid.test", s);
  19202. cli->set_no_proxy({"*"});
  19203. auto res = cli->Get("/");
  19204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19205. EXPECT_EQ(0, s.proxy_hits());
  19206. EXPECT_EQ(1, s.target_hits());
  19207. }
  19208. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  19209. ProxyAndTargetServers s;
  19210. Client cli("127.0.0.1", s.target_port());
  19211. cli.set_proxy("127.0.0.1", s.proxy_port());
  19212. cli.set_no_proxy({"127.0.0.1"});
  19213. auto res = cli.Get("/");
  19214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19215. EXPECT_EQ(0, s.proxy_hits());
  19216. EXPECT_EQ(1, s.target_hits());
  19217. }
  19218. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  19219. ProxyAndTargetServers s;
  19220. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  19221. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  19222. cli.set_proxy("127.0.0.1", s.proxy_port());
  19223. cli.set_no_proxy({"::1"});
  19224. auto res = cli.Get("/");
  19225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19226. EXPECT_EQ(0, s.proxy_hits());
  19227. EXPECT_EQ(1, s.target_hits());
  19228. }
  19229. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  19230. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  19231. // must still be recognized as IPv6 for CIDR matching. Implementations
  19232. // that detect IPv6 only when the host begins with '[' would parse the
  19233. // host as a hostname and miss the match.
  19234. ProxyAndTargetServers s;
  19235. Client cli("fe80::1", s.target_port());
  19236. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19237. cli.set_proxy("127.0.0.1", s.proxy_port());
  19238. cli.set_no_proxy({"fe80::/10"});
  19239. auto res = cli.Get("/");
  19240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19241. EXPECT_EQ(0, s.proxy_hits());
  19242. EXPECT_EQ(1, s.target_hits());
  19243. }
  19244. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  19245. ProxyAndTargetServers s;
  19246. Client cli("::1", s.target_port());
  19247. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  19248. cli.set_proxy("127.0.0.1", s.proxy_port());
  19249. cli.set_no_proxy({"[::1]"});
  19250. auto res = cli.Get("/");
  19251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19252. EXPECT_EQ(0, s.proxy_hits());
  19253. EXPECT_EQ(1, s.target_hits());
  19254. }
  19255. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  19256. ProxyAndTargetServers s;
  19257. Client cli("fe80::1", s.target_port());
  19258. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  19259. cli.set_proxy("127.0.0.1", s.proxy_port());
  19260. cli.set_no_proxy({"[fe80::]/10"});
  19261. auto res = cli.Get("/");
  19262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19263. EXPECT_EQ(0, s.proxy_hits());
  19264. EXPECT_EQ(1, s.target_hits());
  19265. }
  19266. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  19267. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  19268. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  19269. // tricks via address-family conversion.
  19270. ProxyAndTargetServers s;
  19271. Client cli("::ffff:127.0.0.1", s.target_port());
  19272. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  19273. cli.set_proxy("127.0.0.1", s.proxy_port());
  19274. cli.set_no_proxy({"127.0.0.1"});
  19275. auto res = cli.Get("/");
  19276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19277. EXPECT_GE(s.proxy_hits(), 1);
  19278. EXPECT_EQ(0, s.target_hits());
  19279. }
  19280. TEST(NoProxyTest, IPv4CidrMatch) {
  19281. ProxyAndTargetServers s;
  19282. Client cli("127.0.0.1", s.target_port());
  19283. cli.set_proxy("127.0.0.1", s.proxy_port());
  19284. cli.set_no_proxy({"127.0.0.0/8"});
  19285. auto res = cli.Get("/");
  19286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19287. EXPECT_EQ(0, s.proxy_hits());
  19288. EXPECT_EQ(1, s.target_hits());
  19289. }
  19290. TEST(NoProxyTest, IPv4CidrNonMatch) {
  19291. ProxyAndTargetServers s;
  19292. Client cli("127.0.0.1", s.target_port());
  19293. cli.set_proxy("127.0.0.1", s.proxy_port());
  19294. cli.set_no_proxy({"10.0.0.0/8"});
  19295. auto res = cli.Get("/");
  19296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19297. EXPECT_GE(s.proxy_hits(), 1);
  19298. EXPECT_EQ(0, s.target_hits());
  19299. }
  19300. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  19301. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  19302. // IPv4 target matches.
  19303. ProxyAndTargetServers s;
  19304. Client cli("127.0.0.1", s.target_port());
  19305. cli.set_proxy("127.0.0.1", s.proxy_port());
  19306. cli.set_no_proxy({"0.0.0.0/0"});
  19307. auto res = cli.Get("/");
  19308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19309. EXPECT_EQ(0, s.proxy_hits());
  19310. EXPECT_EQ(1, s.target_hits());
  19311. }
  19312. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  19313. ProxyAndTargetServers s;
  19314. Client cli("127.0.0.1", s.target_port());
  19315. cli.set_proxy("127.0.0.1", s.proxy_port());
  19316. cli.set_no_proxy({"127.0.0.1"});
  19317. auto res = cli.Get("/");
  19318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19319. EXPECT_EQ(0, s.proxy_hits());
  19320. EXPECT_EQ(1, s.target_hits());
  19321. }
  19322. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  19323. ProxyAndTargetServers s;
  19324. Client cli("127.0.0.1", s.target_port());
  19325. cli.set_proxy("127.0.0.1", s.proxy_port());
  19326. cli.set_no_proxy({"127.0.0.0/33"});
  19327. auto res = cli.Get("/");
  19328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19329. EXPECT_GE(s.proxy_hits(), 1);
  19330. EXPECT_EQ(0, s.target_hits());
  19331. }
  19332. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  19333. // Empty prefix after the slash must be rejected, not silently treated as /32.
  19334. ProxyAndTargetServers s;
  19335. Client cli("127.0.0.1", s.target_port());
  19336. cli.set_proxy("127.0.0.1", s.proxy_port());
  19337. cli.set_no_proxy({"127.0.0.1/"});
  19338. auto res = cli.Get("/");
  19339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19340. EXPECT_GE(s.proxy_hits(), 1);
  19341. EXPECT_EQ(0, s.target_hits());
  19342. }
  19343. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  19344. ProxyAndTargetServers s;
  19345. auto cli = make_client("internal.corp", s);
  19346. cli->set_proxy_basic_auth("u", "p");
  19347. cli->set_no_proxy({"internal.corp"});
  19348. auto res = cli->Get("/");
  19349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19350. EXPECT_EQ(1, s.target_hits());
  19351. EXPECT_EQ(0, s.proxy_hits());
  19352. EXPECT_FALSE(s.last_had_proxy_authz())
  19353. << "Proxy-Authorization must not be sent direct to the target";
  19354. }
  19355. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  19356. ProxyAndTargetServers s;
  19357. auto cli = make_client("public.example", s);
  19358. cli->set_proxy_basic_auth("u", "p");
  19359. cli->set_no_proxy({"internal.corp"}); // does not match
  19360. auto res = cli->Get("/");
  19361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19362. EXPECT_GE(s.proxy_hits(), 1);
  19363. EXPECT_TRUE(s.last_had_proxy_authz());
  19364. }
  19365. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  19366. ProxyAndTargetServers s;
  19367. auto cli = make_client("anything.test", s);
  19368. auto res = cli->Get("/");
  19369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19370. EXPECT_GE(s.proxy_hits(), 1);
  19371. EXPECT_EQ(0, s.target_hits());
  19372. }
  19373. TEST(NoProxyTest, PortSpecificEntryRejected) {
  19374. ProxyAndTargetServers s;
  19375. auto cli = make_client("example.com", s);
  19376. cli->set_no_proxy({"example.com:8080"});
  19377. auto res = cli->Get("/");
  19378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19379. EXPECT_GE(s.proxy_hits(), 1);
  19380. EXPECT_EQ(0, s.target_hits());
  19381. }
  19382. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  19383. ProxyAndTargetServers s;
  19384. auto cli = make_client("anything.test", s);
  19385. cli->set_no_proxy({"", " ", "\t"});
  19386. auto res = cli->Get("/");
  19387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19388. EXPECT_GE(s.proxy_hits(), 1);
  19389. EXPECT_EQ(0, s.target_hits());
  19390. }
  19391. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  19392. // An entry with leading/trailing whitespace must still match — env-style
  19393. // values are commonly pasted with stray spaces and an implementation
  19394. // that feeds the raw token directly to inet_pton would fail to match
  19395. // valid CIDRs because of the spaces.
  19396. ProxyAndTargetServers s;
  19397. Client cli("127.0.0.1", s.target_port());
  19398. cli.set_proxy("127.0.0.1", s.proxy_port());
  19399. cli.set_no_proxy({" 127.0.0.0/8 "});
  19400. auto res = cli.Get("/");
  19401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19402. EXPECT_EQ(0, s.proxy_hits());
  19403. EXPECT_EQ(1, s.target_hits());
  19404. }
  19405. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  19406. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  19407. // go direct and must NOT carry Proxy-Authorization.
  19408. std::atomic<int> proxy_hits{0};
  19409. std::atomic<int> target_hits{0};
  19410. std::atomic<bool> target_saw_authz{false};
  19411. no_proxy_test::ScopedServer proxy_mock, target;
  19412. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19413. proxy_hits++;
  19414. res.status = 302;
  19415. res.set_header("Location", "http://127.0.0.1:" +
  19416. std::to_string(target.port()) + "/landed");
  19417. });
  19418. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19419. target_hits++;
  19420. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  19421. res.set_content("direct", "text/plain");
  19422. });
  19423. proxy_mock.listen();
  19424. target.listen();
  19425. Client cli("public.example", target.port());
  19426. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19427. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19428. cli.set_proxy_basic_auth("u", "p");
  19429. cli.set_no_proxy({"127.0.0.1"});
  19430. cli.set_follow_location(true);
  19431. auto res = cli.Get("/redir");
  19432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19433. EXPECT_GE(proxy_hits.load(), 1);
  19434. EXPECT_GE(target_hits.load(), 1);
  19435. EXPECT_FALSE(target_saw_authz.load());
  19436. }
  19437. #ifdef CPPHTTPLIB_SSL_ENABLED
  19438. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  19439. // Direct origin replying 407 must not trigger the digest retry; otherwise
  19440. // proxy creds would be sent to the (possibly hostile) origin.
  19441. std::atomic<int> target_hits{0};
  19442. std::atomic<bool> target_saw_proxy_authz{false};
  19443. no_proxy_test::ScopedServer target;
  19444. target.svr().Get(".*", [&](const Request &req, Response &res) {
  19445. target_hits++;
  19446. if (req.has_header("Proxy-Authorization")) {
  19447. target_saw_proxy_authz = true;
  19448. }
  19449. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19450. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  19451. "nonce=\"abc\", algorithm=MD5");
  19452. });
  19453. target.listen();
  19454. // The proxy address is set to the target's port: the bypass MUST kick in;
  19455. // if it doesn't, the test still routes "via proxy" to the same server and
  19456. // the Proxy-Authorization assertion below catches the leak.
  19457. Client cli("evil.example", target.port());
  19458. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  19459. cli.set_proxy("127.0.0.1", target.port());
  19460. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19461. cli.set_no_proxy({"evil.example"});
  19462. auto res = cli.Get("/x");
  19463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19464. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19465. EXPECT_EQ(1, target_hits.load());
  19466. EXPECT_FALSE(target_saw_proxy_authz.load());
  19467. }
  19468. #endif
  19469. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  19470. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  19471. std::atomic<int> proxy_hits{0};
  19472. std::atomic<int> bypass_hits{0};
  19473. std::atomic<bool> proxy_saw_c_url{false};
  19474. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  19475. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  19476. proxy_hits++;
  19477. if (req.path.find("/start") != std::string::npos) {
  19478. res.status = 302;
  19479. res.set_header("Location", "http://127.0.0.1:" +
  19480. std::to_string(bypass_server.port()) +
  19481. "/middle");
  19482. return;
  19483. }
  19484. if (req.path.find("/end") != std::string::npos) {
  19485. proxy_saw_c_url = true;
  19486. res.set_content("c-via-proxy", "text/plain");
  19487. return;
  19488. }
  19489. res.set_content("unexpected", "text/plain");
  19490. });
  19491. // public.example's "advertised" port is arbitrary (the request never lands
  19492. // there — it goes through the proxy), but use a dynamic value to stay
  19493. // friendly with sharded parallel runs.
  19494. int public_port = bypass_server.port();
  19495. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  19496. bypass_hits++;
  19497. res.status = 302;
  19498. res.set_header("Location", "http://public.example:" +
  19499. std::to_string(public_port) + "/end");
  19500. });
  19501. proxy_mock.listen();
  19502. bypass_server.listen();
  19503. Client cli("public.example", public_port);
  19504. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19505. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19506. cli.set_no_proxy({"127.0.0.1"});
  19507. cli.set_follow_location(true);
  19508. auto res = cli.Get("/start");
  19509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19510. EXPECT_EQ(StatusCode::OK_200, res->status);
  19511. EXPECT_EQ("c-via-proxy", res->body);
  19512. EXPECT_GE(proxy_hits.load(), 2);
  19513. EXPECT_GE(bypass_hits.load(), 1);
  19514. EXPECT_TRUE(proxy_saw_c_url.load());
  19515. }
  19516. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  19517. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  19518. // request reconnects to the correct endpoint.
  19519. std::atomic<int> proxy_hits{0};
  19520. std::atomic<int> target_hits{0};
  19521. no_proxy_test::ScopedServer proxy_mock, target;
  19522. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  19523. proxy_hits++;
  19524. res.set_content("via-proxy", "text/plain");
  19525. });
  19526. target.svr().Get(".*", [&](const Request &, Response &res) {
  19527. target_hits++;
  19528. res.set_content("direct", "text/plain");
  19529. });
  19530. proxy_mock.listen();
  19531. target.listen();
  19532. Client cli("public.example", target.port());
  19533. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  19534. cli.set_proxy("127.0.0.1", proxy_mock.port());
  19535. cli.set_keep_alive(true);
  19536. auto res1 = cli.Get("/a");
  19537. ASSERT_TRUE(res1);
  19538. EXPECT_EQ("via-proxy", res1->body);
  19539. EXPECT_EQ(1, proxy_hits.load());
  19540. EXPECT_EQ(0, target_hits.load());
  19541. cli.set_no_proxy({"public.example"});
  19542. auto res2 = cli.Get("/b");
  19543. ASSERT_TRUE(res2);
  19544. EXPECT_EQ("direct", res2->body);
  19545. EXPECT_EQ(1, proxy_hits.load());
  19546. EXPECT_EQ(1, target_hits.load());
  19547. }
  19548. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  19549. namespace proxy_tunnel_test {
  19550. // SSLServer counterpart to no_proxy_test::ScopedServer.
  19551. class ScopedSSLServer {
  19552. public:
  19553. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  19554. port_ = svr_.bind_to_any_port("127.0.0.1");
  19555. }
  19556. ~ScopedSSLServer() {
  19557. svr_.stop();
  19558. if (th_.joinable()) { th_.join(); }
  19559. }
  19560. SSLServer &svr() { return svr_; }
  19561. int port() const { return port_; }
  19562. void listen() {
  19563. th_ = std::thread([this] { svr_.listen_after_bind(); });
  19564. svr_.wait_until_ready();
  19565. }
  19566. private:
  19567. SSLServer svr_;
  19568. std::thread th_;
  19569. int port_ = 0;
  19570. };
  19571. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  19572. class ScopedConnectProxy {
  19573. public:
  19574. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  19575. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  19576. if (listen_fd_ < 0) { return; }
  19577. int yes = 1;
  19578. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  19579. sockaddr_in a{};
  19580. a.sin_family = AF_INET;
  19581. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19582. a.sin_port = 0;
  19583. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  19584. return;
  19585. }
  19586. socklen_t alen = sizeof(a);
  19587. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  19588. 0) {
  19589. return;
  19590. }
  19591. port_ = ntohs(a.sin_port);
  19592. if (::listen(listen_fd_, 1) != 0) { return; }
  19593. th_ = std::thread([this] { run(); });
  19594. }
  19595. ~ScopedConnectProxy() {
  19596. stop_ = true;
  19597. if (listen_fd_ >= 0) {
  19598. ::shutdown(listen_fd_, SHUT_RDWR);
  19599. ::close(listen_fd_);
  19600. }
  19601. if (th_.joinable()) { th_.join(); }
  19602. }
  19603. int port() const { return port_; }
  19604. int connect_hits() const { return connect_hits_.load(); }
  19605. private:
  19606. void run() {
  19607. while (!stop_.load()) {
  19608. fd_set rfds;
  19609. FD_ZERO(&rfds);
  19610. FD_SET(listen_fd_, &rfds);
  19611. timeval tv{0, 100 * 1000};
  19612. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  19613. if (sel <= 0) { continue; }
  19614. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  19615. if (client_fd < 0) { continue; }
  19616. std::string req;
  19617. char buf[2048];
  19618. while (req.find("\r\n\r\n") == std::string::npos) {
  19619. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  19620. if (n <= 0) { break; }
  19621. req.append(buf, static_cast<size_t>(n));
  19622. }
  19623. if (req.compare(0, 7, "CONNECT") != 0) {
  19624. ::close(client_fd);
  19625. continue;
  19626. }
  19627. connect_hits_++;
  19628. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  19629. ::send(client_fd, ok, std::strlen(ok), 0);
  19630. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  19631. sockaddr_in o{};
  19632. o.sin_family = AF_INET;
  19633. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  19634. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  19635. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  19636. 0) {
  19637. ::close(client_fd);
  19638. ::close(origin_fd);
  19639. continue;
  19640. }
  19641. auto forward = [](int from, int to) {
  19642. char b[8192];
  19643. for (;;) {
  19644. ssize_t n = ::recv(from, b, sizeof(b), 0);
  19645. if (n <= 0) { break; }
  19646. ssize_t off = 0;
  19647. while (off < n) {
  19648. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  19649. if (s <= 0) {
  19650. off = n;
  19651. break;
  19652. }
  19653. off += s;
  19654. }
  19655. }
  19656. ::shutdown(to, SHUT_WR);
  19657. };
  19658. std::thread t1([&] { forward(client_fd, origin_fd); });
  19659. std::thread t2([&] { forward(origin_fd, client_fd); });
  19660. t1.join();
  19661. t2.join();
  19662. ::close(client_fd);
  19663. ::close(origin_fd);
  19664. }
  19665. }
  19666. int forward_port_ = -1;
  19667. int listen_fd_ = -1;
  19668. int port_ = 0;
  19669. std::thread th_;
  19670. std::atomic<bool> stop_{false};
  19671. std::atomic<int> connect_hits_{0};
  19672. };
  19673. } // namespace proxy_tunnel_test
  19674. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  19675. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  19676. // retry; otherwise proxy creds would be sent to the origin.
  19677. std::atomic<int> origin_hits{0};
  19678. std::atomic<bool> origin_saw_proxy_authz{false};
  19679. proxy_tunnel_test::ScopedSSLServer origin;
  19680. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  19681. origin_hits++;
  19682. if (req.has_header("Proxy-Authorization")) {
  19683. origin_saw_proxy_authz = true;
  19684. }
  19685. res.status = StatusCode::ProxyAuthenticationRequired_407;
  19686. res.set_header("Proxy-Authenticate",
  19687. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  19688. "algorithm=MD5");
  19689. });
  19690. origin.listen();
  19691. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  19692. ASSERT_NE(0, proxy.port());
  19693. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  19694. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  19695. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  19696. // and answer with its own status, making this test flaky.
  19697. SSLClient cli("127.0.0.1", origin.port());
  19698. cli.enable_server_certificate_verification(false);
  19699. cli.set_proxy("127.0.0.1", proxy.port());
  19700. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  19701. auto res = cli.Get("/x");
  19702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19703. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19704. EXPECT_EQ(1, origin_hits.load());
  19705. EXPECT_FALSE(origin_saw_proxy_authz.load());
  19706. EXPECT_EQ(1, proxy.connect_hits());
  19707. }
  19708. #endif