test.cc 725 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702
  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(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1358. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1359. // to depend on the standard library (libstdc++ handed back duplicates in
  1360. // reverse insertion order, libc++ in insertion order).
  1361. Request req;
  1362. req.set_header("Accept-Encoding", "gzip");
  1363. req.set_header("Accept-Encoding", "deflate");
  1364. req.set_header("Accept-Encoding", "br");
  1365. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1366. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1367. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1368. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1369. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1370. }
  1371. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1372. Request req;
  1373. req.set_header("X-Test", "only");
  1374. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1375. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1376. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1377. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1378. }
  1379. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1380. Headers headers;
  1381. headers.emplace("Host", "example.com");
  1382. headers.emplace("Accept-Encoding", "gzip");
  1383. headers.emplace("User-Agent", "test");
  1384. headers.emplace("Accept-Encoding", "deflate");
  1385. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1386. "Accept-Encoding=deflate ",
  1387. entries_to_string(headers));
  1388. }
  1389. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1390. Headers headers = {{"Content-Type", "text/html"},
  1391. {"CONTENT-TYPE", "text/xml"}};
  1392. EXPECT_EQ(2U, headers.count("content-type"));
  1393. auto it = headers.find("content-type");
  1394. ASSERT_TRUE(it != headers.end());
  1395. EXPECT_EQ("text/html", it->second);
  1396. }
  1397. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1398. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1399. // drop only those fields and leave everything positioned between them.
  1400. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1401. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1402. auto rng = headers.equal_range("a");
  1403. headers.erase(rng.first, rng.second);
  1404. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1405. }
  1406. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1407. Headers headers = {
  1408. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1409. EXPECT_EQ(3U, headers.erase("A"));
  1410. EXPECT_EQ(0U, headers.count("A"));
  1411. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1412. }
  1413. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1414. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1415. headers.emplace_front("Host", "example.com");
  1416. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1417. entries_to_string(headers));
  1418. }
  1419. TEST(ParseHeaderValueTest, Range) {
  1420. {
  1421. Ranges ranges;
  1422. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1423. EXPECT_TRUE(ret);
  1424. EXPECT_EQ(1u, ranges.size());
  1425. EXPECT_EQ(1u, ranges[0].first);
  1426. EXPECT_EQ(-1, ranges[0].second);
  1427. }
  1428. {
  1429. Ranges ranges;
  1430. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1431. EXPECT_TRUE(ret);
  1432. EXPECT_EQ(1u, ranges.size());
  1433. EXPECT_EQ(-1, ranges[0].first);
  1434. EXPECT_EQ(1u, ranges[0].second);
  1435. }
  1436. {
  1437. Ranges ranges;
  1438. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1439. EXPECT_TRUE(ret);
  1440. EXPECT_EQ(1u, ranges.size());
  1441. EXPECT_EQ(1u, ranges[0].first);
  1442. EXPECT_EQ(10u, ranges[0].second);
  1443. }
  1444. {
  1445. Ranges ranges;
  1446. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1447. EXPECT_FALSE(ret);
  1448. }
  1449. {
  1450. Ranges ranges;
  1451. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1452. EXPECT_TRUE(ret);
  1453. EXPECT_EQ(2u, ranges.size());
  1454. EXPECT_EQ(1u, ranges[0].first);
  1455. EXPECT_EQ(10u, ranges[0].second);
  1456. EXPECT_EQ(100u, ranges[1].first);
  1457. EXPECT_EQ(-1, ranges[1].second);
  1458. }
  1459. {
  1460. Ranges ranges;
  1461. auto ret =
  1462. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1463. EXPECT_TRUE(ret);
  1464. EXPECT_EQ(3u, ranges.size());
  1465. EXPECT_EQ(1u, ranges[0].first);
  1466. EXPECT_EQ(10u, ranges[0].second);
  1467. EXPECT_EQ(100u, ranges[1].first);
  1468. EXPECT_EQ(200u, ranges[1].second);
  1469. EXPECT_EQ(300u, ranges[2].first);
  1470. EXPECT_EQ(400u, ranges[2].second);
  1471. }
  1472. {
  1473. Ranges ranges;
  1474. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1475. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1476. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1477. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1478. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1479. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1480. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1481. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1482. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1483. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1484. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1485. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1486. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1487. EXPECT_TRUE(ranges.empty());
  1488. }
  1489. }
  1490. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1491. Request req;
  1492. req.set_header("Accept-Encoding", "gzip");
  1493. Response res;
  1494. res.set_header("Content-Type", "text/plain");
  1495. auto ret = detail::encoding_type(req, res);
  1496. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1497. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1498. #else
  1499. EXPECT_TRUE(ret == detail::EncodingType::None);
  1500. #endif
  1501. }
  1502. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1503. Request req;
  1504. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1505. Response res;
  1506. res.set_header("Content-Type", "text/plain");
  1507. auto ret = detail::encoding_type(req, res);
  1508. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1509. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1510. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1511. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1512. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1513. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1514. #else
  1515. EXPECT_TRUE(ret == detail::EncodingType::None);
  1516. #endif
  1517. }
  1518. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1519. Request req;
  1520. req.set_header("Accept-Encoding",
  1521. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1522. Response res;
  1523. res.set_header("Content-Type", "text/plain");
  1524. auto ret = detail::encoding_type(req, res);
  1525. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1526. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1527. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1528. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1529. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1530. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1531. #else
  1532. EXPECT_TRUE(ret == detail::EncodingType::None);
  1533. #endif
  1534. }
  1535. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1536. // All supported encodings rejected with q=0 should return None
  1537. Request req;
  1538. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1539. Response res;
  1540. res.set_header("Content-Type", "text/plain");
  1541. auto ret = detail::encoding_type(req, res);
  1542. EXPECT_TRUE(ret == detail::EncodingType::None);
  1543. }
  1544. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1545. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1546. Request req;
  1547. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1548. Response res;
  1549. res.set_header("Content-Type", "text/plain");
  1550. auto ret = detail::encoding_type(req, res);
  1551. EXPECT_TRUE(ret == detail::EncodingType::None);
  1552. }
  1553. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1554. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1555. Request req;
  1556. req.set_header("Accept-Encoding", "x-gzip;q=0");
  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(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1563. // RFC 7231: Accept-Encoding values are case-insensitive
  1564. Request req;
  1565. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1566. Response res;
  1567. res.set_header("Content-Type", "text/plain");
  1568. auto ret = detail::encoding_type(req, res);
  1569. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1570. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1571. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1572. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1573. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1574. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1575. #else
  1576. EXPECT_TRUE(ret == detail::EncodingType::None);
  1577. #endif
  1578. }
  1579. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1580. // q value should determine priority, not hardcoded order
  1581. Request req;
  1582. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1583. Response res;
  1584. res.set_header("Content-Type", "text/plain");
  1585. auto ret = detail::encoding_type(req, res);
  1586. // gzip has highest q=1.0, so it should be selected even though
  1587. // br and zstd are also supported
  1588. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1589. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1590. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1591. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1592. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1593. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1594. #else
  1595. EXPECT_TRUE(ret == detail::EncodingType::None);
  1596. #endif
  1597. }
  1598. TEST(BufferStreamTest, read) {
  1599. detail::BufferStream strm1;
  1600. Stream &strm = strm1;
  1601. EXPECT_EQ(5, strm.write("hello"));
  1602. char buf[512];
  1603. EXPECT_EQ(2, strm.read(buf, 2));
  1604. EXPECT_EQ('h', buf[0]);
  1605. EXPECT_EQ('e', buf[1]);
  1606. EXPECT_EQ(2, strm.read(buf, 2));
  1607. EXPECT_EQ('l', buf[0]);
  1608. EXPECT_EQ('l', buf[1]);
  1609. EXPECT_EQ(1, strm.read(buf, 1));
  1610. EXPECT_EQ('o', buf[0]);
  1611. EXPECT_EQ(0, strm.read(buf, 1));
  1612. }
  1613. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1614. auto host = "www.httpwatch.com";
  1615. auto ip = hosted_at(host);
  1616. EXPECT_EQ("23.96.13.243", ip);
  1617. std::vector<std::string> addrs;
  1618. hosted_at(host, addrs);
  1619. EXPECT_EQ(1u, addrs.size());
  1620. }
  1621. #if 0 // It depends on each test environment...
  1622. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1623. auto host = "www.youtube.com";
  1624. std::vector<std::string> addrs;
  1625. hosted_at(host, addrs);
  1626. EXPECT_EQ(20u, addrs.size());
  1627. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1628. EXPECT_TRUE(it != addrs.end());
  1629. }
  1630. #endif
  1631. class ChunkedEncodingTest : public ::testing::Test {
  1632. protected:
  1633. ChunkedEncodingTest()
  1634. : cli_(HOST, PORT)
  1635. #ifdef CPPHTTPLIB_SSL_ENABLED
  1636. ,
  1637. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1638. #endif
  1639. {
  1640. cli_.set_connection_timeout(2);
  1641. #ifdef CPPHTTPLIB_SSL_ENABLED
  1642. cli_.enable_server_certificate_verification(false);
  1643. #endif
  1644. }
  1645. virtual void SetUp() {
  1646. read_file("./image.jpg", image_data_);
  1647. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1648. res.set_content("Hello World!", "text/plain");
  1649. });
  1650. svr_.Get(
  1651. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1652. res.set_chunked_content_provider(
  1653. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1654. size_t remaining = image_data_.size() - offset;
  1655. if (remaining == 0) {
  1656. sink.done();
  1657. } else {
  1658. constexpr size_t CHUNK_SIZE = 1024;
  1659. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1660. sink.write(&image_data_[offset], send_size);
  1661. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1662. }
  1663. return true;
  1664. });
  1665. });
  1666. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1667. svr_.wait_until_ready();
  1668. }
  1669. virtual void TearDown() {
  1670. svr_.stop();
  1671. if (!request_threads_.empty()) {
  1672. std::this_thread::sleep_for(std::chrono::seconds(1));
  1673. for (auto &t : request_threads_) {
  1674. t.join();
  1675. }
  1676. }
  1677. t_.join();
  1678. }
  1679. #ifdef CPPHTTPLIB_SSL_ENABLED
  1680. SSLClient cli_;
  1681. SSLServer svr_;
  1682. #else
  1683. Client cli_;
  1684. Server svr_;
  1685. #endif
  1686. thread t_;
  1687. std::vector<thread> request_threads_;
  1688. std::string image_data_;
  1689. };
  1690. TEST_F(ChunkedEncodingTest, NormalGet) {
  1691. auto res = cli_.Get("/chunked");
  1692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1693. std::string out;
  1694. read_file("./image.jpg", out);
  1695. EXPECT_EQ(StatusCode::OK_200, res->status);
  1696. EXPECT_EQ(out, res->body);
  1697. }
  1698. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1699. std::string body;
  1700. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1701. body.append(data, data_length);
  1702. return true;
  1703. });
  1704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1705. std::string out;
  1706. read_file("./image.jpg", out);
  1707. EXPECT_EQ(StatusCode::OK_200, res->status);
  1708. EXPECT_EQ(out, body);
  1709. }
  1710. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1711. std::string body;
  1712. auto res = cli_.Get(
  1713. "/chunked",
  1714. [&](const Response &response) {
  1715. EXPECT_EQ(StatusCode::OK_200, response.status);
  1716. return true;
  1717. },
  1718. [&](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(RangeTest, FromHTTPBin_Online) {
  1729. auto host = "httpbingo.org";
  1730. auto path = std::string{"/range/32"};
  1731. #ifdef CPPHTTPLIB_SSL_ENABLED
  1732. auto port = 443;
  1733. SSLClient cli(host, port);
  1734. #else
  1735. auto port = 80;
  1736. Client cli(host, port);
  1737. #endif
  1738. cli.set_connection_timeout(5);
  1739. {
  1740. auto res = cli.Get(path);
  1741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1742. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1743. EXPECT_EQ(StatusCode::OK_200, res->status);
  1744. }
  1745. {
  1746. Headers headers = {make_range_header({{1, -1}})};
  1747. auto res = cli.Get(path, headers);
  1748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1749. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1750. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1751. }
  1752. {
  1753. Headers headers = {make_range_header({{1, 10}})};
  1754. auto res = cli.Get(path, headers);
  1755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1756. EXPECT_EQ("bcdefghijk", res->body);
  1757. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1758. }
  1759. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1760. // entire resource, while the original httpbin returned 200. Both are
  1761. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1762. {
  1763. Headers headers = {make_range_header({{0, 31}})};
  1764. auto res = cli.Get(path, headers);
  1765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1766. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1767. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1768. res->status == StatusCode::PartialContent_206);
  1769. }
  1770. {
  1771. Headers headers = {make_range_header({{0, -1}})};
  1772. auto res = cli.Get(path, headers);
  1773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1774. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1775. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1776. res->status == StatusCode::PartialContent_206);
  1777. }
  1778. // go-httpbin returns 206 with clamped range for over-range requests,
  1779. // while the original httpbin returned 416. Both behaviors are observed
  1780. // in real servers, so we only verify the request succeeds.
  1781. {
  1782. Headers headers = {make_range_header({{0, 32}})};
  1783. auto res = cli.Get(path, headers);
  1784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1785. }
  1786. }
  1787. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1788. auto host = "unresolvableaddress.local";
  1789. auto path = std::string{"/"};
  1790. #ifdef CPPHTTPLIB_SSL_ENABLED
  1791. auto port = 443;
  1792. SSLClient cli(host, port);
  1793. #else
  1794. auto port = 80;
  1795. Client cli(host, port);
  1796. #endif
  1797. cli.set_connection_timeout(1);
  1798. {
  1799. auto res = cli.Get(path);
  1800. ASSERT_FALSE(res);
  1801. }
  1802. std::this_thread::sleep_for(std::chrono::seconds(8));
  1803. }
  1804. #if defined(__linux__) && defined(__GLIBC__) && \
  1805. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1806. // Forward declaration: in split builds split.py strips `inline` and moves the
  1807. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1808. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1809. // against the symbol in both header-only and split builds.
  1810. namespace httplib {
  1811. namespace detail {
  1812. int getaddrinfo_with_timeout(const char *node, const char *service,
  1813. const struct addrinfo *hints,
  1814. struct addrinfo **res, time_t timeout_sec);
  1815. } // namespace detail
  1816. } // namespace httplib
  1817. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1818. //
  1819. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1820. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1821. // gai_suspend() call hits the connection timeout the function calls
  1822. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1823. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1824. // still alive and still references the now-destroyed stack frame.
  1825. //
  1826. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1827. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1828. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1829. // and runs them in a container.
  1830. namespace {
  1831. bool should_run_issue_2431_tests() {
  1832. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1833. return v && *v && std::string(v) != "0";
  1834. }
  1835. std::string unique_unresolvable_host(int n) {
  1836. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1837. // glibc still asks the configured nameserver — which is exactly the path
  1838. // we want to exercise. A unique label per call avoids the resolver cache.
  1839. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1840. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1841. std::to_string(n) + ".invalid";
  1842. }
  1843. } // namespace
  1844. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1845. if (!should_run_issue_2431_tests()) {
  1846. GTEST_SKIP()
  1847. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1848. }
  1849. for (int i = 0; i < 8; ++i) {
  1850. struct addrinfo hints;
  1851. memset(&hints, 0, sizeof(hints));
  1852. hints.ai_family = AF_UNSPEC;
  1853. hints.ai_socktype = SOCK_STREAM;
  1854. auto host = unique_unresolvable_host(i);
  1855. struct addrinfo *result = nullptr;
  1856. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1857. &result, /*timeout_sec=*/1);
  1858. if (rc == 0 && result) { freeaddrinfo(result); }
  1859. }
  1860. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1861. // stack region they still believe holds their gaicb.
  1862. std::this_thread::sleep_for(std::chrono::seconds(3));
  1863. }
  1864. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1865. if (!should_run_issue_2431_tests()) {
  1866. GTEST_SKIP()
  1867. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1868. }
  1869. std::atomic<bool> stop{false};
  1870. std::vector<std::thread> threads;
  1871. for (int t = 0; t < 8; ++t) {
  1872. threads.emplace_back([t, &stop] {
  1873. int i = 0;
  1874. while (!stop.load(std::memory_order_relaxed)) {
  1875. struct addrinfo hints;
  1876. memset(&hints, 0, sizeof(hints));
  1877. hints.ai_family = AF_UNSPEC;
  1878. hints.ai_socktype = SOCK_STREAM;
  1879. auto host = unique_unresolvable_host(t * 100000 + i++);
  1880. struct addrinfo *result = nullptr;
  1881. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1882. &result, /*timeout_sec=*/1);
  1883. if (rc == 0 && result) { freeaddrinfo(result); }
  1884. }
  1885. });
  1886. }
  1887. std::this_thread::sleep_for(std::chrono::seconds(8));
  1888. stop.store(true, std::memory_order_relaxed);
  1889. for (auto &th : threads) {
  1890. th.join();
  1891. }
  1892. std::this_thread::sleep_for(std::chrono::seconds(3));
  1893. }
  1894. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1895. if (!should_run_issue_2431_tests()) {
  1896. GTEST_SKIP()
  1897. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1898. }
  1899. std::atomic<bool> stop{false};
  1900. std::vector<std::thread> threads;
  1901. for (int t = 0; t < 8; ++t) {
  1902. threads.emplace_back([t, &stop] {
  1903. int i = 0;
  1904. while (!stop.load(std::memory_order_relaxed)) {
  1905. auto host = unique_unresolvable_host(t * 100000 + i++);
  1906. Client cli(host, 80);
  1907. cli.set_connection_timeout(1, 0);
  1908. cli.set_read_timeout(1, 0);
  1909. cli.set_write_timeout(1, 0);
  1910. (void)cli.Get("/");
  1911. }
  1912. });
  1913. }
  1914. std::this_thread::sleep_for(std::chrono::seconds(8));
  1915. stop.store(true, std::memory_order_relaxed);
  1916. for (auto &th : threads) {
  1917. th.join();
  1918. }
  1919. std::this_thread::sleep_for(std::chrono::seconds(3));
  1920. }
  1921. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1922. TEST(ConnectionErrorTest, InvalidHost) {
  1923. auto host = "-abcde.com";
  1924. #ifdef CPPHTTPLIB_SSL_ENABLED
  1925. auto port = 443;
  1926. SSLClient cli(host, port);
  1927. #else
  1928. auto port = 80;
  1929. Client cli(host, port);
  1930. #endif
  1931. cli.set_connection_timeout(std::chrono::seconds(2));
  1932. auto res = cli.Get("/");
  1933. ASSERT_TRUE(!res);
  1934. EXPECT_EQ(Error::Connection, res.error());
  1935. }
  1936. TEST(ConnectionErrorTest, InvalidHost2) {
  1937. auto host = "httpcan.org/";
  1938. #ifdef CPPHTTPLIB_SSL_ENABLED
  1939. SSLClient cli(host);
  1940. #else
  1941. Client cli(host);
  1942. #endif
  1943. cli.set_connection_timeout(std::chrono::seconds(2));
  1944. auto res = cli.Get("/");
  1945. ASSERT_TRUE(!res);
  1946. EXPECT_EQ(Error::Connection, res.error());
  1947. }
  1948. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1949. auto host = "httpcan.org/";
  1950. #ifdef CPPHTTPLIB_SSL_ENABLED
  1951. SSLClient cli(host);
  1952. #else
  1953. Client cli(host);
  1954. #endif
  1955. cli.set_connection_timeout(std::chrono::seconds(2));
  1956. auto res = cli.Get("/");
  1957. ASSERT_TRUE(!res);
  1958. stringstream s;
  1959. s << "error code: " << res.error();
  1960. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1961. }
  1962. TEST(ConnectionErrorTest, InvalidPort) {
  1963. auto host = "localhost";
  1964. auto port = 44380;
  1965. #ifdef CPPHTTPLIB_SSL_ENABLED
  1966. SSLClient cli(host, port);
  1967. #else
  1968. Client cli(host, port);
  1969. #endif
  1970. cli.set_connection_timeout(std::chrono::seconds(2));
  1971. auto res = cli.Get("/");
  1972. ASSERT_TRUE(!res);
  1973. EXPECT_TRUE(Error::Connection == res.error() ||
  1974. Error::ConnectionTimeout == res.error());
  1975. }
  1976. TEST(ConnectionErrorTest, Timeout_Online) {
  1977. auto host = "google.com";
  1978. #ifdef CPPHTTPLIB_SSL_ENABLED
  1979. auto port = 44380;
  1980. SSLClient cli(host, port);
  1981. #else
  1982. auto port = 8080;
  1983. Client cli(host, port);
  1984. #endif
  1985. cli.set_connection_timeout(std::chrono::seconds(2));
  1986. // only probe one address type so that the error reason
  1987. // correlates to the timed-out IPv4, not the unsupported
  1988. // IPv6 connection attempt
  1989. cli.set_address_family(AF_INET);
  1990. auto res = cli.Get("/");
  1991. ASSERT_TRUE(!res);
  1992. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1993. }
  1994. TEST(CancelTest, NoCancel_Online) {
  1995. auto host = "httpbingo.org";
  1996. auto path = std::string{"/range/32"};
  1997. #ifdef CPPHTTPLIB_SSL_ENABLED
  1998. auto port = 443;
  1999. SSLClient cli(host, port);
  2000. #else
  2001. auto port = 80;
  2002. Client cli(host, port);
  2003. #endif
  2004. cli.set_connection_timeout(std::chrono::seconds(5));
  2005. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2007. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2008. EXPECT_EQ(StatusCode::OK_200, res->status);
  2009. }
  2010. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2011. // Use /bytes with a large payload so that the DownloadProgress callback
  2012. // (which only fires for Content-Length responses) is invoked before the
  2013. // entire body is received, giving cancellation a chance to fire.
  2014. auto host = "httpbingo.org";
  2015. auto path = std::string{"/bytes/524288"};
  2016. #ifdef CPPHTTPLIB_SSL_ENABLED
  2017. auto port = 443;
  2018. SSLClient cli(host, port);
  2019. #else
  2020. auto port = 80;
  2021. Client cli(host, port);
  2022. #endif
  2023. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2024. cli.set_connection_timeout(std::chrono::seconds(5));
  2025. ASSERT_TRUE(!res);
  2026. EXPECT_EQ(Error::Canceled, res.error());
  2027. }
  2028. TEST(CancelTest, WithCancelLargePayload_Online) {
  2029. auto host = "httpbingo.org";
  2030. auto path = std::string{"/bytes/524288"};
  2031. #ifdef CPPHTTPLIB_SSL_ENABLED
  2032. auto port = 443;
  2033. SSLClient cli(host, port);
  2034. #else
  2035. auto port = 80;
  2036. Client cli(host, port);
  2037. #endif
  2038. cli.set_connection_timeout(std::chrono::seconds(5));
  2039. uint32_t count = 0;
  2040. auto res =
  2041. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2042. ASSERT_TRUE(!res);
  2043. EXPECT_EQ(Error::Canceled, res.error());
  2044. }
  2045. TEST(CancelTest, NoCancelPost) {
  2046. Server svr;
  2047. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2048. res.set_content("Hello World!", "text/plain");
  2049. });
  2050. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2051. auto se = detail::scope_exit([&] {
  2052. svr.stop();
  2053. thread.join();
  2054. ASSERT_FALSE(svr.is_running());
  2055. });
  2056. svr.wait_until_ready();
  2057. Client cli(HOST, PORT);
  2058. cli.set_connection_timeout(std::chrono::seconds(5));
  2059. auto res =
  2060. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2061. "application/json", [](uint64_t, uint64_t) { return true; });
  2062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2063. EXPECT_EQ("Hello World!", res->body);
  2064. EXPECT_EQ(StatusCode::OK_200, res->status);
  2065. }
  2066. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2067. Server svr;
  2068. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2069. res.set_content("Hello World!", "text/plain");
  2070. });
  2071. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2072. auto se = detail::scope_exit([&] {
  2073. svr.stop();
  2074. thread.join();
  2075. ASSERT_FALSE(svr.is_running());
  2076. });
  2077. svr.wait_until_ready();
  2078. Client cli(HOST, PORT);
  2079. cli.set_connection_timeout(std::chrono::seconds(5));
  2080. auto res =
  2081. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2082. "application/json", [](uint64_t, uint64_t) { return false; });
  2083. ASSERT_TRUE(!res);
  2084. EXPECT_EQ(Error::Canceled, res.error());
  2085. }
  2086. TEST(CancelTest, WithCancelLargePayloadPost) {
  2087. Server svr;
  2088. svr.set_payload_max_length(200 * 1024 * 1024);
  2089. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2090. res.set_content(LARGE_DATA, "text/plain");
  2091. });
  2092. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2093. auto se = detail::scope_exit([&] {
  2094. svr.stop();
  2095. thread.join();
  2096. ASSERT_FALSE(svr.is_running());
  2097. });
  2098. svr.wait_until_ready();
  2099. Client cli(HOST, PORT);
  2100. cli.set_payload_max_length(200 * 1024 * 1024);
  2101. cli.set_connection_timeout(std::chrono::seconds(5));
  2102. auto res =
  2103. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2104. "application/json", [](uint64_t, uint64_t) { return false; });
  2105. ASSERT_TRUE(!res);
  2106. EXPECT_EQ(Error::Canceled, res.error());
  2107. }
  2108. TEST(CancelTest, NoCancelPut) {
  2109. Server svr;
  2110. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2111. res.set_content("Hello World!", "text/plain");
  2112. });
  2113. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2114. auto se = detail::scope_exit([&] {
  2115. svr.stop();
  2116. thread.join();
  2117. ASSERT_FALSE(svr.is_running());
  2118. });
  2119. svr.wait_until_ready();
  2120. Client cli(HOST, PORT);
  2121. cli.set_connection_timeout(std::chrono::seconds(5));
  2122. auto res =
  2123. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2124. "application/json", [](uint64_t, uint64_t) { return true; });
  2125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2126. EXPECT_EQ("Hello World!", res->body);
  2127. EXPECT_EQ(StatusCode::OK_200, res->status);
  2128. }
  2129. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2130. Server svr;
  2131. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2132. res.set_content("Hello World!", "text/plain");
  2133. });
  2134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2135. auto se = detail::scope_exit([&] {
  2136. svr.stop();
  2137. thread.join();
  2138. ASSERT_FALSE(svr.is_running());
  2139. });
  2140. svr.wait_until_ready();
  2141. Client cli(HOST, PORT);
  2142. cli.set_connection_timeout(std::chrono::seconds(5));
  2143. auto res =
  2144. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2145. "application/json", [](uint64_t, uint64_t) { return false; });
  2146. ASSERT_TRUE(!res);
  2147. EXPECT_EQ(Error::Canceled, res.error());
  2148. }
  2149. TEST(CancelTest, WithCancelLargePayloadPut) {
  2150. Server svr;
  2151. svr.set_payload_max_length(200 * 1024 * 1024);
  2152. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2153. res.set_content(LARGE_DATA, "text/plain");
  2154. });
  2155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2156. auto se = detail::scope_exit([&] {
  2157. svr.stop();
  2158. thread.join();
  2159. ASSERT_FALSE(svr.is_running());
  2160. });
  2161. svr.wait_until_ready();
  2162. Client cli(HOST, PORT);
  2163. cli.set_payload_max_length(200 * 1024 * 1024);
  2164. cli.set_connection_timeout(std::chrono::seconds(5));
  2165. auto res =
  2166. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2167. "application/json", [](uint64_t, uint64_t) { return false; });
  2168. ASSERT_TRUE(!res);
  2169. EXPECT_EQ(Error::Canceled, res.error());
  2170. }
  2171. TEST(CancelTest, NoCancelPatch) {
  2172. Server svr;
  2173. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2174. res.set_content("Hello World!", "text/plain");
  2175. });
  2176. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2177. auto se = detail::scope_exit([&] {
  2178. svr.stop();
  2179. thread.join();
  2180. ASSERT_FALSE(svr.is_running());
  2181. });
  2182. svr.wait_until_ready();
  2183. Client cli(HOST, PORT);
  2184. cli.set_connection_timeout(std::chrono::seconds(5));
  2185. auto res =
  2186. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2187. "application/json", [](uint64_t, uint64_t) { return true; });
  2188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2189. EXPECT_EQ("Hello World!", res->body);
  2190. EXPECT_EQ(StatusCode::OK_200, res->status);
  2191. }
  2192. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2193. Server svr;
  2194. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2195. res.set_content("Hello World!", "text/plain");
  2196. });
  2197. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2198. auto se = detail::scope_exit([&] {
  2199. svr.stop();
  2200. thread.join();
  2201. ASSERT_FALSE(svr.is_running());
  2202. });
  2203. svr.wait_until_ready();
  2204. Client cli(HOST, PORT);
  2205. cli.set_connection_timeout(std::chrono::seconds(5));
  2206. auto res =
  2207. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2208. "application/json", [](uint64_t, uint64_t) { return false; });
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_EQ(Error::Canceled, res.error());
  2211. }
  2212. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2213. Server svr;
  2214. svr.set_payload_max_length(200 * 1024 * 1024);
  2215. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2216. res.set_content(LARGE_DATA, "text/plain");
  2217. });
  2218. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2219. auto se = detail::scope_exit([&] {
  2220. svr.stop();
  2221. thread.join();
  2222. ASSERT_FALSE(svr.is_running());
  2223. });
  2224. svr.wait_until_ready();
  2225. Client cli(HOST, PORT);
  2226. cli.set_payload_max_length(200 * 1024 * 1024);
  2227. cli.set_connection_timeout(std::chrono::seconds(5));
  2228. auto res =
  2229. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2230. "application/json", [](uint64_t, uint64_t) { return false; });
  2231. ASSERT_TRUE(!res);
  2232. EXPECT_EQ(Error::Canceled, res.error());
  2233. }
  2234. TEST(CancelTest, NoCancelDelete) {
  2235. Server svr;
  2236. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2237. res.set_content("Hello World!", "text/plain");
  2238. });
  2239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2240. auto se = detail::scope_exit([&] {
  2241. svr.stop();
  2242. thread.join();
  2243. ASSERT_FALSE(svr.is_running());
  2244. });
  2245. svr.wait_until_ready();
  2246. Client cli(HOST, PORT);
  2247. cli.set_connection_timeout(std::chrono::seconds(5));
  2248. auto res =
  2249. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2250. "application/json", [](uint64_t, uint64_t) { return true; });
  2251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2252. EXPECT_EQ("Hello World!", res->body);
  2253. EXPECT_EQ(StatusCode::OK_200, res->status);
  2254. }
  2255. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2256. Server svr;
  2257. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2258. res.set_content("Hello World!", "text/plain");
  2259. });
  2260. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2261. auto se = detail::scope_exit([&] {
  2262. svr.stop();
  2263. thread.join();
  2264. ASSERT_FALSE(svr.is_running());
  2265. });
  2266. svr.wait_until_ready();
  2267. Client cli(HOST, PORT);
  2268. cli.set_connection_timeout(std::chrono::seconds(5));
  2269. auto res =
  2270. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2271. "application/json", [](uint64_t, uint64_t) { return false; });
  2272. ASSERT_TRUE(!res);
  2273. EXPECT_EQ(Error::Canceled, res.error());
  2274. }
  2275. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2276. Server svr;
  2277. svr.set_payload_max_length(200 * 1024 * 1024);
  2278. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2279. res.set_content(LARGE_DATA, "text/plain");
  2280. });
  2281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2282. auto se = detail::scope_exit([&] {
  2283. svr.stop();
  2284. thread.join();
  2285. ASSERT_FALSE(svr.is_running());
  2286. });
  2287. svr.wait_until_ready();
  2288. Client cli(HOST, PORT);
  2289. cli.set_payload_max_length(200 * 1024 * 1024);
  2290. cli.set_connection_timeout(std::chrono::seconds(5));
  2291. auto res =
  2292. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2293. "application/json", [](uint64_t, uint64_t) { return false; });
  2294. ASSERT_TRUE(!res);
  2295. EXPECT_EQ(Error::Canceled, res.error());
  2296. }
  2297. static std::string remove_whitespace(const std::string &input) {
  2298. std::string output;
  2299. output.reserve(input.size());
  2300. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2301. [](unsigned char c) { return !std::isspace(c); });
  2302. return output;
  2303. }
  2304. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2305. auto host = "httpbingo.org";
  2306. auto path = std::string{"/basic-auth/hello/world"};
  2307. #ifdef CPPHTTPLIB_SSL_ENABLED
  2308. auto port = 443;
  2309. SSLClient cli(host, port);
  2310. #else
  2311. auto port = 80;
  2312. Client cli(host, port);
  2313. #endif
  2314. {
  2315. auto res = cli.Get(path);
  2316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2317. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2318. }
  2319. {
  2320. auto res = cli.Get(
  2321. path, Headers{make_basic_authentication_header("hello", "world")});
  2322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2323. auto body = remove_whitespace(res->body);
  2324. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2325. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2326. EXPECT_EQ(StatusCode::OK_200, res->status);
  2327. }
  2328. {
  2329. cli.set_basic_auth("hello", "world");
  2330. auto res = cli.Get(path);
  2331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2332. auto body = remove_whitespace(res->body);
  2333. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2334. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2335. EXPECT_EQ(StatusCode::OK_200, res->status);
  2336. }
  2337. {
  2338. cli.set_basic_auth("hello", "bad");
  2339. auto res = cli.Get(path);
  2340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2341. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2342. }
  2343. {
  2344. cli.set_basic_auth("bad", "world");
  2345. auto res = cli.Get(path);
  2346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2347. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2348. }
  2349. }
  2350. #ifdef CPPHTTPLIB_SSL_ENABLED
  2351. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2352. auto host = "httpbingo.org";
  2353. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2354. auto paths = std::vector<std::string>{
  2355. "/digest-auth/auth/hello/world/MD5",
  2356. "/digest-auth/auth/hello/world/SHA-256",
  2357. };
  2358. auto port = 443;
  2359. SSLClient cli(host, port);
  2360. {
  2361. auto res = cli.Get(unauth_path);
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2364. }
  2365. {
  2366. cli.set_digest_auth("hello", "world");
  2367. for (const auto &path : paths) {
  2368. auto res = cli.Get(path.c_str());
  2369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2370. auto body = remove_whitespace(res->body);
  2371. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2372. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2373. EXPECT_EQ(StatusCode::OK_200, res->status);
  2374. }
  2375. cli.set_digest_auth("hello", "bad");
  2376. for (const auto &path : paths) {
  2377. auto res = cli.Get(path.c_str());
  2378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2379. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2380. }
  2381. }
  2382. }
  2383. #endif
  2384. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2385. auto host = "google.com";
  2386. auto another_host = "example.com";
  2387. auto wrong_ip = "0.0.0.0";
  2388. #ifdef CPPHTTPLIB_SSL_ENABLED
  2389. SSLClient cli(host);
  2390. #else
  2391. Client cli(host);
  2392. #endif
  2393. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2394. auto res = cli.Get("/");
  2395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2396. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2397. }
  2398. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2399. auto host = "google.com";
  2400. auto wrong_ip = "0.0.0.0";
  2401. #ifdef CPPHTTPLIB_SSL_ENABLED
  2402. SSLClient cli(host);
  2403. #else
  2404. Client cli(host);
  2405. #endif
  2406. cli.set_hostname_addr_map({{host, wrong_ip}});
  2407. auto res = cli.Get("/");
  2408. ASSERT_TRUE(!res);
  2409. EXPECT_EQ(Error::Connection, res.error());
  2410. }
  2411. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2412. // A mapped value that is not an IP literal must be resolved. "localhost"
  2413. // resolves from the hosts file, so this test needs no external DNS.
  2414. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2415. auto host = "target.invalid";
  2416. Server svr;
  2417. std::string received_host;
  2418. svr.Get("/hi", [&](const Request &req, Response &res) {
  2419. received_host = req.get_header_value("Host");
  2420. res.set_content("Hello World!", "text/plain");
  2421. });
  2422. auto port = svr.bind_to_any_port(HOST);
  2423. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2424. auto se = detail::scope_exit([&] {
  2425. svr.stop();
  2426. thread.join();
  2427. ASSERT_FALSE(svr.is_running());
  2428. });
  2429. svr.wait_until_ready();
  2430. Client cli(host, port);
  2431. cli.set_hostname_addr_map({{host, HOST}});
  2432. auto res = cli.Get("/hi");
  2433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2434. EXPECT_EQ(StatusCode::OK_200, res->status);
  2435. // The mapping only redirects the connection; the identity stays host_.
  2436. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2437. }
  2438. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2439. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2440. auto host = "target.invalid";
  2441. Server svr;
  2442. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2443. res.set_content("Hello World!", "text/plain");
  2444. });
  2445. auto port = svr.bind_to_any_port("127.0.0.1");
  2446. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2447. auto se = detail::scope_exit([&] {
  2448. svr.stop();
  2449. thread.join();
  2450. ASSERT_FALSE(svr.is_running());
  2451. });
  2452. svr.wait_until_ready();
  2453. Client cli(host, port);
  2454. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2455. auto res = cli.Get("/hi");
  2456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2457. EXPECT_EQ(StatusCode::OK_200, res->status);
  2458. }
  2459. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2460. // An empty mapped value must leave host_ as the connection target. Without
  2461. // that guard the empty value would become the host argument, getaddrinfo
  2462. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2463. // loopback - silently connecting somewhere the caller never asked for.
  2464. // The server listens on loopback, so such a fallback would succeed and is
  2465. // therefore observable as a failure of this test.
  2466. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2467. Server svr;
  2468. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2469. res.set_content("Hello World!", "text/plain");
  2470. });
  2471. auto port = svr.bind_to_any_port(HOST);
  2472. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2473. auto se = detail::scope_exit([&] {
  2474. svr.stop();
  2475. thread.join();
  2476. ASSERT_FALSE(svr.is_running());
  2477. });
  2478. svr.wait_until_ready();
  2479. Client cli(blackhole, port);
  2480. cli.set_hostname_addr_map({{blackhole, ""}});
  2481. cli.set_connection_timeout(1);
  2482. auto res = cli.Get("/hi");
  2483. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2484. }
  2485. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2486. auto host = "httpbingo.org";
  2487. auto path = std::string{"/absolute-redirect/3"};
  2488. #ifdef CPPHTTPLIB_SSL_ENABLED
  2489. SSLClient cli(host);
  2490. #else
  2491. Client cli(host);
  2492. #endif
  2493. cli.set_follow_location(true);
  2494. auto res = cli.Get(path);
  2495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2496. EXPECT_EQ(StatusCode::OK_200, res->status);
  2497. }
  2498. TEST(RedirectTest, Redirect_Online) {
  2499. auto host = "httpbingo.org";
  2500. auto path = std::string{"/redirect/3"};
  2501. #ifdef CPPHTTPLIB_SSL_ENABLED
  2502. SSLClient cli(host);
  2503. #else
  2504. Client cli(host);
  2505. #endif
  2506. cli.set_follow_location(true);
  2507. auto res = cli.Get(path);
  2508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2509. EXPECT_EQ(StatusCode::OK_200, res->status);
  2510. }
  2511. TEST(RelativeRedirectTest, Redirect_Online) {
  2512. auto host = "httpbingo.org";
  2513. auto path = std::string{"/relative-redirect/3"};
  2514. #ifdef CPPHTTPLIB_SSL_ENABLED
  2515. SSLClient cli(host);
  2516. #else
  2517. Client cli(host);
  2518. #endif
  2519. cli.set_follow_location(true);
  2520. auto res = cli.Get(path);
  2521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2522. EXPECT_EQ(StatusCode::OK_200, res->status);
  2523. }
  2524. TEST(TooManyRedirectTest, Redirect_Online) {
  2525. auto host = "httpbingo.org";
  2526. auto path = std::string{"/redirect/21"};
  2527. #ifdef CPPHTTPLIB_SSL_ENABLED
  2528. SSLClient cli(host);
  2529. #else
  2530. Client cli(host);
  2531. #endif
  2532. cli.set_follow_location(true);
  2533. auto res = cli.Get(path);
  2534. ASSERT_TRUE(!res);
  2535. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2536. }
  2537. #ifdef CPPHTTPLIB_SSL_ENABLED
  2538. TEST(YahooRedirectTest, Redirect_Online) {
  2539. Client cli("yahoo.com");
  2540. auto res = cli.Get("/");
  2541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2542. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2543. cli.set_follow_location(true);
  2544. res = cli.Get("/");
  2545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2546. EXPECT_EQ(StatusCode::OK_200, res->status);
  2547. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2548. }
  2549. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2550. #define REDIR_HOST "httpbingo.org"
  2551. #define REDIR_PATH "/redirect-to"
  2552. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2553. SSLClient cli(REDIR_HOST);
  2554. cli.set_follow_location(true);
  2555. auto res =
  2556. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2558. EXPECT_EQ(StatusCode::OK_200, res->status);
  2559. }
  2560. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2561. SSLClient cli(REDIR_HOST);
  2562. cli.set_follow_location(true);
  2563. Params params;
  2564. params.emplace("url", "http://example.com");
  2565. params.emplace("status_code", "302");
  2566. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2568. EXPECT_EQ(StatusCode::OK_200, res->status);
  2569. }
  2570. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2571. SSLClient cli(REDIR_HOST);
  2572. cli.set_follow_location(true);
  2573. Params params;
  2574. params.emplace("url", "http://example.com");
  2575. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2577. EXPECT_EQ(StatusCode::OK_200, res->status);
  2578. }
  2579. TEST(UrlWithSpace, Redirect_Online) {
  2580. SSLClient cli("edge.forgecdn.net");
  2581. cli.set_follow_location(true);
  2582. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2584. EXPECT_EQ(StatusCode::OK_200, res->status);
  2585. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2586. }
  2587. #endif
  2588. #if !defined(_WIN32) && !defined(_WIN64)
  2589. TEST(ReceiveSignals, Signal) {
  2590. auto setupSignalHandlers = []() {
  2591. struct sigaction act;
  2592. sigemptyset(&act.sa_mask);
  2593. act.sa_flags = SA_SIGINFO;
  2594. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2595. switch (sig) {
  2596. case SIGINT:
  2597. default: break;
  2598. }
  2599. };
  2600. ::sigaction(SIGINT, &act, nullptr);
  2601. };
  2602. Server svr;
  2603. int port = 0;
  2604. auto thread = std::thread([&]() {
  2605. setupSignalHandlers();
  2606. port = svr.bind_to_any_port(HOST);
  2607. svr.listen_after_bind();
  2608. });
  2609. auto se = detail::scope_exit([&] {
  2610. svr.stop();
  2611. thread.join();
  2612. ASSERT_FALSE(svr.is_running());
  2613. });
  2614. svr.wait_until_ready();
  2615. ASSERT_TRUE(svr.is_running());
  2616. pthread_kill(thread.native_handle(), SIGINT);
  2617. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2618. ASSERT_TRUE(svr.is_running());
  2619. }
  2620. #endif
  2621. TEST(RedirectToDifferentPort, Redirect) {
  2622. Server svr1;
  2623. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2624. res.set_content("Hello World!", "text/plain");
  2625. });
  2626. int svr1_port = 0;
  2627. auto thread1 = std::thread([&]() {
  2628. svr1_port = svr1.bind_to_any_port(HOST);
  2629. svr1.listen_after_bind();
  2630. });
  2631. Server svr2;
  2632. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2633. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2634. });
  2635. int svr2_port = 0;
  2636. auto thread2 = std::thread([&]() {
  2637. svr2_port = svr2.bind_to_any_port(HOST);
  2638. svr2.listen_after_bind();
  2639. });
  2640. auto se = detail::scope_exit([&] {
  2641. svr2.stop();
  2642. thread2.join();
  2643. svr1.stop();
  2644. thread1.join();
  2645. ASSERT_FALSE(svr2.is_running());
  2646. ASSERT_FALSE(svr1.is_running());
  2647. });
  2648. svr1.wait_until_ready();
  2649. svr2.wait_until_ready();
  2650. Client cli("localhost", svr2_port);
  2651. cli.set_follow_location(true);
  2652. auto res = cli.Get("/2");
  2653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2654. EXPECT_EQ(StatusCode::OK_200, res->status);
  2655. EXPECT_EQ("Hello World!", res->body);
  2656. }
  2657. static void
  2658. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2659. Server svr1;
  2660. std::string captured_authorization;
  2661. svr1.Get("/target", [&](const Request &req, Response &res) {
  2662. captured_authorization = req.get_header_value("Authorization");
  2663. res.set_content("OK", "text/plain");
  2664. });
  2665. int svr1_port = 0;
  2666. auto thread1 = std::thread([&]() {
  2667. svr1_port = svr1.bind_to_any_port(HOST);
  2668. svr1.listen_after_bind();
  2669. });
  2670. Server svr2;
  2671. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2672. res.set_redirect(
  2673. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2674. });
  2675. int svr2_port = 0;
  2676. auto thread2 = std::thread([&]() {
  2677. svr2_port = svr2.bind_to_any_port(HOST);
  2678. svr2.listen_after_bind();
  2679. });
  2680. auto se = detail::scope_exit([&] {
  2681. svr2.stop();
  2682. thread2.join();
  2683. svr1.stop();
  2684. thread1.join();
  2685. ASSERT_FALSE(svr2.is_running());
  2686. ASSERT_FALSE(svr1.is_running());
  2687. });
  2688. svr1.wait_until_ready();
  2689. svr2.wait_until_ready();
  2690. Client cli("localhost", svr2_port);
  2691. cli.set_follow_location(true);
  2692. set_auth(cli);
  2693. auto res = cli.Get("/redir");
  2694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2695. EXPECT_EQ(StatusCode::OK_200, res->status);
  2696. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2697. EXPECT_TRUE(captured_authorization.empty());
  2698. }
  2699. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2700. TestDoNotForwardCredentialsOnRedirect(
  2701. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2702. }
  2703. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2704. TestDoNotForwardCredentialsOnRedirect(
  2705. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2706. }
  2707. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2708. Server svr1;
  2709. std::string captured_cookie;
  2710. bool target_hit = false;
  2711. svr1.Get("/target", [&](const Request &req, Response &res) {
  2712. captured_cookie = req.get_header_value("Cookie");
  2713. target_hit = true;
  2714. res.set_content("OK", "text/plain");
  2715. });
  2716. int svr1_port = 0;
  2717. auto thread1 = std::thread([&]() {
  2718. svr1_port = svr1.bind_to_any_port(HOST);
  2719. svr1.listen_after_bind();
  2720. });
  2721. Server svr2;
  2722. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2723. res.set_redirect(
  2724. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2725. });
  2726. int svr2_port = 0;
  2727. auto thread2 = std::thread([&]() {
  2728. svr2_port = svr2.bind_to_any_port(HOST);
  2729. svr2.listen_after_bind();
  2730. });
  2731. auto se = detail::scope_exit([&] {
  2732. svr2.stop();
  2733. thread2.join();
  2734. svr1.stop();
  2735. thread1.join();
  2736. ASSERT_FALSE(svr2.is_running());
  2737. ASSERT_FALSE(svr1.is_running());
  2738. });
  2739. svr1.wait_until_ready();
  2740. svr2.wait_until_ready();
  2741. Client cli("localhost", svr2_port);
  2742. cli.set_follow_location(true);
  2743. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2744. auto res = cli.Get("/redir", headers);
  2745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2746. EXPECT_EQ(StatusCode::OK_200, res->status);
  2747. EXPECT_TRUE(target_hit);
  2748. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2749. EXPECT_TRUE(captured_cookie.empty());
  2750. }
  2751. TEST(RedirectToSamePort, ForwardCookie) {
  2752. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2753. // header so that ordinary session flows keep working.
  2754. Server svr;
  2755. std::string captured_cookie;
  2756. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2757. res.set_redirect("/target", 302);
  2758. });
  2759. svr.Get("/target", [&](const Request &req, Response &res) {
  2760. captured_cookie = req.get_header_value("Cookie");
  2761. res.set_content("OK", "text/plain");
  2762. });
  2763. auto port = svr.bind_to_any_port(HOST);
  2764. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2765. auto se = detail::scope_exit([&] {
  2766. svr.stop();
  2767. thread.join();
  2768. ASSERT_FALSE(svr.is_running());
  2769. });
  2770. svr.wait_until_ready();
  2771. Client cli(HOST, port);
  2772. cli.set_follow_location(true);
  2773. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2774. auto res = cli.Get("/redir", headers);
  2775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2776. EXPECT_EQ(StatusCode::OK_200, res->status);
  2777. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2778. }
  2779. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2780. Server svr;
  2781. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2782. // Port number that overflows int — should not crash
  2783. res.set_redirect("http://localhost:99999999999999999999/target");
  2784. });
  2785. auto port = svr.bind_to_any_port(HOST);
  2786. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2787. auto se = detail::scope_exit([&] {
  2788. svr.stop();
  2789. thread.join();
  2790. ASSERT_FALSE(svr.is_running());
  2791. });
  2792. svr.wait_until_ready();
  2793. Client cli(HOST, port);
  2794. cli.set_follow_location(true);
  2795. auto res = cli.Get("/redir");
  2796. // Should fail gracefully, not crash (no valid response due to bad port)
  2797. EXPECT_FALSE(res);
  2798. }
  2799. TEST(RedirectFromPageWithContent, Redirect) {
  2800. Server svr;
  2801. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2802. res.set_content("___", "text/plain");
  2803. res.set_redirect("/2");
  2804. });
  2805. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2806. res.set_content("Hello World!", "text/plain");
  2807. });
  2808. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2809. auto se = detail::scope_exit([&] {
  2810. svr.stop();
  2811. th.join();
  2812. ASSERT_FALSE(svr.is_running());
  2813. });
  2814. svr.wait_until_ready();
  2815. {
  2816. Client cli("localhost", PORT);
  2817. cli.set_follow_location(true);
  2818. std::string body;
  2819. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2820. body.append(data, data_length);
  2821. return true;
  2822. });
  2823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2824. EXPECT_EQ(StatusCode::OK_200, res->status);
  2825. EXPECT_EQ("Hello World!", body);
  2826. }
  2827. {
  2828. Client cli("localhost", PORT);
  2829. std::string body;
  2830. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2831. body.append(data, data_length);
  2832. return true;
  2833. });
  2834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2835. EXPECT_EQ(StatusCode::Found_302, res->status);
  2836. EXPECT_EQ("___", body);
  2837. }
  2838. }
  2839. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2840. Server svr;
  2841. auto port_str = std::to_string(PORT);
  2842. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2843. auto expected_host = "[::1]:" + port_str;
  2844. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2845. res.set_content("___", "text/plain");
  2846. // res.set_redirect("/2");
  2847. res.set_redirect(redirect_url);
  2848. });
  2849. svr.Get("/2", [&](const Request &req, Response &res) {
  2850. auto host_header = req.headers.find("Host");
  2851. ASSERT_TRUE(host_header != req.headers.end());
  2852. EXPECT_EQ(expected_host, host_header->second);
  2853. res.set_content("Hello World!", "text/plain");
  2854. });
  2855. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2856. auto se = detail::scope_exit([&] {
  2857. svr.stop();
  2858. th.join();
  2859. ASSERT_FALSE(svr.is_running());
  2860. });
  2861. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2862. // actually starts anything, so the condition !svr.is_running() will
  2863. // always remain true, and the loop never stops.
  2864. // This basically counts how many milliseconds have passed since the
  2865. // call to svr.listen(), and if after 5 seconds nothing started yet
  2866. // aborts the test.
  2867. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2868. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2869. ASSERT_LT(milliseconds, 5000U);
  2870. }
  2871. {
  2872. Client cli("::1", PORT);
  2873. cli.set_follow_location(true);
  2874. std::string body;
  2875. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2876. body.append(data, data_length);
  2877. return true;
  2878. });
  2879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2880. EXPECT_EQ(StatusCode::OK_200, res->status);
  2881. EXPECT_EQ("Hello World!", body);
  2882. }
  2883. {
  2884. Client cli("::1", PORT);
  2885. std::string body;
  2886. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2887. body.append(data, data_length);
  2888. return true;
  2889. });
  2890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2891. EXPECT_EQ(StatusCode::Found_302, res->status);
  2892. EXPECT_EQ("___", body);
  2893. }
  2894. }
  2895. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2896. Server svr;
  2897. svr.Get("/foo", [](const Request &req, Response &res) {
  2898. auto a = req.params.find("a");
  2899. if (a != req.params.end()) {
  2900. res.set_content((*a).second, "text/plain");
  2901. res.status = StatusCode::OK_200;
  2902. } else {
  2903. res.status = StatusCode::BadRequest_400;
  2904. }
  2905. });
  2906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2907. auto se = detail::scope_exit([&] {
  2908. svr.stop();
  2909. thread.join();
  2910. ASSERT_FALSE(svr.is_running());
  2911. });
  2912. svr.wait_until_ready();
  2913. {
  2914. Client cli(HOST, PORT);
  2915. cli.set_path_encode(false);
  2916. auto res = cli.Get("/foo?a=explicitly+encoded");
  2917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2918. EXPECT_EQ(StatusCode::OK_200, res->status);
  2919. // This expects it back with a space, as the `+` won't have been
  2920. // url-encoded, and server-side the params get decoded turning `+`
  2921. // into spaces.
  2922. EXPECT_EQ("explicitly encoded", res->body);
  2923. }
  2924. }
  2925. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2926. // When path encoding is disabled the client must transmit the supplied
  2927. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2928. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2929. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2930. // than a space (0x20). Assert on the raw wire target to catch this.
  2931. Server svr;
  2932. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2933. svr.Get("/foo", [&](const Request &req, Response &res) {
  2934. EXPECT_EQ(expected_target, req.target);
  2935. res.status = StatusCode::OK_200;
  2936. });
  2937. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2938. auto se = detail::scope_exit([&] {
  2939. svr.stop();
  2940. thread.join();
  2941. ASSERT_FALSE(svr.is_running());
  2942. });
  2943. svr.wait_until_ready();
  2944. {
  2945. Client cli(HOST, PORT);
  2946. cli.set_path_encode(false);
  2947. auto res = cli.Get(expected_target.c_str());
  2948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2949. EXPECT_EQ(StatusCode::OK_200, res->status);
  2950. }
  2951. }
  2952. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2953. // `open_stream()` used to skip the path encoding that the buffered send
  2954. // path applies, so the same `path` produced different bytes in the request
  2955. // line depending on which API was used. Assert the two agree.
  2956. Server svr;
  2957. std::string target;
  2958. svr.Get(".*", [&](const Request &req, Response &res) {
  2959. target = req.target;
  2960. res.status = StatusCode::OK_200;
  2961. });
  2962. auto port = svr.bind_to_any_port(HOST);
  2963. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2964. auto se = detail::scope_exit([&] {
  2965. svr.stop();
  2966. thread.join();
  2967. ASSERT_FALSE(svr.is_running());
  2968. });
  2969. svr.wait_until_ready();
  2970. struct {
  2971. const char *path;
  2972. const char *expected;
  2973. } cases[] = {
  2974. {"/a b?x=1", "/a%20b?x=1"},
  2975. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2976. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2977. };
  2978. for (const auto &c : cases) {
  2979. Client cli(HOST, port);
  2980. target.clear();
  2981. auto res = cli.Get(c.path);
  2982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2983. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2984. auto buffered_target = target;
  2985. target.clear();
  2986. auto handle = cli.open_stream("GET", c.path);
  2987. EXPECT_TRUE(handle.is_valid())
  2988. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2989. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2990. }
  2991. }
  2992. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2993. // The `set_path_encode(false)` contract — transmit the supplied target
  2994. // verbatim — must hold for the streaming API too.
  2995. Server svr;
  2996. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2997. std::string target;
  2998. svr.Get("/foo", [&](const Request &req, Response &res) {
  2999. target = req.target;
  3000. res.status = StatusCode::OK_200;
  3001. });
  3002. auto port = svr.bind_to_any_port(HOST);
  3003. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3004. auto se = detail::scope_exit([&] {
  3005. svr.stop();
  3006. thread.join();
  3007. ASSERT_FALSE(svr.is_running());
  3008. });
  3009. svr.wait_until_ready();
  3010. {
  3011. Client cli(HOST, port);
  3012. cli.set_path_encode(false);
  3013. auto handle = cli.open_stream("GET", expected_target);
  3014. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3015. EXPECT_EQ(expected_target, target);
  3016. }
  3017. }
  3018. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3019. // With path encoding enabled a CR/LF in the target is percent-encoded
  3020. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3021. // write_request_line still backstops `set_path_encode(false)`, which is
  3022. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3023. Server svr;
  3024. // Captured before routing: the decoded path contains a newline, which a
  3025. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3026. std::string target;
  3027. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3028. target = req.target;
  3029. res.status = StatusCode::OK_200;
  3030. return Server::HandlerResponse::Handled;
  3031. });
  3032. auto port = svr.bind_to_any_port(HOST);
  3033. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3034. auto se = detail::scope_exit([&] {
  3035. svr.stop();
  3036. thread.join();
  3037. ASSERT_FALSE(svr.is_running());
  3038. });
  3039. svr.wait_until_ready();
  3040. {
  3041. Client cli(HOST, port);
  3042. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3043. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3044. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3045. }
  3046. }
  3047. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3048. // Nothing may reach the wire: a raw CR/LF target would split the request
  3049. // line and inject headers.
  3050. Server svr;
  3051. // Pre-routing so that "not called" means nothing reached the server at all,
  3052. // rather than merely failing to match a handler pattern.
  3053. auto handler_called = false;
  3054. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3055. handler_called = true;
  3056. res.status = StatusCode::OK_200;
  3057. return Server::HandlerResponse::Handled;
  3058. });
  3059. auto port = svr.bind_to_any_port(HOST);
  3060. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3061. auto se = detail::scope_exit([&] {
  3062. svr.stop();
  3063. thread.join();
  3064. ASSERT_FALSE(svr.is_running());
  3065. });
  3066. svr.wait_until_ready();
  3067. {
  3068. Client cli(HOST, port);
  3069. cli.set_path_encode(false);
  3070. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3071. EXPECT_FALSE(handle.is_valid());
  3072. EXPECT_EQ(Error::Write, handle.error);
  3073. EXPECT_FALSE(handler_called);
  3074. }
  3075. }
  3076. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3077. // Which of the two branches runs is decided by whether the query component
  3078. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3079. // an empty query and must still fall back to building one from
  3080. // `req.params`, while a non-empty query must win over `req.params`.
  3081. Server svr;
  3082. std::string target;
  3083. svr.Get("/foo", [&](const Request &req, Response &res) {
  3084. target = req.target;
  3085. res.status = StatusCode::OK_200;
  3086. });
  3087. auto port = svr.bind_to_any_port(HOST);
  3088. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3089. auto se = detail::scope_exit([&] {
  3090. svr.stop();
  3091. thread.join();
  3092. ASSERT_FALSE(svr.is_running());
  3093. });
  3094. svr.wait_until_ready();
  3095. {
  3096. // Trailing `?` -> empty query component -> `req.params` is used.
  3097. Client cli(HOST, port);
  3098. Request req;
  3099. req.method = "GET";
  3100. req.path = "/foo?";
  3101. req.params.emplace("a", "1");
  3102. target.clear();
  3103. auto res = cli.send(req);
  3104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3105. EXPECT_EQ("/foo?a=1", target);
  3106. }
  3107. {
  3108. // Non-empty query in `req.path` -> `req.params` is not appended.
  3109. Client cli(HOST, port);
  3110. Request req;
  3111. req.method = "GET";
  3112. req.path = "/foo?b=2";
  3113. req.params.emplace("a", "1");
  3114. target.clear();
  3115. auto res = cli.send(req);
  3116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3117. EXPECT_EQ("/foo?b=2", target);
  3118. }
  3119. }
  3120. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3121. Server svr;
  3122. svr.Get("/", [](const Request &req, Response &) {
  3123. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3124. });
  3125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3126. auto se = detail::scope_exit([&] {
  3127. svr.stop();
  3128. thread.join();
  3129. ASSERT_FALSE(svr.is_running());
  3130. });
  3131. svr.wait_until_ready();
  3132. {
  3133. Client cli(HOST, PORT);
  3134. cli.set_path_encode(false);
  3135. auto res = cli.Get("/?something=%0A");
  3136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3137. EXPECT_EQ(StatusCode::OK_200, res->status);
  3138. }
  3139. }
  3140. TEST(BindServerTest, BindDualStack) {
  3141. Server svr;
  3142. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3143. res.set_content("Hello World!", "text/plain");
  3144. });
  3145. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3146. auto se = detail::scope_exit([&] {
  3147. svr.stop();
  3148. thread.join();
  3149. ASSERT_FALSE(svr.is_running());
  3150. });
  3151. svr.wait_until_ready();
  3152. {
  3153. Client cli("127.0.0.1", PORT);
  3154. auto res = cli.Get("/1");
  3155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3156. EXPECT_EQ(StatusCode::OK_200, res->status);
  3157. EXPECT_EQ("Hello World!", res->body);
  3158. }
  3159. {
  3160. Client cli("::1", PORT);
  3161. auto res = cli.Get("/1");
  3162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3163. EXPECT_EQ(StatusCode::OK_200, res->status);
  3164. EXPECT_EQ("Hello World!", res->body);
  3165. }
  3166. }
  3167. TEST(BindServerTest, BindAndListenSeparately) {
  3168. Server svr;
  3169. int port = svr.bind_to_any_port("0.0.0.0");
  3170. ASSERT_TRUE(svr.is_valid());
  3171. ASSERT_TRUE(port > 0);
  3172. svr.stop();
  3173. }
  3174. // Reports whether anything is still listening on a loopback port. A plain
  3175. // connect() is used instead of a Client request because a socket left bound by
  3176. // mistake accepts the connection into its backlog and never answers, which
  3177. // would hang the test instead of failing it.
  3178. static bool is_loopback_port_accepting(int port) {
  3179. sockaddr_in addr{};
  3180. addr.sin_family = AF_INET;
  3181. addr.sin_port = htons(static_cast<uint16_t>(port));
  3182. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3183. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3184. EXPECT_NE(sock, INVALID_SOCKET);
  3185. if (sock == INVALID_SOCKET) { return false; }
  3186. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3187. static_cast<socklen_t>(sizeof(addr)));
  3188. detail::close_socket(sock);
  3189. return ret == 0;
  3190. }
  3191. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3192. Server svr;
  3193. auto port = svr.bind_to_any_port("127.0.0.1");
  3194. ASSERT_TRUE(port > 0);
  3195. svr.stop();
  3196. // bind_to_any_port() already called listen(2), so until stop() closed the
  3197. // descriptor the port kept accepting connections into the backlog. ASSERT
  3198. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3199. // below blocks forever in the accept loop.
  3200. ASSERT_FALSE(is_loopback_port_accepting(port));
  3201. // Nothing is left to accept on, so listen_after_bind() must report failure
  3202. // instead of returning success without ever serving.
  3203. EXPECT_FALSE(svr.listen_after_bind());
  3204. // The failed listen marks the server decommissioned, so a waiter returns
  3205. // instead of spinning forever.
  3206. svr.wait_until_ready();
  3207. }
  3208. #ifdef CPPHTTPLIB_SSL_ENABLED
  3209. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3210. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3211. CLIENT_CA_CERT_DIR);
  3212. int port = svr.bind_to_any_port("0.0.0.0");
  3213. ASSERT_TRUE(svr.is_valid());
  3214. ASSERT_TRUE(port > 0);
  3215. svr.stop();
  3216. }
  3217. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3218. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3219. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3220. int port = svr.bind_to_any_port("0.0.0.0");
  3221. ASSERT_TRUE(svr.is_valid());
  3222. ASSERT_TRUE(port > 0);
  3223. svr.stop();
  3224. }
  3225. TEST(BindServerTest, UpdateCertsPem) {
  3226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3227. int port = svr.bind_to_any_port("0.0.0.0");
  3228. ASSERT_TRUE(svr.is_valid());
  3229. ASSERT_TRUE(port > 0);
  3230. // Read PEM files
  3231. std::string cert_pem, key_pem, ca_pem;
  3232. read_file(SERVER_CERT_FILE, cert_pem);
  3233. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3234. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3235. // Update server certificates using PEM API
  3236. ASSERT_TRUE(
  3237. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3238. ASSERT_TRUE(svr.is_valid());
  3239. svr.stop();
  3240. }
  3241. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3242. // Start server with client CA (enables client auth)
  3243. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3244. ASSERT_TRUE(svr.is_valid());
  3245. bool handler_called = false;
  3246. svr.Get("/test", [&](const Request &req, Response &res) {
  3247. handler_called = true;
  3248. // Verify client certificate is present
  3249. auto cert = req.peer_cert();
  3250. EXPECT_TRUE(static_cast<bool>(cert));
  3251. res.set_content("ok", "text/plain");
  3252. });
  3253. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3254. auto se = detail::scope_exit([&] {
  3255. svr.stop();
  3256. t.join();
  3257. ASSERT_FALSE(svr.is_running());
  3258. });
  3259. svr.wait_until_ready();
  3260. // Read PEM files
  3261. std::string cert_pem, key_pem, ca_pem;
  3262. read_file(SERVER_CERT_FILE, cert_pem);
  3263. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3264. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3265. // Update server certificates and client CA using PEM API while server running
  3266. ASSERT_TRUE(
  3267. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3268. // Connect with client certificate
  3269. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3270. cli.enable_server_certificate_verification(false);
  3271. cli.set_connection_timeout(30);
  3272. auto res = cli.Get("/test");
  3273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3274. ASSERT_EQ(StatusCode::OK_200, res->status);
  3275. ASSERT_TRUE(handler_called);
  3276. EXPECT_EQ("ok", res->body);
  3277. }
  3278. #endif
  3279. TEST(ErrorHandlerTest, ContentLength) {
  3280. Server svr;
  3281. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3282. res.status = StatusCode::OK_200;
  3283. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3284. "text/html"); // <= Content-Length still 13
  3285. });
  3286. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3287. res.set_content("Hello World!\n", "text/plain");
  3288. res.status = 524;
  3289. });
  3290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3291. auto se = detail::scope_exit([&] {
  3292. svr.stop();
  3293. thread.join();
  3294. ASSERT_FALSE(svr.is_running());
  3295. });
  3296. svr.wait_until_ready();
  3297. {
  3298. Client cli(HOST, PORT);
  3299. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3301. EXPECT_EQ(StatusCode::OK_200, res->status);
  3302. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3303. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3305. }
  3306. }
  3307. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3308. TEST(ExceptionTest, WithoutExceptionHandler) {
  3309. Server svr;
  3310. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3311. throw std::runtime_error("exception...");
  3312. });
  3313. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3314. throw std::runtime_error("exception\r\n...");
  3315. });
  3316. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3317. auto se = detail::scope_exit([&] {
  3318. svr.stop();
  3319. listen_thread.join();
  3320. ASSERT_FALSE(svr.is_running());
  3321. });
  3322. svr.wait_until_ready();
  3323. Client cli("localhost", PORT);
  3324. {
  3325. auto res = cli.Get("/exception");
  3326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3327. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3328. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3329. }
  3330. {
  3331. auto res = cli.Get("/unknown");
  3332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3333. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3334. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3335. }
  3336. }
  3337. TEST(ExceptionTest, WithExceptionHandler) {
  3338. Server svr;
  3339. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3340. std::exception_ptr ep) {
  3341. EXPECT_FALSE(ep == nullptr);
  3342. try {
  3343. std::rethrow_exception(ep);
  3344. } catch (std::exception &e) {
  3345. EXPECT_EQ("abc", std::string(e.what()));
  3346. } catch (...) {}
  3347. res.status = StatusCode::InternalServerError_500;
  3348. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3349. "text/html"); // <= Content-Length still 13 at this point
  3350. });
  3351. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3352. res.set_content("Hello World!\n", "text/plain");
  3353. throw std::runtime_error("abc");
  3354. });
  3355. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3356. auto se = detail::scope_exit([&] {
  3357. svr.stop();
  3358. thread.join();
  3359. ASSERT_FALSE(svr.is_running());
  3360. });
  3361. svr.wait_until_ready();
  3362. for (size_t i = 0; i < 10; i++) {
  3363. Client cli(HOST, PORT);
  3364. for (size_t j = 0; j < 100; j++) {
  3365. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3367. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3368. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3369. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3370. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3371. }
  3372. cli.set_keep_alive(true);
  3373. for (size_t j = 0; j < 100; j++) {
  3374. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3376. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3377. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3378. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3379. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3380. }
  3381. }
  3382. }
  3383. TEST(ExceptionTest, AndErrorHandler) {
  3384. Server svr;
  3385. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3386. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3387. });
  3388. svr.set_exception_handler(
  3389. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3390. EXPECT_FALSE(ep == nullptr);
  3391. try {
  3392. std::rethrow_exception(ep);
  3393. } catch (std::exception &e) {
  3394. res.set_content(e.what(), "text/html");
  3395. } catch (...) {}
  3396. res.status = StatusCode::InternalServerError_500;
  3397. });
  3398. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3399. throw std::runtime_error("EXCEPTION");
  3400. });
  3401. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3402. res.set_content("ERROR", "text/html");
  3403. res.status = StatusCode::InternalServerError_500;
  3404. });
  3405. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3406. auto se = detail::scope_exit([&] {
  3407. svr.stop();
  3408. thread.join();
  3409. ASSERT_FALSE(svr.is_running());
  3410. });
  3411. svr.wait_until_ready();
  3412. Client cli(HOST, PORT);
  3413. {
  3414. auto res = cli.Get("/exception");
  3415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3416. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3417. EXPECT_EQ("EXCEPTION", res->body);
  3418. }
  3419. {
  3420. auto res = cli.Get("/error");
  3421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3422. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3423. EXPECT_EQ("ERROR", res->body);
  3424. }
  3425. {
  3426. auto res = cli.Get("/invalid");
  3427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3428. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3429. EXPECT_EQ("NOT_FOUND", res->body);
  3430. }
  3431. }
  3432. #endif
  3433. TEST(NoContentTest, ContentLength) {
  3434. Server svr;
  3435. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3436. res.status = StatusCode::NoContent_204;
  3437. });
  3438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3439. auto se = detail::scope_exit([&] {
  3440. svr.stop();
  3441. thread.join();
  3442. ASSERT_FALSE(svr.is_running());
  3443. });
  3444. svr.wait_until_ready();
  3445. {
  3446. Client cli(HOST, PORT);
  3447. auto res = cli.Get("/hi");
  3448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3449. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3450. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3451. }
  3452. }
  3453. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3454. #ifdef CPPHTTPLIB_SSL_ENABLED
  3455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3456. ASSERT_TRUE(svr.is_valid());
  3457. #else
  3458. Server svr;
  3459. #endif
  3460. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3461. if (req.path == "/routing_handler") {
  3462. res.set_header("PRE_ROUTING", "on");
  3463. res.set_content("Routing Handler", "text/plain");
  3464. return httplib::Server::HandlerResponse::Handled;
  3465. }
  3466. return httplib::Server::HandlerResponse::Unhandled;
  3467. });
  3468. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3469. res.set_content("Error", "text/html");
  3470. });
  3471. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3472. if (req.path == "/routing_handler") {
  3473. res.set_header("POST_ROUTING", "on");
  3474. }
  3475. });
  3476. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3477. res.set_content("Hello World!\n", "text/plain");
  3478. });
  3479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3480. auto se = detail::scope_exit([&] {
  3481. svr.stop();
  3482. thread.join();
  3483. ASSERT_FALSE(svr.is_running());
  3484. });
  3485. svr.wait_until_ready();
  3486. {
  3487. #ifdef CPPHTTPLIB_SSL_ENABLED
  3488. SSLClient cli(HOST, PORT);
  3489. cli.enable_server_certificate_verification(false);
  3490. #else
  3491. Client cli(HOST, PORT);
  3492. #endif
  3493. auto res = cli.Get("/routing_handler");
  3494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3495. EXPECT_EQ(StatusCode::OK_200, res->status);
  3496. EXPECT_EQ("Routing Handler", res->body);
  3497. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3498. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3499. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3500. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3501. }
  3502. {
  3503. #ifdef CPPHTTPLIB_SSL_ENABLED
  3504. SSLClient cli(HOST, PORT);
  3505. cli.enable_server_certificate_verification(false);
  3506. #else
  3507. Client cli(HOST, PORT);
  3508. #endif
  3509. auto res = cli.Get("/hi");
  3510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3511. EXPECT_EQ(StatusCode::OK_200, res->status);
  3512. EXPECT_EQ("Hello World!\n", res->body);
  3513. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3514. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3515. }
  3516. {
  3517. #ifdef CPPHTTPLIB_SSL_ENABLED
  3518. SSLClient cli(HOST, PORT);
  3519. cli.enable_server_certificate_verification(false);
  3520. #else
  3521. Client cli(HOST, PORT);
  3522. #endif
  3523. auto res = cli.Get("/aaa");
  3524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3526. EXPECT_EQ("Error", res->body);
  3527. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3528. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3529. }
  3530. }
  3531. TEST(RequestHandlerTest, PreRequestHandler) {
  3532. auto route_path = "/user/:user";
  3533. Server svr;
  3534. svr.Get("/hi", [](const Request &, Response &res) {
  3535. res.set_content("hi", "text/plain");
  3536. });
  3537. svr.Get(route_path, [](const Request &req, Response &res) {
  3538. res.set_content(req.path_params.at("user"), "text/plain");
  3539. });
  3540. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3541. if (req.matched_route == route_path) {
  3542. auto user = req.path_params.at("user");
  3543. if (user != "john") {
  3544. res.status = StatusCode::Forbidden_403;
  3545. res.set_content("error", "text/html");
  3546. return Server::HandlerResponse::Handled;
  3547. }
  3548. }
  3549. return Server::HandlerResponse::Unhandled;
  3550. });
  3551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3552. auto se = detail::scope_exit([&] {
  3553. svr.stop();
  3554. thread.join();
  3555. ASSERT_FALSE(svr.is_running());
  3556. });
  3557. svr.wait_until_ready();
  3558. Client cli(HOST, PORT);
  3559. {
  3560. auto res = cli.Get("/hi");
  3561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3562. EXPECT_EQ(StatusCode::OK_200, res->status);
  3563. EXPECT_EQ("hi", res->body);
  3564. }
  3565. {
  3566. auto res = cli.Get("/user/john");
  3567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3568. EXPECT_EQ(StatusCode::OK_200, res->status);
  3569. EXPECT_EQ("john", res->body);
  3570. }
  3571. {
  3572. auto res = cli.Get("/user/invalid-user");
  3573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3574. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3575. EXPECT_EQ("error", res->body);
  3576. }
  3577. }
  3578. // The pre-request handler must run before the request body is read, so a
  3579. // rejected request never forces the server to buffer a (potentially large)
  3580. // body. Here the posted body is larger than the payload limit: if the body
  3581. // were read first the server would answer 413, but because the pre-request
  3582. // handler runs first it answers 403 and the body is never read.
  3583. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3584. Server svr;
  3585. svr.set_payload_max_length(8);
  3586. auto handler_ran = false;
  3587. svr.Post("/reject", [&](const Request &req, Response &res) {
  3588. handler_ran = true;
  3589. res.set_content(req.body, "text/plain");
  3590. });
  3591. svr.Post("/accept", [](const Request &req, Response &res) {
  3592. res.set_content(req.body, "text/plain");
  3593. });
  3594. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3595. if (req.matched_route == "/reject") {
  3596. res.status = StatusCode::Forbidden_403;
  3597. res.set_content("denied", "text/plain");
  3598. return Server::HandlerResponse::Handled;
  3599. }
  3600. return Server::HandlerResponse::Unhandled;
  3601. });
  3602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3603. auto se = detail::scope_exit([&] {
  3604. svr.stop();
  3605. thread.join();
  3606. ASSERT_FALSE(svr.is_running());
  3607. });
  3608. svr.wait_until_ready();
  3609. Client cli(HOST, PORT);
  3610. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3611. // rejects with 403 before the body is read, so 413 is never reached.
  3612. {
  3613. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3615. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3616. EXPECT_EQ("denied", res->body);
  3617. EXPECT_FALSE(handler_ran);
  3618. }
  3619. // An approved route still reads the body and enforces the payload limit.
  3620. {
  3621. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3623. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3624. }
  3625. }
  3626. TEST(UserDataTest, BasicOperations) {
  3627. httplib::UserData ud;
  3628. // Initially empty
  3629. EXPECT_FALSE(ud.has("key"));
  3630. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3631. // set and get
  3632. ud.set("key", 42);
  3633. EXPECT_TRUE(ud.has("key"));
  3634. auto *p = ud.get<int>("key");
  3635. ASSERT_NE(nullptr, p);
  3636. EXPECT_EQ(42, *p);
  3637. // Type mismatch → nullptr
  3638. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3639. // Overwrite with different type
  3640. ud.set("key", std::string("hello"));
  3641. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3642. auto *s = ud.get<std::string>("key");
  3643. ASSERT_NE(nullptr, s);
  3644. EXPECT_EQ("hello", *s);
  3645. // erase
  3646. ud.erase("key");
  3647. EXPECT_FALSE(ud.has("key"));
  3648. // clear
  3649. ud.set("a", 1);
  3650. ud.set("b", 2);
  3651. ud.clear();
  3652. EXPECT_FALSE(ud.has("a"));
  3653. EXPECT_FALSE(ud.has("b"));
  3654. }
  3655. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3656. struct AuthCtx {
  3657. std::string user_id;
  3658. };
  3659. Server svr;
  3660. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3661. res.user_data.set("auth", AuthCtx{"alice"});
  3662. return Server::HandlerResponse::Unhandled;
  3663. });
  3664. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3665. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3666. ASSERT_NE(nullptr, ctx);
  3667. res.set_content("Hello " + ctx->user_id, "text/plain");
  3668. });
  3669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3670. auto se = detail::scope_exit([&] {
  3671. svr.stop();
  3672. thread.join();
  3673. ASSERT_FALSE(svr.is_running());
  3674. });
  3675. svr.wait_until_ready();
  3676. Client cli(HOST, PORT);
  3677. auto res = cli.Get("/me");
  3678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3679. EXPECT_EQ(StatusCode::OK_200, res->status);
  3680. EXPECT_EQ("Hello alice", res->body);
  3681. }
  3682. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3683. struct RoleCtx {
  3684. std::string role;
  3685. };
  3686. Server svr;
  3687. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3688. res.user_data.set("role", RoleCtx{"admin"});
  3689. return Server::HandlerResponse::Unhandled;
  3690. });
  3691. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3692. auto *ctx = res.user_data.get<RoleCtx>("role");
  3693. ASSERT_NE(nullptr, ctx);
  3694. res.set_content(ctx->role, "text/plain");
  3695. });
  3696. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3697. auto se = detail::scope_exit([&] {
  3698. svr.stop();
  3699. thread.join();
  3700. ASSERT_FALSE(svr.is_running());
  3701. });
  3702. svr.wait_until_ready();
  3703. Client cli(HOST, PORT);
  3704. auto res = cli.Get("/role");
  3705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3706. EXPECT_EQ(StatusCode::OK_200, res->status);
  3707. EXPECT_EQ("admin", res->body);
  3708. }
  3709. TEST(InvalidFormatTest, StatusCode) {
  3710. Server svr;
  3711. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3712. res.set_content("Hello World!\n", "text/plain");
  3713. res.status = 9999; // Status should be a three-digit code...
  3714. });
  3715. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3716. auto se = detail::scope_exit([&] {
  3717. svr.stop();
  3718. thread.join();
  3719. ASSERT_FALSE(svr.is_running());
  3720. });
  3721. svr.wait_until_ready();
  3722. {
  3723. Client cli(HOST, PORT);
  3724. auto res = cli.Get("/hi");
  3725. ASSERT_FALSE(res);
  3726. }
  3727. }
  3728. TEST(URLFragmentTest, WithFragment) {
  3729. Server svr;
  3730. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3731. EXPECT_TRUE(req.target == "/hi");
  3732. });
  3733. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3734. auto se = detail::scope_exit([&] {
  3735. svr.stop();
  3736. thread.join();
  3737. ASSERT_FALSE(svr.is_running());
  3738. });
  3739. svr.wait_until_ready();
  3740. {
  3741. Client cli(HOST, PORT);
  3742. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3743. EXPECT_TRUE(res);
  3744. EXPECT_EQ(StatusCode::OK_200, res->status);
  3745. res = cli.Get("/hi%23key1=val1=key2=val2");
  3746. EXPECT_TRUE(res);
  3747. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. }
  3750. TEST(HeaderWriter, SetHeaderWriter) {
  3751. Server svr;
  3752. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3753. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3754. return detail::write_headers(strm, hdrs);
  3755. });
  3756. svr.Get("/hi", [](const Request &req, Response &res) {
  3757. auto it = req.headers.find("CustomClientHeader");
  3758. EXPECT_TRUE(it != req.headers.end());
  3759. EXPECT_EQ(it->second, "CustomClientValue");
  3760. res.set_content("Hello World!\n", "text/plain");
  3761. });
  3762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3763. auto se = detail::scope_exit([&] {
  3764. svr.stop();
  3765. thread.join();
  3766. ASSERT_FALSE(svr.is_running());
  3767. });
  3768. svr.wait_until_ready();
  3769. {
  3770. Client cli(HOST, PORT);
  3771. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3772. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3773. return detail::write_headers(strm, hdrs);
  3774. });
  3775. auto res = cli.Get("/hi");
  3776. EXPECT_TRUE(res);
  3777. EXPECT_EQ(StatusCode::OK_200, res->status);
  3778. auto it = res->headers.find("CustomServerHeader");
  3779. EXPECT_TRUE(it != res->headers.end());
  3780. EXPECT_EQ(it->second, "CustomServerValue");
  3781. }
  3782. }
  3783. class ServerTest : public ::testing::Test {
  3784. protected:
  3785. ServerTest()
  3786. : cli_(HOST, PORT)
  3787. #ifdef CPPHTTPLIB_SSL_ENABLED
  3788. ,
  3789. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3790. #endif
  3791. {
  3792. #ifdef CPPHTTPLIB_SSL_ENABLED
  3793. cli_.enable_server_certificate_verification(false);
  3794. #endif
  3795. // Allow LARGE_DATA (100MB) responses
  3796. cli_.set_payload_max_length(200 * 1024 * 1024);
  3797. }
  3798. virtual void SetUp() {
  3799. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3800. svr_.set_payload_max_length(200 * 1024 * 1024);
  3801. svr_.set_mount_point("/", "./www");
  3802. svr_.set_mount_point("/mount", "./www2");
  3803. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3804. svr_.Get("/hi",
  3805. [&](const Request & /*req*/, Response &res) {
  3806. res.set_content("Hello World!", "text/plain");
  3807. })
  3808. .Get("/file_content",
  3809. [&](const Request & /*req*/, Response &res) {
  3810. res.set_file_content("./www/dir/test.html");
  3811. })
  3812. .Get("/file_content_with_content_type",
  3813. [&](const Request & /*req*/, Response &res) {
  3814. res.set_file_content("./www/file", "text/plain");
  3815. })
  3816. .Get("/invalid_file_content",
  3817. [&](const Request & /*req*/, Response &res) {
  3818. res.set_file_content("./www/dir/invalid_file_path");
  3819. })
  3820. .Get("/http_response_splitting",
  3821. [&](const Request & /*req*/, Response &res) {
  3822. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3823. EXPECT_EQ(0U, res.headers.size());
  3824. EXPECT_FALSE(res.has_header("a"));
  3825. res.set_header("a", "1\nSet-Cookie: a=1");
  3826. EXPECT_EQ(0U, res.headers.size());
  3827. EXPECT_FALSE(res.has_header("a"));
  3828. res.set_header("a", "1\rSet-Cookie: a=1");
  3829. EXPECT_EQ(0U, res.headers.size());
  3830. EXPECT_FALSE(res.has_header("a"));
  3831. res.set_header("a\r\nb", "0");
  3832. EXPECT_EQ(0U, res.headers.size());
  3833. EXPECT_FALSE(res.has_header("a"));
  3834. res.set_header("a\rb", "0");
  3835. EXPECT_EQ(0U, res.headers.size());
  3836. EXPECT_FALSE(res.has_header("a"));
  3837. res.set_header("a\nb", "0");
  3838. EXPECT_EQ(0U, res.headers.size());
  3839. EXPECT_FALSE(res.has_header("a"));
  3840. res.set_redirect("1\r\nSet-Cookie: a=1");
  3841. EXPECT_EQ(0U, res.headers.size());
  3842. EXPECT_FALSE(res.has_header("Location"));
  3843. })
  3844. .Get("/slow",
  3845. [&](const Request & /*req*/, Response &res) {
  3846. std::this_thread::sleep_for(std::chrono::seconds(4));
  3847. res.set_content("slow", "text/plain");
  3848. })
  3849. #if 0
  3850. .Post("/slowpost",
  3851. [&](const Request & /*req*/, Response &res) {
  3852. std::this_thread::sleep_for(std::chrono::seconds(2));
  3853. res.set_content("slow", "text/plain");
  3854. })
  3855. #endif
  3856. .Get("/remote_addr",
  3857. [&](const Request &req, Response &res) {
  3858. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3859. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3860. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3861. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3862. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3863. #endif
  3864. res.set_content(req.remote_addr, "text/plain");
  3865. })
  3866. .Get("/local_addr",
  3867. [&](const Request &req, Response &res) {
  3868. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3869. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3870. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3871. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3872. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3873. #endif
  3874. auto local_addr = req.local_addr;
  3875. auto local_port = std::to_string(req.local_port);
  3876. res.set_content(local_addr.append(":").append(local_port),
  3877. "text/plain");
  3878. })
  3879. .Get("/endwith%",
  3880. [&](const Request & /*req*/, Response &res) {
  3881. res.set_content("Hello World!", "text/plain");
  3882. })
  3883. .Get("/a\\+\\+b",
  3884. [&](const Request &req, Response &res) {
  3885. ASSERT_TRUE(req.has_param("a +b"));
  3886. auto val = req.get_param_value("a +b");
  3887. res.set_content(val, "text/plain");
  3888. })
  3889. .Get("/", [&](const Request & /*req*/,
  3890. Response &res) { res.set_redirect("/hi"); })
  3891. .Post("/1",
  3892. [](const Request & /*req*/, Response &res) {
  3893. res.set_redirect("/2", StatusCode::SeeOther_303);
  3894. })
  3895. .Get("/2",
  3896. [](const Request & /*req*/, Response &res) {
  3897. res.set_content("redirected.", "text/plain");
  3898. res.status = StatusCode::OK_200;
  3899. })
  3900. .Post("/person",
  3901. [&](const Request &req, Response &res) {
  3902. if (req.has_param("name") && req.has_param("note")) {
  3903. persons_[req.get_param_value("name")] =
  3904. req.get_param_value("note");
  3905. } else {
  3906. res.status = StatusCode::BadRequest_400;
  3907. }
  3908. })
  3909. .Put("/person",
  3910. [&](const Request &req, Response &res) {
  3911. if (req.has_param("name") && req.has_param("note")) {
  3912. persons_[req.get_param_value("name")] =
  3913. req.get_param_value("note");
  3914. } else {
  3915. res.status = StatusCode::BadRequest_400;
  3916. }
  3917. })
  3918. .Get("/person/(.*)",
  3919. [&](const Request &req, Response &res) {
  3920. string name = req.matches[1];
  3921. if (persons_.find(name) != persons_.end()) {
  3922. auto note = persons_[name];
  3923. res.set_content(note, "text/plain");
  3924. } else {
  3925. res.status = StatusCode::NotFound_404;
  3926. }
  3927. })
  3928. .Delete("/person",
  3929. [&](const Request &req, Response &res) {
  3930. if (req.has_param("name")) {
  3931. string name = req.get_param_value("name");
  3932. if (persons_.find(name) != persons_.end()) {
  3933. persons_.erase(name);
  3934. res.set_content("DELETED", "text/plain");
  3935. } else {
  3936. res.status = StatusCode::NotFound_404;
  3937. }
  3938. } else {
  3939. res.status = StatusCode::BadRequest_400;
  3940. }
  3941. })
  3942. .Post("/x-www-form-urlencoded-json",
  3943. [&](const Request &req, Response &res) {
  3944. auto json = req.get_param_value("json");
  3945. ASSERT_EQ(JSON_DATA, json);
  3946. res.set_content(json, "appliation/json");
  3947. res.status = StatusCode::OK_200;
  3948. })
  3949. .Get("/streamed-chunked",
  3950. [&](const Request & /*req*/, Response &res) {
  3951. res.set_chunked_content_provider(
  3952. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3953. sink.os << "123";
  3954. sink.os << "456";
  3955. sink.os << "789";
  3956. sink.done();
  3957. return true;
  3958. });
  3959. })
  3960. .Get("/streamed-chunked-with-prohibited-trailer",
  3961. [&](const Request & /*req*/, Response &res) {
  3962. auto i = new int(0);
  3963. // Declare both a prohibited trailer (Content-Length) and an
  3964. // allowed one
  3965. res.set_header("Trailer", "Content-Length, X-Allowed");
  3966. res.set_chunked_content_provider(
  3967. "text/plain",
  3968. [i](size_t /*offset*/, DataSink &sink) {
  3969. switch (*i) {
  3970. case 0: sink.os << "123"; break;
  3971. case 1: sink.os << "456"; break;
  3972. case 2: sink.os << "789"; break;
  3973. case 3: {
  3974. sink.done_with_trailer(
  3975. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3976. } break;
  3977. }
  3978. (*i)++;
  3979. return true;
  3980. },
  3981. [i](bool success) {
  3982. EXPECT_TRUE(success);
  3983. delete i;
  3984. });
  3985. })
  3986. .Get("/streamed-chunked2",
  3987. [&](const Request & /*req*/, Response &res) {
  3988. auto i = new int(0);
  3989. res.set_chunked_content_provider(
  3990. "text/plain",
  3991. [i](size_t /*offset*/, DataSink &sink) {
  3992. switch (*i) {
  3993. case 0: sink.os << "123"; break;
  3994. case 1: sink.os << "456"; break;
  3995. case 2: sink.os << "789"; break;
  3996. case 3: sink.done(); break;
  3997. }
  3998. (*i)++;
  3999. return true;
  4000. },
  4001. [i](bool success) {
  4002. EXPECT_TRUE(success);
  4003. delete i;
  4004. });
  4005. })
  4006. .Get("/streamed-chunked-with-trailer",
  4007. [&](const Request & /*req*/, Response &res) {
  4008. auto i = new int(0);
  4009. res.set_header("Trailer", "Dummy1, Dummy2");
  4010. res.set_chunked_content_provider(
  4011. "text/plain",
  4012. [i](size_t /*offset*/, DataSink &sink) {
  4013. switch (*i) {
  4014. case 0: sink.os << "123"; break;
  4015. case 1: sink.os << "456"; break;
  4016. case 2: sink.os << "789"; break;
  4017. case 3: {
  4018. sink.done_with_trailer(
  4019. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4020. } break;
  4021. }
  4022. (*i)++;
  4023. return true;
  4024. },
  4025. [i](bool success) {
  4026. EXPECT_TRUE(success);
  4027. delete i;
  4028. });
  4029. })
  4030. .Get("/streamed",
  4031. [&](const Request & /*req*/, Response &res) {
  4032. res.set_content_provider(
  4033. 6, "text/plain",
  4034. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4035. sink.os << (offset < 3 ? "a" : "b");
  4036. return true;
  4037. });
  4038. })
  4039. .Get("/streamed-without-length",
  4040. [&](const Request & /*req*/, Response &res) {
  4041. auto data = new std::string("abcdefg");
  4042. res.set_content_provider(
  4043. "text/plain",
  4044. [data](size_t offset, DataSink &sink) {
  4045. if (offset < data->size()) {
  4046. sink.os << data->substr(offset);
  4047. }
  4048. sink.done();
  4049. return true;
  4050. },
  4051. [data](bool success) {
  4052. EXPECT_TRUE(success);
  4053. delete data;
  4054. });
  4055. })
  4056. .Get("/streamed-with-range",
  4057. [&](const Request &req, Response &res) {
  4058. auto data = new std::string("abcdefg");
  4059. // An explicit status keeps the server from picking the 206 it
  4060. // would otherwise choose for a ranged request, so the response
  4061. // is not a partial representation.
  4062. auto status = req.get_param_value("status");
  4063. if (status == "200") {
  4064. res.status = StatusCode::OK_200;
  4065. } else if (status == "403") {
  4066. res.status = StatusCode::Forbidden_403;
  4067. }
  4068. res.set_content_provider(
  4069. data->size(), "text/plain",
  4070. [data](size_t offset, size_t length, DataSink &sink) {
  4071. size_t DATA_CHUNK_SIZE = 4;
  4072. const auto &d = *data;
  4073. auto out_len =
  4074. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4075. auto ret =
  4076. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4077. EXPECT_TRUE(ret);
  4078. return true;
  4079. },
  4080. [data, &req](bool success) {
  4081. EXPECT_EQ(success, !req.has_param("error"));
  4082. delete data;
  4083. });
  4084. })
  4085. .Get("/streamed-cancel",
  4086. [&](const Request & /*req*/, Response &res) {
  4087. res.set_content_provider(
  4088. size_t(-1), "text/plain",
  4089. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4090. sink.os << "data_chunk";
  4091. return true;
  4092. });
  4093. })
  4094. .Get("/regex-with-delimiter",
  4095. [&](const Request &req, Response & /*res*/) {
  4096. ASSERT_TRUE(req.has_param("key"));
  4097. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4098. })
  4099. .Get("/with-range",
  4100. [&](const Request & /*req*/, Response &res) {
  4101. res.set_content("abcdefg", "text/plain");
  4102. })
  4103. .Get("/test-start-time",
  4104. [&](const Request &req, Response & /*res*/) {
  4105. EXPECT_NE(req.start_time_,
  4106. std::chrono::steady_clock::time_point::min());
  4107. })
  4108. .Get("/with-range-customized-response",
  4109. [&](const Request & /*req*/, Response &res) {
  4110. res.status = StatusCode::BadRequest_400;
  4111. res.set_content(JSON_DATA, "application/json");
  4112. })
  4113. .Post("/chunked",
  4114. [&](const Request &req, Response & /*res*/) {
  4115. EXPECT_EQ(req.body, "dechunked post body");
  4116. })
  4117. .Post("/large-chunked",
  4118. [&](const Request &req, Response & /*res*/) {
  4119. std::string expected(6 * 30 * 1024u, 'a');
  4120. EXPECT_EQ(req.body, expected);
  4121. })
  4122. .Post("/multipart",
  4123. [&](const Request &req, Response & /*res*/) {
  4124. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4125. req.form.get_field_count("text2") +
  4126. req.form.get_field_count("file3") +
  4127. req.form.get_field_count("file4"));
  4128. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4129. req.form.get_file_count("file2"));
  4130. ASSERT_TRUE(!req.form.has_file("???"));
  4131. ASSERT_TRUE(!req.form.has_field("???"));
  4132. ASSERT_TRUE(req.body.empty());
  4133. {
  4134. const auto &text = req.form.get_field("text1");
  4135. EXPECT_EQ("text default", text);
  4136. }
  4137. {
  4138. const auto &text = req.form.get_field("text2");
  4139. EXPECT_EQ("aωb", text);
  4140. }
  4141. {
  4142. const auto &file = req.form.get_file("file1");
  4143. EXPECT_EQ("hello.txt", file.filename);
  4144. EXPECT_EQ("text/plain", file.content_type);
  4145. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4146. }
  4147. {
  4148. const auto &file = req.form.get_file("file2");
  4149. EXPECT_EQ("world.json", file.filename);
  4150. EXPECT_EQ("application/json", file.content_type);
  4151. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4152. }
  4153. {
  4154. const auto &text = req.form.get_field("file3");
  4155. EXPECT_EQ(0u, text.size());
  4156. }
  4157. {
  4158. const auto &text = req.form.get_field("file4");
  4159. EXPECT_EQ(0u, text.size());
  4160. }
  4161. })
  4162. .Post("/multipart/multi_file_values",
  4163. [&](const Request &req, Response & /*res*/) {
  4164. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4165. req.form.get_field_count("multi_text1"));
  4166. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4167. ASSERT_TRUE(!req.form.has_file("???"));
  4168. ASSERT_TRUE(!req.form.has_field("???"));
  4169. ASSERT_TRUE(req.body.empty());
  4170. {
  4171. const auto &text = req.form.get_field("text");
  4172. EXPECT_EQ("default text", text);
  4173. }
  4174. {
  4175. const auto &text1_values = req.form.get_fields("multi_text1");
  4176. EXPECT_EQ(2u, text1_values.size());
  4177. EXPECT_EQ("aaaaa", text1_values[0]);
  4178. EXPECT_EQ("bbbbb", text1_values[1]);
  4179. }
  4180. {
  4181. const auto &file1_values = req.form.get_files("multi_file1");
  4182. EXPECT_EQ(2u, file1_values.size());
  4183. auto file1 = file1_values[0];
  4184. EXPECT_EQ(file1.filename, "hello.txt");
  4185. EXPECT_EQ(file1.content_type, "text/plain");
  4186. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4187. auto file2 = file1_values[1];
  4188. EXPECT_EQ(file2.filename, "world.json");
  4189. EXPECT_EQ(file2.content_type, "application/json");
  4190. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4191. }
  4192. })
  4193. .Post("/empty",
  4194. [&](const Request &req, Response &res) {
  4195. EXPECT_EQ(req.body, "");
  4196. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4197. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4198. res.set_content("empty", "text/plain");
  4199. })
  4200. .Post("/empty-no-content-type",
  4201. [&](const Request &req, Response &res) {
  4202. EXPECT_EQ(req.body, "");
  4203. EXPECT_FALSE(req.has_header("Content-Type"));
  4204. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4205. res.set_content("empty-no-content-type", "text/plain");
  4206. })
  4207. .Post("/path-only",
  4208. [&](const Request &req, Response &res) {
  4209. EXPECT_EQ(req.body, "");
  4210. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4211. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4212. res.set_content("path-only", "text/plain");
  4213. })
  4214. .Post("/path-headers-only",
  4215. [&](const Request &req, Response &res) {
  4216. EXPECT_EQ(req.body, "");
  4217. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4218. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4219. EXPECT_EQ("world", req.get_header_value("hello"));
  4220. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4221. res.set_content("path-headers-only", "text/plain");
  4222. })
  4223. .Post("/post-large",
  4224. [&](const Request &req, Response &res) {
  4225. EXPECT_EQ(req.body, LARGE_DATA);
  4226. res.set_content(req.body, "text/plain");
  4227. })
  4228. .Post("/post-loopback",
  4229. [&](const Request &, Response &res,
  4230. ContentReader const &content_reader) {
  4231. std::string body;
  4232. content_reader([&](const char *data, size_t data_length) {
  4233. body.append(data, data_length);
  4234. return true;
  4235. });
  4236. res.set_content(body, "text/plain");
  4237. })
  4238. .Put("/put-loopback",
  4239. [&](const Request &, Response &res,
  4240. ContentReader const &content_reader) {
  4241. std::string body;
  4242. content_reader([&](const char *data, size_t data_length) {
  4243. body.append(data, data_length);
  4244. return true;
  4245. });
  4246. res.set_content(body, "text/plain");
  4247. })
  4248. .Patch("/patch-loopback",
  4249. [&](const Request &, Response &res,
  4250. ContentReader const &content_reader) {
  4251. std::string body;
  4252. content_reader([&](const char *data, size_t data_length) {
  4253. body.append(data, data_length);
  4254. return true;
  4255. });
  4256. res.set_content(body, "text/plain");
  4257. })
  4258. .Put("/empty-no-content-type",
  4259. [&](const Request &req, Response &res) {
  4260. EXPECT_EQ(req.body, "");
  4261. EXPECT_FALSE(req.has_header("Content-Type"));
  4262. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4263. res.set_content("empty-no-content-type", "text/plain");
  4264. })
  4265. .Put("/put",
  4266. [&](const Request &req, Response &res) {
  4267. EXPECT_EQ(req.body, "PUT");
  4268. res.set_content(req.body, "text/plain");
  4269. })
  4270. .Put("/put-large",
  4271. [&](const Request &req, Response &res) {
  4272. EXPECT_EQ(req.body, LARGE_DATA);
  4273. res.set_content(req.body, "text/plain");
  4274. })
  4275. .Patch("/patch",
  4276. [&](const Request &req, Response &res) {
  4277. EXPECT_EQ(req.body, "PATCH");
  4278. res.set_content(req.body, "text/plain");
  4279. })
  4280. .Delete("/delete",
  4281. [&](const Request & /*req*/, Response &res) {
  4282. res.set_content("DELETE", "text/plain");
  4283. })
  4284. .Delete("/delete-body",
  4285. [&](const Request &req, Response &res) {
  4286. EXPECT_EQ(req.body, "content");
  4287. res.set_content(req.body, "text/plain");
  4288. })
  4289. .Options(R"(\*)",
  4290. [&](const Request & /*req*/, Response &res) {
  4291. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4292. })
  4293. .Get("/request-target",
  4294. [&](const Request &req, Response & /*res*/) {
  4295. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4296. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4297. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4298. })
  4299. .Get("/long-query-value",
  4300. [&](const Request &req, Response & /*res*/) {
  4301. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4302. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4303. })
  4304. .Get("/too-long-query-value",
  4305. [&](const Request &req, Response & /*res*/) {
  4306. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4307. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4308. })
  4309. .Get("/array-param",
  4310. [&](const Request &req, Response & /*res*/) {
  4311. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4312. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4313. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4314. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4315. })
  4316. .Get("/array-param-values",
  4317. [&](const Request &req, Response & /*res*/) {
  4318. auto values = req.get_param_values("array");
  4319. EXPECT_EQ(3u, values.size());
  4320. EXPECT_EQ("value1", values[0]);
  4321. EXPECT_EQ("value2", values[1]);
  4322. EXPECT_EQ("value3", values[2]);
  4323. auto empty = req.get_param_values("nonexistent");
  4324. EXPECT_TRUE(empty.empty());
  4325. })
  4326. .Post("/validate-no-multiple-headers",
  4327. [&](const Request &req, Response & /*res*/) {
  4328. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4329. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4330. })
  4331. .Post("/content_receiver",
  4332. [&](const Request &req, Response &res,
  4333. const ContentReader &content_reader) {
  4334. if (req.is_multipart_form_data()) {
  4335. std::vector<FormData> items;
  4336. content_reader(
  4337. [&](const FormData &file) {
  4338. items.push_back(file);
  4339. return true;
  4340. },
  4341. [&](const char *data, size_t data_length) {
  4342. items.back().content.append(data, data_length);
  4343. return true;
  4344. });
  4345. EXPECT_EQ(5u, items.size());
  4346. {
  4347. const auto &file = get_file_value(items, "text1");
  4348. EXPECT_TRUE(file.filename.empty());
  4349. EXPECT_EQ("text default", file.content);
  4350. }
  4351. {
  4352. const auto &file = get_file_value(items, "text2");
  4353. EXPECT_TRUE(file.filename.empty());
  4354. EXPECT_EQ("aωb", file.content);
  4355. }
  4356. {
  4357. const auto &file = get_file_value(items, "file1");
  4358. EXPECT_EQ("hello.txt", file.filename);
  4359. EXPECT_EQ("text/plain", file.content_type);
  4360. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4361. }
  4362. {
  4363. const auto &file = get_file_value(items, "file2");
  4364. EXPECT_EQ("world.json", file.filename);
  4365. EXPECT_EQ("application/json", file.content_type);
  4366. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4367. }
  4368. {
  4369. const auto &file = get_file_value(items, "file3");
  4370. EXPECT_TRUE(file.filename.empty());
  4371. EXPECT_EQ("application/octet-stream", file.content_type);
  4372. EXPECT_EQ(0u, file.content.size());
  4373. }
  4374. } else {
  4375. std::string body;
  4376. content_reader([&](const char *data, size_t data_length) {
  4377. EXPECT_EQ(7U, data_length);
  4378. body.append(data, data_length);
  4379. return true;
  4380. });
  4381. EXPECT_EQ(body, "content");
  4382. res.set_content(body, "text/plain");
  4383. }
  4384. })
  4385. .Put("/content_receiver",
  4386. [&](const Request & /*req*/, Response &res,
  4387. const ContentReader &content_reader) {
  4388. std::string body;
  4389. content_reader([&](const char *data, size_t data_length) {
  4390. body.append(data, data_length);
  4391. return true;
  4392. });
  4393. EXPECT_EQ(body, "content");
  4394. res.set_content(body, "text/plain");
  4395. })
  4396. .Patch("/content_receiver",
  4397. [&](const Request & /*req*/, Response &res,
  4398. const ContentReader &content_reader) {
  4399. std::string body;
  4400. content_reader([&](const char *data, size_t data_length) {
  4401. body.append(data, data_length);
  4402. return true;
  4403. });
  4404. EXPECT_EQ(body, "content");
  4405. res.set_content(body, "text/plain");
  4406. })
  4407. .Post("/query-string-and-body",
  4408. [&](const Request &req, Response & /*res*/) {
  4409. ASSERT_TRUE(req.has_param("key"));
  4410. EXPECT_EQ(req.get_param_value("key"), "value");
  4411. EXPECT_EQ(req.body, "content");
  4412. })
  4413. .Get("/last-request",
  4414. [&](const Request &req, Response & /*res*/) {
  4415. EXPECT_EQ("close", req.get_header_value("Connection"));
  4416. })
  4417. .Get(R"(/redirect/(\d+))",
  4418. [&](const Request &req, Response &res) {
  4419. auto num = std::stoi(req.matches[1]) + 1;
  4420. std::string url = "/redirect/" + std::to_string(num);
  4421. res.set_redirect(url);
  4422. })
  4423. .Post("/binary",
  4424. [&](const Request &req, Response &res) {
  4425. EXPECT_EQ(4U, req.body.size());
  4426. EXPECT_EQ("application/octet-stream",
  4427. req.get_header_value("Content-Type"));
  4428. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4429. res.set_content(req.body, "application/octet-stream");
  4430. })
  4431. .Put("/binary",
  4432. [&](const Request &req, Response &res) {
  4433. EXPECT_EQ(4U, req.body.size());
  4434. EXPECT_EQ("application/octet-stream",
  4435. req.get_header_value("Content-Type"));
  4436. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4437. res.set_content(req.body, "application/octet-stream");
  4438. })
  4439. .Patch("/binary",
  4440. [&](const Request &req, Response &res) {
  4441. EXPECT_EQ(4U, req.body.size());
  4442. EXPECT_EQ("application/octet-stream",
  4443. req.get_header_value("Content-Type"));
  4444. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4445. res.set_content(req.body, "application/octet-stream");
  4446. })
  4447. .Delete("/binary",
  4448. [&](const Request &req, Response &res) {
  4449. EXPECT_EQ(4U, req.body.size());
  4450. EXPECT_EQ("application/octet-stream",
  4451. req.get_header_value("Content-Type"));
  4452. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4453. res.set_content(req.body, "application/octet-stream");
  4454. })
  4455. .Get("/issue1772",
  4456. [&](const Request & /*req*/, Response &res) {
  4457. res.status = 401;
  4458. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4459. })
  4460. .Delete("/issue609",
  4461. [](const httplib::Request &, httplib::Response &res,
  4462. const httplib::ContentReader &) {
  4463. res.set_content("ok", "text/plain");
  4464. })
  4465. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4466. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4467. .Get("/compress",
  4468. [&](const Request & /*req*/, Response &res) {
  4469. res.set_content(
  4470. "12345678901234567890123456789012345678901234567890123456789"
  4471. "01234567890123456789012345678901234567890",
  4472. "text/plain");
  4473. })
  4474. .Get("/compress-with-charset",
  4475. [&](const Request & /*req*/, Response &res) {
  4476. res.set_content(
  4477. "12345678901234567890123456789012345678901234567890123456789"
  4478. "01234567890123456789012345678901234567890",
  4479. "application/json; charset=utf-8");
  4480. })
  4481. .Get("/nocompress",
  4482. [&](const Request & /*req*/, Response &res) {
  4483. res.set_content(
  4484. "12345678901234567890123456789012345678901234567890123456789"
  4485. "01234567890123456789012345678901234567890",
  4486. "application/octet-stream");
  4487. })
  4488. .Post("/compress-multipart",
  4489. [&](const Request &req, Response & /*res*/) {
  4490. EXPECT_EQ(2u, req.form.fields.size());
  4491. ASSERT_TRUE(!req.form.has_field("???"));
  4492. {
  4493. const auto &text = req.form.get_field("key1");
  4494. EXPECT_EQ("test", text);
  4495. }
  4496. {
  4497. const auto &text = req.form.get_field("key2");
  4498. EXPECT_EQ("--abcdefg123", text);
  4499. }
  4500. })
  4501. #endif
  4502. ;
  4503. persons_["john"] = "programmer";
  4504. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4505. svr_.wait_until_ready();
  4506. }
  4507. virtual void TearDown() {
  4508. svr_.stop();
  4509. if (!request_threads_.empty()) {
  4510. std::this_thread::sleep_for(std::chrono::seconds(1));
  4511. for (auto &t : request_threads_) {
  4512. t.join();
  4513. }
  4514. }
  4515. t_.join();
  4516. }
  4517. map<string, string> persons_;
  4518. #ifdef CPPHTTPLIB_SSL_ENABLED
  4519. SSLClient cli_;
  4520. SSLServer svr_;
  4521. #else
  4522. Client cli_;
  4523. Server svr_;
  4524. #endif
  4525. thread t_;
  4526. std::vector<thread> request_threads_;
  4527. };
  4528. TEST_F(ServerTest, GetMethod200) {
  4529. auto res = cli_.Get("/hi");
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ("HTTP/1.1", res->version);
  4532. EXPECT_EQ(StatusCode::OK_200, res->status);
  4533. EXPECT_EQ("OK", res->reason);
  4534. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4535. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4536. EXPECT_EQ("Hello World!", res->body);
  4537. }
  4538. TEST_F(ServerTest, GetEmptyFile) {
  4539. auto res = cli_.Get("/empty_file");
  4540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4541. EXPECT_EQ(StatusCode::OK_200, res->status);
  4542. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4543. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4544. EXPECT_EQ("", res->body);
  4545. }
  4546. TEST_F(ServerTest, GetFileContent) {
  4547. auto res = cli_.Get("/file_content");
  4548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4549. EXPECT_EQ(StatusCode::OK_200, res->status);
  4550. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4551. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4552. EXPECT_EQ("test.html", res->body);
  4553. }
  4554. TEST_F(ServerTest, GetFileContentWithRange) {
  4555. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4557. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4558. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4559. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4560. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4561. EXPECT_EQ("est", res->body);
  4562. }
  4563. TEST_F(ServerTest, GetFileContentWithContentType) {
  4564. auto res = cli_.Get("/file_content_with_content_type");
  4565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4566. EXPECT_EQ(StatusCode::OK_200, res->status);
  4567. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4568. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4569. EXPECT_EQ("file\n", res->body);
  4570. }
  4571. TEST_F(ServerTest, GetInvalidFileContent) {
  4572. auto res = cli_.Get("/invalid_file_content");
  4573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4574. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4575. }
  4576. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4577. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4579. EXPECT_EQ("HTTP/1.1", res->version);
  4580. EXPECT_EQ(StatusCode::OK_200, res->status);
  4581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4582. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4583. EXPECT_EQ("Hello World!", res->body);
  4584. }
  4585. TEST_F(ServerTest, GetMethod302) {
  4586. auto res = cli_.Get("/");
  4587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4588. EXPECT_EQ(StatusCode::Found_302, res->status);
  4589. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4590. }
  4591. TEST_F(ServerTest, GetMethod302Redirect) {
  4592. cli_.set_follow_location(true);
  4593. auto res = cli_.Get("/");
  4594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4595. EXPECT_EQ(StatusCode::OK_200, res->status);
  4596. EXPECT_EQ("Hello World!", res->body);
  4597. EXPECT_EQ("/hi", res->location);
  4598. }
  4599. TEST_F(ServerTest, GetMethod404) {
  4600. auto res = cli_.Get("/invalid");
  4601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4602. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4603. }
  4604. TEST_F(ServerTest, HeadMethod200) {
  4605. auto res = cli_.Head("/hi");
  4606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4607. EXPECT_EQ(StatusCode::OK_200, res->status);
  4608. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4609. EXPECT_TRUE(res->body.empty());
  4610. }
  4611. TEST_F(ServerTest, HeadMethod200Static) {
  4612. auto res = cli_.Head("/mount/dir/index.html");
  4613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4614. EXPECT_EQ(StatusCode::OK_200, res->status);
  4615. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4616. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4617. EXPECT_TRUE(res->body.empty());
  4618. }
  4619. TEST_F(ServerTest, HeadMethod404) {
  4620. auto res = cli_.Head("/invalid");
  4621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4622. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4623. EXPECT_TRUE(res->body.empty());
  4624. }
  4625. TEST_F(ServerTest, GetMethodPersonJohn) {
  4626. auto res = cli_.Get("/person/john");
  4627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4628. EXPECT_EQ(StatusCode::OK_200, res->status);
  4629. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4630. EXPECT_EQ("programmer", res->body);
  4631. }
  4632. TEST_F(ServerTest, PostMethod1) {
  4633. auto res = cli_.Get("/person/john1");
  4634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4635. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4636. res = cli_.Post("/person", "name=john1&note=coder",
  4637. "application/x-www-form-urlencoded");
  4638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4639. ASSERT_EQ(StatusCode::OK_200, res->status);
  4640. res = cli_.Get("/person/john1");
  4641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4642. ASSERT_EQ(StatusCode::OK_200, res->status);
  4643. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4644. ASSERT_EQ("coder", res->body);
  4645. }
  4646. TEST_F(ServerTest, PostMethod2) {
  4647. auto res = cli_.Get("/person/john2");
  4648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4649. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4650. Params params;
  4651. params.emplace("name", "john2");
  4652. params.emplace("note", "coder");
  4653. res = cli_.Post("/person", params);
  4654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4655. ASSERT_EQ(StatusCode::OK_200, res->status);
  4656. res = cli_.Get("/person/john2");
  4657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4658. ASSERT_EQ(StatusCode::OK_200, res->status);
  4659. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4660. ASSERT_EQ("coder", res->body);
  4661. }
  4662. TEST_F(ServerTest, PutMethod3) {
  4663. auto res = cli_.Get("/person/john3");
  4664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4665. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4666. Params params;
  4667. params.emplace("name", "john3");
  4668. params.emplace("note", "coder");
  4669. res = cli_.Put("/person", params);
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. ASSERT_EQ(StatusCode::OK_200, res->status);
  4672. res = cli_.Get("/person/john3");
  4673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4674. ASSERT_EQ(StatusCode::OK_200, res->status);
  4675. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4676. ASSERT_EQ("coder", res->body);
  4677. }
  4678. TEST_F(ServerTest, DeleteMethod1) {
  4679. auto res = cli_.Get("/person/john4");
  4680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4681. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4682. Params params;
  4683. params.emplace("name", "john4");
  4684. params.emplace("note", "coder");
  4685. res = cli_.Post("/person", params);
  4686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4687. ASSERT_EQ(StatusCode::OK_200, res->status);
  4688. res = cli_.Get("/person/john4");
  4689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4690. ASSERT_EQ(StatusCode::OK_200, res->status);
  4691. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4692. ASSERT_EQ("coder", res->body);
  4693. Params delete_params;
  4694. delete_params.emplace("name", "john4");
  4695. res = cli_.Delete("/person", delete_params);
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. ASSERT_EQ(StatusCode::OK_200, res->status);
  4698. ASSERT_EQ("DELETED", res->body);
  4699. res = cli_.Get("/person/john4");
  4700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4701. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4702. }
  4703. TEST_F(ServerTest, DeleteMethod2) {
  4704. auto res = cli_.Get("/person/john5");
  4705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4706. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4707. Params params;
  4708. params.emplace("name", "john5");
  4709. params.emplace("note", "developer");
  4710. res = cli_.Post("/person", params);
  4711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4712. ASSERT_EQ(StatusCode::OK_200, res->status);
  4713. res = cli_.Get("/person/john5");
  4714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4715. ASSERT_EQ(StatusCode::OK_200, res->status);
  4716. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4717. ASSERT_EQ("developer", res->body);
  4718. Params delete_params;
  4719. delete_params.emplace("name", "john5");
  4720. Headers headers;
  4721. headers.emplace("Custom-Header", "test-value");
  4722. res = cli_.Delete("/person", headers, delete_params);
  4723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4724. ASSERT_EQ(StatusCode::OK_200, res->status);
  4725. ASSERT_EQ("DELETED", res->body);
  4726. res = cli_.Get("/person/john5");
  4727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4728. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4729. }
  4730. TEST_F(ServerTest, DeleteMethod3) {
  4731. auto res = cli_.Get("/person/john6");
  4732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4733. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4734. Params params;
  4735. params.emplace("name", "john6");
  4736. params.emplace("note", "tester");
  4737. res = cli_.Post("/person", params);
  4738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4739. ASSERT_EQ(StatusCode::OK_200, res->status);
  4740. res = cli_.Get("/person/john6");
  4741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4742. ASSERT_EQ(StatusCode::OK_200, res->status);
  4743. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4744. ASSERT_EQ("tester", res->body);
  4745. Params delete_params;
  4746. delete_params.emplace("name", "john6");
  4747. Headers headers;
  4748. headers.emplace("Custom-Header", "test-value");
  4749. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. ASSERT_EQ(StatusCode::OK_200, res->status);
  4752. ASSERT_EQ("DELETED", res->body);
  4753. res = cli_.Get("/person/john6");
  4754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4755. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4756. }
  4757. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4758. Params params;
  4759. params.emplace("json", JSON_DATA);
  4760. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4762. ASSERT_EQ(StatusCode::OK_200, res->status);
  4763. ASSERT_EQ(JSON_DATA, res->body);
  4764. }
  4765. TEST_F(ServerTest, PostEmptyContent) {
  4766. auto res = cli_.Post("/empty", "", "text/plain");
  4767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4768. ASSERT_EQ(StatusCode::OK_200, res->status);
  4769. ASSERT_EQ("empty", res->body);
  4770. }
  4771. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4772. auto res = cli_.Post("/empty-no-content-type");
  4773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4774. ASSERT_EQ(StatusCode::OK_200, res->status);
  4775. ASSERT_EQ("empty-no-content-type", res->body);
  4776. }
  4777. TEST_F(ServerTest, PostPathOnly) {
  4778. auto res = cli_.Post("/path-only");
  4779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4780. ASSERT_EQ(StatusCode::OK_200, res->status);
  4781. ASSERT_EQ("path-only", res->body);
  4782. }
  4783. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4784. auto res = cli_.Post("/path-headers-only",
  4785. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4787. ASSERT_EQ(StatusCode::OK_200, res->status);
  4788. ASSERT_EQ("path-headers-only", res->body);
  4789. }
  4790. TEST_F(ServerTest, PostLarge) {
  4791. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4793. ASSERT_EQ(StatusCode::OK_200, res->status);
  4794. EXPECT_EQ(LARGE_DATA, res->body);
  4795. }
  4796. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4797. auto res = cli_.Put("/empty-no-content-type");
  4798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4799. ASSERT_EQ(StatusCode::OK_200, res->status);
  4800. ASSERT_EQ("empty-no-content-type", res->body);
  4801. }
  4802. TEST_F(ServerTest, GetMethodDir) {
  4803. auto res = cli_.Get("/dir/");
  4804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4805. EXPECT_EQ(StatusCode::OK_200, res->status);
  4806. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4807. auto body = R"(<html>
  4808. <head>
  4809. </head>
  4810. <body>
  4811. <a href="/dir/test.html">Test</a>
  4812. <a href="/hi">hi</a>
  4813. </body>
  4814. </html>
  4815. )";
  4816. EXPECT_EQ(body, res->body);
  4817. }
  4818. TEST_F(ServerTest, GetMethodDirTest) {
  4819. auto res = cli_.Get("/dir/test.html");
  4820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4821. EXPECT_EQ(StatusCode::OK_200, res->status);
  4822. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4823. EXPECT_EQ("test.html", res->body);
  4824. }
  4825. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4826. auto res = cli_.Get("/dir/../dir/test.html");
  4827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4828. EXPECT_EQ(StatusCode::OK_200, res->status);
  4829. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4830. EXPECT_EQ("test.html", res->body);
  4831. }
  4832. TEST_F(ServerTest, GetMethodInvalidPath) {
  4833. auto res = cli_.Get("/dir/../test.html");
  4834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4835. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4836. }
  4837. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4838. auto res = cli_.Get("/../www/dir/test.html");
  4839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4840. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4841. }
  4842. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4843. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4845. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4846. }
  4847. TEST_F(ServerTest, GetMethodDirMountTest) {
  4848. auto res = cli_.Get("/mount/dir/test.html");
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. EXPECT_EQ(StatusCode::OK_200, res->status);
  4851. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4852. EXPECT_EQ("test.html", res->body);
  4853. }
  4854. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4855. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4857. EXPECT_EQ(StatusCode::OK_200, res->status);
  4858. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4859. EXPECT_EQ("test.html", res->body);
  4860. }
  4861. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4862. auto res = cli_.Get("/mount/dir/../test.html");
  4863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4865. }
  4866. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4867. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4869. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4870. }
  4871. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4872. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4875. }
  4876. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4877. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4880. }
  4881. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4882. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4885. }
  4886. TEST_F(ServerTest, PostMethod303) {
  4887. auto res = cli_.Post("/1", "body", "text/plain");
  4888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4889. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4890. EXPECT_EQ("/2", res->get_header_value("Location"));
  4891. }
  4892. TEST_F(ServerTest, PostMethod303Redirect) {
  4893. cli_.set_follow_location(true);
  4894. auto res = cli_.Post("/1", "body", "text/plain");
  4895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4896. EXPECT_EQ(StatusCode::OK_200, res->status);
  4897. EXPECT_EQ("redirected.", res->body);
  4898. EXPECT_EQ("/2", res->location);
  4899. }
  4900. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4901. auto res = cli_.Get("/dir/test.abcde");
  4902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4903. EXPECT_EQ(StatusCode::OK_200, res->status);
  4904. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4905. EXPECT_EQ("abcde", res->body);
  4906. }
  4907. TEST_F(ServerTest, StaticFileRange) {
  4908. auto res =
  4909. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4911. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4912. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4913. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4914. EXPECT_EQ(true, res->has_header("Content-Range"));
  4915. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4916. EXPECT_EQ(std::string("cd"), res->body);
  4917. }
  4918. TEST_F(ServerTest, StaticFileRanges) {
  4919. auto res = cli_.Get("/dir/test.abcde",
  4920. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4922. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4923. EXPECT_TRUE(
  4924. res->get_header_value("Content-Type")
  4925. .find(
  4926. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4927. 0);
  4928. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4929. }
  4930. TEST_F(ServerTest, StaticFileRangeHead) {
  4931. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4933. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4934. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4935. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4936. EXPECT_EQ(true, res->has_header("Content-Range"));
  4937. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4938. }
  4939. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4940. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4942. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4944. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4945. EXPECT_EQ(true, res->has_header("Content-Range"));
  4946. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4947. res->get_header_value("Content-Range"));
  4948. EXPECT_EQ("LAST\n", res->body);
  4949. }
  4950. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4951. auto res =
  4952. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4954. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4955. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4956. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4957. EXPECT_EQ(true, res->has_header("Content-Range"));
  4958. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4959. }
  4960. TEST_F(ServerTest, StaticFileBigFile) {
  4961. auto res = cli_.Get("/dir/1MB.txt");
  4962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4963. EXPECT_EQ(StatusCode::OK_200, res->status);
  4964. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4965. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4966. }
  4967. TEST_F(ServerTest, InvalidBaseDirMount) {
  4968. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4969. }
  4970. TEST_F(ServerTest, Binary) {
  4971. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4972. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4973. "application/octet-stream");
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. ASSERT_EQ(StatusCode::OK_200, res->status);
  4976. ASSERT_EQ(4U, res->body.size());
  4977. res = cli_.Put("/binary", binary.data(), binary.size(),
  4978. "application/octet-stream");
  4979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4980. ASSERT_EQ(StatusCode::OK_200, res->status);
  4981. ASSERT_EQ(4U, res->body.size());
  4982. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4983. "application/octet-stream");
  4984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4985. ASSERT_EQ(StatusCode::OK_200, res->status);
  4986. ASSERT_EQ(4U, res->body.size());
  4987. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4988. "application/octet-stream");
  4989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4990. ASSERT_EQ(StatusCode::OK_200, res->status);
  4991. ASSERT_EQ(4U, res->body.size());
  4992. }
  4993. TEST_F(ServerTest, BinaryString) {
  4994. auto binary = std::string("\x00\x01\x02\x03", 4);
  4995. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4997. ASSERT_EQ(StatusCode::OK_200, res->status);
  4998. ASSERT_EQ(4U, res->body.size());
  4999. res = cli_.Put("/binary", binary, "application/octet-stream");
  5000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5001. ASSERT_EQ(StatusCode::OK_200, res->status);
  5002. ASSERT_EQ(4U, res->body.size());
  5003. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5005. ASSERT_EQ(StatusCode::OK_200, res->status);
  5006. ASSERT_EQ(4U, res->body.size());
  5007. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5009. ASSERT_EQ(StatusCode::OK_200, res->status);
  5010. ASSERT_EQ(4U, res->body.size());
  5011. }
  5012. TEST_F(ServerTest, EmptyRequest) {
  5013. auto res = cli_.Get("");
  5014. ASSERT_TRUE(!res);
  5015. EXPECT_EQ(Error::Connection, res.error());
  5016. }
  5017. TEST_F(ServerTest, LongRequest) {
  5018. std::string request;
  5019. for (size_t i = 0; i < 545; i++) {
  5020. request += "/TooLongRequest";
  5021. }
  5022. request += "OK";
  5023. auto res = cli_.Get(request.c_str());
  5024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5025. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5026. }
  5027. TEST_F(ServerTest, TooLongRequest) {
  5028. std::string request;
  5029. for (size_t i = 0; i < 546; i++) {
  5030. request += "/TooLongRequest";
  5031. }
  5032. request += "_NG";
  5033. auto start = std::chrono::high_resolution_clock::now();
  5034. cli_.set_keep_alive(true);
  5035. auto res = cli_.Get(request.c_str());
  5036. auto end = std::chrono::high_resolution_clock::now();
  5037. auto elapsed =
  5038. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5039. .count();
  5040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5041. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5042. EXPECT_LE(elapsed, 1000);
  5043. EXPECT_EQ("close", res->get_header_value("Connection"));
  5044. EXPECT_FALSE(cli_.is_socket_open());
  5045. }
  5046. TEST_F(ServerTest, AlmostTooLongRequest) {
  5047. // test for #2046 - URI length check shouldn't include other content on req
  5048. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5049. // leading /, space, HTTP/1.1)
  5050. std::string request =
  5051. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5052. auto res = cli_.Get(request.c_str());
  5053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5054. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5055. }
  5056. TEST_F(ServerTest, LongHeader) {
  5057. Request req;
  5058. req.method = "GET";
  5059. req.path = "/hi";
  5060. std::string host_and_port;
  5061. host_and_port += HOST;
  5062. host_and_port += ":";
  5063. host_and_port += std::to_string(PORT);
  5064. req.headers.emplace("Host", host_and_port.c_str());
  5065. req.headers.emplace("Accept", "*/*");
  5066. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5067. req.headers.emplace(
  5068. "Header-Name",
  5069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5072. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5073. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5082. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5083. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5084. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5085. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5097. "@@@@@@@@@@@@@@@@");
  5098. auto res = std::make_shared<Response>();
  5099. auto error = Error::Success;
  5100. auto ret = cli_.send(req, *res, error);
  5101. ASSERT_TRUE(ret);
  5102. EXPECT_EQ(StatusCode::OK_200, res->status);
  5103. }
  5104. TEST_F(ServerTest, LongQueryValue) {
  5105. auto start = std::chrono::high_resolution_clock::now();
  5106. cli_.set_keep_alive(true);
  5107. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5108. auto end = std::chrono::high_resolution_clock::now();
  5109. auto elapsed =
  5110. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5111. .count();
  5112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5113. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5114. EXPECT_LE(elapsed, 1000);
  5115. EXPECT_EQ("close", res->get_header_value("Connection"));
  5116. EXPECT_FALSE(cli_.is_socket_open());
  5117. }
  5118. TEST_F(ServerTest, TooLongQueryValue) {
  5119. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5120. ASSERT_FALSE(res);
  5121. EXPECT_EQ(Error::Read, res.error());
  5122. }
  5123. TEST_F(ServerTest, TooLongHeader) {
  5124. Request req;
  5125. req.method = "GET";
  5126. req.path = "/hi";
  5127. std::string host_and_port;
  5128. host_and_port += HOST;
  5129. host_and_port += ":";
  5130. host_and_port += std::to_string(PORT);
  5131. req.headers.emplace("Host", host_and_port.c_str());
  5132. req.headers.emplace("Accept", "*/*");
  5133. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5134. req.headers.emplace(
  5135. "Header-Name",
  5136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5164. "@@@@@@@@@@@@@@@@@");
  5165. auto res = std::make_shared<Response>();
  5166. auto error = Error::Success;
  5167. auto ret = cli_.send(req, *res, error);
  5168. ASSERT_TRUE(ret);
  5169. EXPECT_EQ(StatusCode::OK_200, res->status);
  5170. }
  5171. TEST_F(ServerTest, HeaderCountAtLimit) {
  5172. // Test with headers just under the 100 limit
  5173. httplib::Headers headers;
  5174. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5175. // This should keep us just under the 100 header limit
  5176. for (int i = 0; i < 95; i++) {
  5177. std::string name = "X-Test-Header-" + std::to_string(i);
  5178. std::string value = "value" + std::to_string(i);
  5179. headers.emplace(name, value);
  5180. }
  5181. // This should work fine as we're under the limit
  5182. auto res = cli_.Get("/hi", headers);
  5183. EXPECT_TRUE(res);
  5184. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5185. }
  5186. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5187. // Test with many headers to exceed the 100 limit
  5188. httplib::Headers headers;
  5189. // Add 150 headers to definitely exceed the 100 limit
  5190. for (int i = 0; i < 150; i++) {
  5191. std::string name = "X-Test-Header-" + std::to_string(i);
  5192. std::string value = "value" + std::to_string(i);
  5193. headers.emplace(name, value);
  5194. }
  5195. // This should fail due to exceeding header count limit
  5196. cli_.set_keep_alive(true);
  5197. auto res = cli_.Get("/hi", headers);
  5198. // The server should respond with 400 Bad Request
  5199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5200. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5201. EXPECT_EQ("close", res->get_header_value("Connection"));
  5202. EXPECT_FALSE(cli_.is_socket_open());
  5203. }
  5204. TEST_F(ServerTest, PercentEncoding) {
  5205. auto res = cli_.Get("/e%6edwith%");
  5206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5207. EXPECT_EQ(StatusCode::OK_200, res->status);
  5208. }
  5209. TEST_F(ServerTest, PercentEncodingUnicode) {
  5210. auto res = cli_.Get("/e%u006edwith%");
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. EXPECT_EQ(StatusCode::OK_200, res->status);
  5213. }
  5214. TEST_F(ServerTest, InvalidPercentEncoding) {
  5215. auto res = cli_.Get("/%endwith%");
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5218. }
  5219. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5220. auto res = cli_.Get("/%uendwith%");
  5221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5223. }
  5224. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5225. auto res = cli_.Get("/hello?aaa=bbb%");
  5226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5227. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5228. }
  5229. TEST_F(ServerTest, PlusSignEncoding) {
  5230. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5232. EXPECT_EQ(StatusCode::OK_200, res->status);
  5233. EXPECT_EQ("a +b", res->body);
  5234. }
  5235. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5236. // This test simulates a potential DoS attack using many headers
  5237. // to verify our security fix prevents memory exhaustion
  5238. httplib::Headers attack_headers;
  5239. // Attempt to add many headers like an attacker would (200 headers to far
  5240. // exceed limit)
  5241. for (int i = 0; i < 200; i++) {
  5242. std::string name = "X-Attack-Header-" + std::to_string(i);
  5243. std::string value = "attack_payload_" + std::to_string(i);
  5244. attack_headers.emplace(name, value);
  5245. }
  5246. // Try to POST with excessive headers
  5247. cli_.set_keep_alive(true);
  5248. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5249. // Should either fail or return 400 Bad Request due to security limit
  5250. if (res) {
  5251. // If we get a response, it should be 400 Bad Request
  5252. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5253. EXPECT_EQ("close", res->get_header_value("Connection"));
  5254. }
  5255. EXPECT_FALSE(cli_.is_socket_open());
  5256. }
  5257. TEST_F(ServerTest, MultipartFormData) {
  5258. UploadFormDataItems items = {
  5259. {"text1", "text default", "", ""},
  5260. {"text2", "aωb", "", ""},
  5261. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5262. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5263. {"file3", "", "", "application/octet-stream"},
  5264. {"file4", "", "", " application/json tmp-string "}};
  5265. auto res = cli_.Post("/multipart", items);
  5266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5267. EXPECT_EQ(StatusCode::OK_200, res->status);
  5268. }
  5269. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5270. UploadFormDataItems items = {
  5271. {"text", "default text", "", ""},
  5272. {"multi_text1", "aaaaa", "", ""},
  5273. {"multi_text1", "bbbbb", "", ""},
  5274. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5275. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5276. "application/json"},
  5277. };
  5278. auto res = cli_.Post("/multipart/multi_file_values", items);
  5279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5280. EXPECT_EQ(StatusCode::OK_200, res->status);
  5281. }
  5282. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5283. auto res = cli_.Get("/hi");
  5284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5285. EXPECT_EQ(StatusCode::OK_200, res->status);
  5286. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5287. EXPECT_EQ("Hello World!", res->body);
  5288. }
  5289. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5290. Request req;
  5291. req.method = "POST";
  5292. req.path = "/chunked";
  5293. std::string host_and_port;
  5294. host_and_port += HOST;
  5295. host_and_port += ":";
  5296. host_and_port += std::to_string(PORT);
  5297. req.headers.emplace("Host", host_and_port.c_str());
  5298. req.headers.emplace("Accept", "*/*");
  5299. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5300. req.headers.emplace("Content-Type", "text/plain");
  5301. req.headers.emplace("Content-Length", "0");
  5302. req.headers.emplace(
  5303. "Transfer-Encoding",
  5304. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5305. // Client does not chunk, so make a chunked body manually.
  5306. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5307. auto res = std::make_shared<Response>();
  5308. auto error = Error::Success;
  5309. auto ret = cli_.send(req, *res, error);
  5310. ASSERT_TRUE(ret);
  5311. EXPECT_EQ(StatusCode::OK_200, res->status);
  5312. }
  5313. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5314. // rather than treat them as valid lengths.
  5315. template <typename ClientT>
  5316. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5317. Request req;
  5318. req.method = "POST";
  5319. req.path = "/chunked";
  5320. std::string host_and_port;
  5321. host_and_port += HOST;
  5322. host_and_port += ":";
  5323. host_and_port += std::to_string(PORT);
  5324. req.headers.emplace("Host", host_and_port.c_str());
  5325. req.headers.emplace("Content-Length", "0");
  5326. req.headers.emplace("Transfer-Encoding", "chunked");
  5327. req.body = body;
  5328. auto res = std::make_shared<Response>();
  5329. auto error = Error::Success;
  5330. ASSERT_TRUE(cli.send(req, *res, error));
  5331. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5332. }
  5333. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5334. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5335. }
  5336. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5337. expect_chunked_body_rejected(
  5338. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5339. }
  5340. TEST_F(ServerTest, GetStreamed2) {
  5341. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5344. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5345. EXPECT_EQ(true, res->has_header("Content-Range"));
  5346. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5347. EXPECT_EQ(std::string("ab"), res->body);
  5348. }
  5349. TEST_F(ServerTest, GetStreamed) {
  5350. auto res = cli_.Get("/streamed");
  5351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5352. EXPECT_EQ(StatusCode::OK_200, res->status);
  5353. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5354. EXPECT_EQ(std::string("aaabbb"), res->body);
  5355. }
  5356. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5357. auto res = cli_.Get("/streamed-without-length",
  5358. Headers{make_range_header({{0, -1}})});
  5359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5360. EXPECT_EQ(StatusCode::OK_200, res->status);
  5361. EXPECT_EQ(false, res->has_header("Content-Length"));
  5362. EXPECT_EQ(false, res->has_header("Content-Range"));
  5363. EXPECT_EQ(std::string("abcdefg"), res->body);
  5364. }
  5365. TEST_F(ServerTest, GetStreamedWithRange1) {
  5366. auto res =
  5367. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5370. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5371. EXPECT_EQ(true, res->has_header("Content-Range"));
  5372. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5373. EXPECT_EQ(std::string("def"), res->body);
  5374. }
  5375. TEST_F(ServerTest, GetStreamedWithRange2) {
  5376. auto res =
  5377. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5380. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5381. EXPECT_EQ(true, res->has_header("Content-Range"));
  5382. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5383. EXPECT_EQ(std::string("bcdefg"), res->body);
  5384. }
  5385. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5386. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5388. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5389. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5390. EXPECT_EQ(true, res->has_header("Content-Range"));
  5391. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5392. EXPECT_EQ(std::string("efg"), res->body);
  5393. }
  5394. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5395. auto res =
  5396. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5398. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5399. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5400. EXPECT_EQ(false, res->has_header("Content-Range"));
  5401. EXPECT_EQ(0U, res->body.size());
  5402. }
  5403. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5404. // Only a 206 is served as a partial representation. Under any other status
  5405. // `apply_ranges()` reported the full content length, so the body must match
  5406. // that header, and the content provider must never be asked for an offset
  5407. // outside the representation.
  5408. auto check = [&](int status, const char *range) {
  5409. auto path =
  5410. std::string("/streamed-with-range?status=") + std::to_string(status);
  5411. auto ctx = path + " Range: " + range;
  5412. auto res = cli_.Get(path, Headers{{"Range", range}});
  5413. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5414. EXPECT_EQ(status, res->status) << ctx;
  5415. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5416. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5417. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5418. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5419. };
  5420. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5421. check(403, "bytes=3-5");
  5422. // The offset is far past the representation.
  5423. check(403, "bytes=100000-100200");
  5424. // `first_pos` is still -1 here, and the bounds asserts in
  5425. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5426. check(403, "bytes=-3");
  5427. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5428. // multipart branch would have written one that is empty.
  5429. check(403, "bytes=1-2, 4-5");
  5430. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5431. // covers the whole representation.
  5432. check(200, "bytes=3-5");
  5433. check(200, "bytes=1-2, 4-5");
  5434. }
  5435. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5436. auto res =
  5437. cli_.Get("/streamed-with-range",
  5438. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5439. "92233720368547758079223372036854775807"}});
  5440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5441. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5442. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5443. EXPECT_EQ(false, res->has_header("Content-Range"));
  5444. EXPECT_EQ(0U, res->body.size());
  5445. }
  5446. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5447. auto res = cli_.Get(
  5448. "/with-range",
  5449. Headers{{"Range",
  5450. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5451. {"Accept-Encoding", ""}});
  5452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5453. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5454. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5455. EXPECT_EQ(true, res->has_header("Content-Range"));
  5456. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5457. EXPECT_EQ(std::string("abcdefg"), res->body);
  5458. }
  5459. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5460. auto res = cli_.Get("/with-range", Headers{
  5461. {"Range", "bytes=0-"},
  5462. {"Accept-Encoding", ""},
  5463. });
  5464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5465. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5466. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5467. EXPECT_EQ(true, res->has_header("Content-Range"));
  5468. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5469. EXPECT_EQ(std::string("abcdefg"), res->body);
  5470. }
  5471. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5472. auto res = cli_.Get("/streamed-with-range",
  5473. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5475. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5476. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5477. EXPECT_EQ(false, res->has_header("Content-Range"));
  5478. EXPECT_EQ(267U, res->body.size());
  5479. // Check that both range contents are present
  5480. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5481. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5482. // Check that Content-Range headers are present for both ranges
  5483. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5484. std::string::npos);
  5485. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5486. std::string::npos);
  5487. }
  5488. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5489. Ranges ranges;
  5490. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5491. ranges.emplace_back(0, -1);
  5492. }
  5493. auto res = cli_.Get("/streamed-with-range?error",
  5494. Headers{{make_range_header(ranges)}});
  5495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5496. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5497. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5498. EXPECT_EQ(false, res->has_header("Content-Range"));
  5499. EXPECT_EQ(0U, res->body.size());
  5500. }
  5501. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5502. auto res = cli_.Get("/streamed-with-range",
  5503. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5505. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5506. EXPECT_EQ(5U, res->body.size());
  5507. // Check that overlapping ranges are coalesced into a single range
  5508. EXPECT_EQ("bcdef", res->body);
  5509. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5510. // Should be single range, not multipart
  5511. EXPECT_TRUE(res->has_header("Content-Range"));
  5512. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5513. }
  5514. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5515. auto res = cli_.Get("/streamed-with-range",
  5516. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5519. EXPECT_EQ(268U, res->body.size());
  5520. // Check that both range contents are present
  5521. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5522. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5523. // Check that Content-Range headers are present for both ranges
  5524. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5525. std::string::npos);
  5526. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5527. std::string::npos);
  5528. }
  5529. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5530. auto res = cli_.Get("/streamed-with-range",
  5531. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5533. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5534. EXPECT_EQ(269U, res->body.size());
  5535. // Check that both duplicate range contents are present
  5536. size_t first_abc = res->body.find("abc\r\n");
  5537. EXPECT_TRUE(first_abc != std::string::npos);
  5538. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5539. EXPECT_TRUE(second_abc != std::string::npos);
  5540. // Check that Content-Range headers are present for both ranges
  5541. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5542. EXPECT_TRUE(first_range != std::string::npos);
  5543. size_t second_range =
  5544. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5545. EXPECT_TRUE(second_range != std::string::npos);
  5546. }
  5547. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5548. auto res =
  5549. cli_.Get("/streamed-with-range?error",
  5550. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5553. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5554. EXPECT_EQ(false, res->has_header("Content-Range"));
  5555. EXPECT_EQ(0U, res->body.size());
  5556. }
  5557. TEST_F(ServerTest, GetStreamedEndless) {
  5558. uint64_t offset = 0;
  5559. auto res = cli_.Get("/streamed-cancel",
  5560. [&](const char * /*data*/, uint64_t data_length) {
  5561. if (offset < 100) {
  5562. offset += data_length;
  5563. return true;
  5564. }
  5565. return false;
  5566. });
  5567. ASSERT_TRUE(!res);
  5568. EXPECT_EQ(Error::Canceled, res.error());
  5569. }
  5570. TEST_F(ServerTest, ClientStop) {
  5571. std::atomic_size_t count{4};
  5572. std::vector<std::thread> threads;
  5573. for (auto i = count.load(); i != 0; --i) {
  5574. threads.emplace_back([&]() {
  5575. auto res = cli_.Get("/streamed-cancel",
  5576. [&](const char *, uint64_t) { return true; });
  5577. --count;
  5578. ASSERT_TRUE(!res);
  5579. EXPECT_TRUE(res.error() == Error::Canceled ||
  5580. res.error() == Error::Read || res.error() == Error::Write);
  5581. });
  5582. }
  5583. std::this_thread::sleep_for(std::chrono::seconds(2));
  5584. while (count != 0) {
  5585. cli_.stop();
  5586. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5587. }
  5588. for (auto &t : threads) {
  5589. t.join();
  5590. }
  5591. }
  5592. TEST_F(ServerTest, GetWithRange1) {
  5593. auto res = cli_.Get("/with-range", Headers{
  5594. make_range_header({{3, 5}}),
  5595. {"Accept-Encoding", ""},
  5596. });
  5597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5598. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5599. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5600. EXPECT_EQ(true, res->has_header("Content-Range"));
  5601. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5602. EXPECT_EQ(std::string("def"), res->body);
  5603. }
  5604. TEST_F(ServerTest, GetWithRange2) {
  5605. auto res = cli_.Get("/with-range", Headers{
  5606. make_range_header({{1, -1}}),
  5607. {"Accept-Encoding", ""},
  5608. });
  5609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5610. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5611. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5612. EXPECT_EQ(true, res->has_header("Content-Range"));
  5613. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5614. EXPECT_EQ(std::string("bcdefg"), res->body);
  5615. }
  5616. TEST_F(ServerTest, GetWithRange3) {
  5617. auto res = cli_.Get("/with-range", Headers{
  5618. make_range_header({{0, 0}}),
  5619. {"Accept-Encoding", ""},
  5620. });
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5623. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5624. EXPECT_EQ(true, res->has_header("Content-Range"));
  5625. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5626. EXPECT_EQ(std::string("a"), res->body);
  5627. }
  5628. TEST_F(ServerTest, GetWithRange4) {
  5629. auto res = cli_.Get("/with-range", Headers{
  5630. make_range_header({{-1, 2}}),
  5631. {"Accept-Encoding", ""},
  5632. });
  5633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5634. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5635. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5636. EXPECT_EQ(true, res->has_header("Content-Range"));
  5637. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5638. EXPECT_EQ(std::string("fg"), res->body);
  5639. }
  5640. TEST_F(ServerTest, GetWithRange5) {
  5641. auto res = cli_.Get("/with-range", Headers{
  5642. make_range_header({{0, 5}}),
  5643. {"Accept-Encoding", ""},
  5644. });
  5645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5646. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5647. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5648. EXPECT_EQ(true, res->has_header("Content-Range"));
  5649. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5650. EXPECT_EQ(std::string("abcdef"), res->body);
  5651. }
  5652. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5653. auto res =
  5654. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5656. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5657. }
  5658. TEST_F(ServerTest, GetWithRangeMultipart) {
  5659. auto res =
  5660. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5663. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5664. EXPECT_EQ(false, res->has_header("Content-Range"));
  5665. EXPECT_EQ(267U, res->body.size());
  5666. }
  5667. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5668. auto res = cli_.Get("/with-range",
  5669. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5672. }
  5673. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5674. auto res = cli_.Get("/with-range-customized-response",
  5675. Headers{{make_range_header({{1, 2}})}});
  5676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5677. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5678. EXPECT_EQ(true, res->has_header("Content-Length"));
  5679. EXPECT_EQ(false, res->has_header("Content-Range"));
  5680. EXPECT_EQ(JSON_DATA, res->body);
  5681. }
  5682. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5683. auto res = cli_.Get("/with-range-customized-response",
  5684. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5687. EXPECT_EQ(true, res->has_header("Content-Length"));
  5688. EXPECT_EQ(false, res->has_header("Content-Range"));
  5689. EXPECT_EQ(JSON_DATA, res->body);
  5690. }
  5691. TEST_F(ServerTest, Issue1772) {
  5692. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5695. }
  5696. TEST_F(ServerTest, Issue609) {
  5697. auto res = cli_.Delete("/issue609");
  5698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5699. EXPECT_EQ(StatusCode::OK_200, res->status);
  5700. EXPECT_EQ(std::string("ok"), res->body);
  5701. }
  5702. TEST_F(ServerTest, GetStreamedChunked) {
  5703. auto res = cli_.Get("/streamed-chunked");
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. EXPECT_EQ(StatusCode::OK_200, res->status);
  5706. EXPECT_EQ(std::string("123456789"), res->body);
  5707. }
  5708. TEST_F(ServerTest, GetStreamedChunked2) {
  5709. auto res = cli_.Get("/streamed-chunked2");
  5710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5711. EXPECT_EQ(StatusCode::OK_200, res->status);
  5712. EXPECT_EQ(std::string("123456789"), res->body);
  5713. }
  5714. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5715. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5717. EXPECT_EQ(StatusCode::OK_200, res->status);
  5718. EXPECT_EQ(std::string("123456789"), res->body);
  5719. EXPECT_TRUE(res->has_header("Trailer"));
  5720. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5721. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5722. // Trailers are now stored separately from headers (security fix)
  5723. EXPECT_EQ(2U, res->trailers.size());
  5724. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5725. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5726. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5727. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5728. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5729. // Verify trailers are NOT in headers (security verification)
  5730. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5731. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5732. }
  5733. TEST_F(ServerTest, LargeChunkedPost) {
  5734. Request req;
  5735. req.method = "POST";
  5736. req.path = "/large-chunked";
  5737. std::string host_and_port;
  5738. host_and_port += HOST;
  5739. host_and_port += ":";
  5740. host_and_port += std::to_string(PORT);
  5741. req.headers.emplace("Host", host_and_port.c_str());
  5742. req.headers.emplace("Accept", "*/*");
  5743. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5744. req.headers.emplace("Content-Type", "text/plain");
  5745. req.headers.emplace("Content-Length", "0");
  5746. req.headers.emplace("Transfer-Encoding", "chunked");
  5747. std::string long_string(30 * 1024u, 'a');
  5748. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5749. // Attempt to make a large enough post to exceed OS buffers, to test that
  5750. // the server handles short reads if the full chunk data isn't available.
  5751. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5752. auto res = std::make_shared<Response>();
  5753. auto error = Error::Success;
  5754. auto ret = cli_.send(req, *res, error);
  5755. ASSERT_TRUE(ret);
  5756. EXPECT_EQ(StatusCode::OK_200, res->status);
  5757. }
  5758. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5759. auto res = cli_.Get("/remote_addr");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. EXPECT_EQ(StatusCode::OK_200, res->status);
  5762. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5763. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5764. }
  5765. TEST_F(ServerTest, GetMethodLocalAddr) {
  5766. auto res = cli_.Get("/local_addr");
  5767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5768. EXPECT_EQ(StatusCode::OK_200, res->status);
  5769. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5770. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5771. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5772. }
  5773. TEST_F(ServerTest, HTTPResponseSplitting) {
  5774. auto res = cli_.Get("/http_response_splitting");
  5775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5776. EXPECT_EQ(StatusCode::OK_200, res->status);
  5777. }
  5778. TEST_F(ServerTest, SlowRequest) {
  5779. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5780. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5781. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5782. }
  5783. #if 0
  5784. TEST_F(ServerTest, SlowPost) {
  5785. char buffer[64 * 1024];
  5786. memset(buffer, 0x42, sizeof(buffer));
  5787. auto res = cli_.Post(
  5788. "/slowpost", 64 * 1024 * 1024,
  5789. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5790. auto ret = sink.write(buffer, sizeof(buffer));
  5791. EXPECT_TRUE(ret);
  5792. return true;
  5793. },
  5794. "text/plain");
  5795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. }
  5798. TEST_F(ServerTest, SlowPostFail) {
  5799. char buffer[64 * 1024];
  5800. memset(buffer, 0x42, sizeof(buffer));
  5801. cli_.set_write_timeout(std::chrono::seconds(0));
  5802. auto res = cli_.Post(
  5803. "/slowpost", 64 * 1024 * 1024,
  5804. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5805. sink.write(buffer, sizeof(buffer));
  5806. return true;
  5807. },
  5808. "text/plain");
  5809. ASSERT_TRUE(!res);
  5810. EXPECT_EQ(Error::Write, res.error());
  5811. }
  5812. #endif
  5813. TEST_F(ServerTest, Put) {
  5814. auto res = cli_.Put("/put", "PUT", "text/plain");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::OK_200, res->status);
  5817. EXPECT_EQ("PUT", res->body);
  5818. }
  5819. TEST_F(ServerTest, PutWithContentProvider) {
  5820. auto res = cli_.Put(
  5821. "/put", 3,
  5822. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5823. sink.os << "PUT";
  5824. return true;
  5825. },
  5826. "text/plain");
  5827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5828. EXPECT_EQ(StatusCode::OK_200, res->status);
  5829. EXPECT_EQ("PUT", res->body);
  5830. }
  5831. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5832. auto res = cli_.Post(
  5833. "/post", 42,
  5834. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5835. return false;
  5836. },
  5837. "text/plain");
  5838. ASSERT_TRUE(!res);
  5839. EXPECT_EQ(Error::Canceled, res.error());
  5840. }
  5841. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5842. auto res = cli_.Put(
  5843. "/put",
  5844. [](size_t /*offset*/, DataSink &sink) {
  5845. sink.os << "PUT";
  5846. sink.done();
  5847. return true;
  5848. },
  5849. "text/plain");
  5850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5851. EXPECT_EQ(StatusCode::OK_200, res->status);
  5852. EXPECT_EQ("PUT", res->body);
  5853. }
  5854. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5855. auto res = cli_.Post(
  5856. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5857. "text/plain");
  5858. ASSERT_TRUE(!res);
  5859. EXPECT_EQ(Error::Canceled, res.error());
  5860. }
  5861. TEST_F(ServerTest, PostLoopBack) {
  5862. std::string body;
  5863. auto res = cli_.Post(
  5864. "/post-loopback", 9,
  5865. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5866. EXPECT_EQ(9u, length);
  5867. sink.write("123", 3);
  5868. sink.write("456", 3);
  5869. sink.write("789", 3);
  5870. return true;
  5871. },
  5872. "text/plain",
  5873. [&body](const char *data, size_t data_length) {
  5874. body.append(data, data_length);
  5875. return true;
  5876. });
  5877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5878. EXPECT_EQ(StatusCode::OK_200, res->status);
  5879. EXPECT_EQ("123456789", body);
  5880. }
  5881. TEST_F(ServerTest, PutLoopBack) {
  5882. std::string body;
  5883. auto res = cli_.Put(
  5884. "/put-loopback", 9,
  5885. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5886. EXPECT_EQ(9u, length);
  5887. sink.write("123", 3);
  5888. sink.write("456", 3);
  5889. sink.write("789", 3);
  5890. return true;
  5891. },
  5892. "text/plain",
  5893. [&body](const char *data, size_t data_length) {
  5894. body.append(data, data_length);
  5895. return true;
  5896. });
  5897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5898. EXPECT_EQ(StatusCode::OK_200, res->status);
  5899. EXPECT_EQ("123456789", body);
  5900. }
  5901. TEST_F(ServerTest, PatchLoopBack) {
  5902. std::string body;
  5903. auto res = cli_.Patch(
  5904. "/patch-loopback", 9,
  5905. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5906. EXPECT_EQ(9u, length);
  5907. sink.write("123", 3);
  5908. sink.write("456", 3);
  5909. sink.write("789", 3);
  5910. return true;
  5911. },
  5912. "text/plain",
  5913. [&body](const char *data, size_t data_length) {
  5914. body.append(data, data_length);
  5915. return true;
  5916. });
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::OK_200, res->status);
  5919. EXPECT_EQ("123456789", body);
  5920. }
  5921. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5922. std::string body;
  5923. auto res = cli_.Post(
  5924. "/post-loopback",
  5925. [](size_t /*offset*/, DataSink &sink) {
  5926. sink.write("123", 3);
  5927. sink.write("456", 3);
  5928. sink.write("789", 3);
  5929. sink.done();
  5930. return true;
  5931. },
  5932. "text/plain",
  5933. [&body](const char *data, size_t data_length) {
  5934. body.append(data, data_length);
  5935. return true;
  5936. });
  5937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5938. EXPECT_EQ(StatusCode::OK_200, res->status);
  5939. EXPECT_EQ("123456789", body);
  5940. }
  5941. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5942. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5943. cli_.set_compress(true);
  5944. auto res = cli_.Put(
  5945. "/put", 3,
  5946. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5947. sink.os << "PUT";
  5948. return true;
  5949. },
  5950. "text/plain");
  5951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5952. EXPECT_EQ(StatusCode::OK_200, res->status);
  5953. EXPECT_EQ("PUT", res->body);
  5954. }
  5955. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5956. cli_.set_compress(true);
  5957. auto res = cli_.Post(
  5958. "/post", 42,
  5959. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5960. return false;
  5961. },
  5962. "text/plain");
  5963. ASSERT_TRUE(!res);
  5964. EXPECT_EQ(Error::Canceled, res.error());
  5965. }
  5966. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5967. cli_.set_compress(true);
  5968. auto res = cli_.Put(
  5969. "/put",
  5970. [](size_t /*offset*/, DataSink &sink) {
  5971. sink.os << "PUT";
  5972. sink.done();
  5973. return true;
  5974. },
  5975. "text/plain");
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. EXPECT_EQ("PUT", res->body);
  5979. }
  5980. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5981. cli_.set_compress(true);
  5982. auto res = cli_.Post(
  5983. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5984. "text/plain");
  5985. ASSERT_TRUE(!res);
  5986. EXPECT_EQ(Error::Canceled, res.error());
  5987. }
  5988. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5989. cli_.set_compress(true);
  5990. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5992. EXPECT_EQ(StatusCode::OK_200, res->status);
  5993. EXPECT_EQ(LARGE_DATA, res->body);
  5994. }
  5995. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5996. #ifdef CPPHTTPLIB_SSL_ENABLED
  5997. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5998. Client cli(s.c_str());
  5999. cli.enable_server_certificate_verification(false);
  6000. #else
  6001. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6002. Client cli(s.c_str());
  6003. #endif
  6004. cli.set_compress(true);
  6005. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6007. EXPECT_EQ(StatusCode::OK_200, res->status);
  6008. EXPECT_EQ(LARGE_DATA, res->body);
  6009. // The compressed size should be less than a 10th of the original. May vary
  6010. // depending on the zlib library.
  6011. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6012. static_cast<uint64_t>(10 * 1024 * 1024));
  6013. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6014. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6015. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6016. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6017. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6018. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6019. #endif
  6020. }
  6021. TEST_F(ServerTest, PutContentWithDeflate) {
  6022. cli_.set_compress(false);
  6023. Headers headers;
  6024. headers.emplace("Content-Encoding", "deflate");
  6025. // PUT in deflate format:
  6026. auto res = cli_.Put("/put", headers,
  6027. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6029. EXPECT_EQ(StatusCode::OK_200, res->status);
  6030. EXPECT_EQ("PUT", res->body);
  6031. }
  6032. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6033. Headers headers;
  6034. headers.emplace("Accept-Encoding", "gzip, deflate");
  6035. auto res = cli_.Get("/streamed-chunked", headers);
  6036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6037. EXPECT_EQ(StatusCode::OK_200, res->status);
  6038. EXPECT_EQ(std::string("123456789"), res->body);
  6039. }
  6040. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6041. Headers headers;
  6042. headers.emplace("Accept-Encoding", "gzip, deflate");
  6043. auto res = cli_.Get("/streamed-chunked2", headers);
  6044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6045. EXPECT_EQ(StatusCode::OK_200, res->status);
  6046. EXPECT_EQ(std::string("123456789"), res->body);
  6047. }
  6048. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6049. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6051. EXPECT_EQ(StatusCode::OK_200, res->status);
  6052. }
  6053. TEST(GzipDecompressor, ChunkedDecompression) {
  6054. std::string data;
  6055. for (size_t i = 0; i < 32 * 1024; ++i) {
  6056. data.push_back(static_cast<char>('a' + i % 26));
  6057. }
  6058. std::string compressed_data;
  6059. {
  6060. httplib::detail::gzip_compressor compressor;
  6061. bool result = compressor.compress(
  6062. data.data(), data.size(),
  6063. /*last=*/true,
  6064. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6065. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6066. compressed_data_size);
  6067. return true;
  6068. });
  6069. ASSERT_TRUE(result);
  6070. }
  6071. std::string decompressed_data;
  6072. {
  6073. httplib::detail::gzip_decompressor decompressor;
  6074. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6075. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6076. size_t chunk_size = 130;
  6077. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6078. chunk_begin += chunk_size) {
  6079. size_t current_chunk_size =
  6080. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6081. bool result = decompressor.decompress(
  6082. compressed_data.data() + chunk_begin, current_chunk_size,
  6083. [&](const char *decompressed_data_chunk,
  6084. size_t decompressed_data_chunk_size) {
  6085. decompressed_data.insert(decompressed_data.size(),
  6086. decompressed_data_chunk,
  6087. decompressed_data_chunk_size);
  6088. return true;
  6089. });
  6090. ASSERT_TRUE(result);
  6091. }
  6092. }
  6093. ASSERT_EQ(data, decompressed_data);
  6094. }
  6095. TEST(GzipDecompressor, DeflateDecompression) {
  6096. std::string original_text = "Raw deflate without gzip";
  6097. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6098. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6099. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6100. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6101. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6102. std::string decompressed_data;
  6103. {
  6104. httplib::detail::gzip_decompressor decompressor;
  6105. bool result = decompressor.decompress(
  6106. compressed_data.data(), compressed_data.size(),
  6107. [&](const char *decompressed_data_chunk,
  6108. size_t decompressed_data_chunk_size) {
  6109. decompressed_data.insert(decompressed_data.size(),
  6110. decompressed_data_chunk,
  6111. decompressed_data_chunk_size);
  6112. return true;
  6113. });
  6114. ASSERT_TRUE(result);
  6115. }
  6116. ASSERT_EQ(original_text, decompressed_data);
  6117. }
  6118. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6119. std::string original_text = "Raw deflate without gzip";
  6120. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6121. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6122. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6123. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6124. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6125. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6126. std::string decompressed_data;
  6127. {
  6128. httplib::detail::gzip_decompressor decompressor;
  6129. bool result = decompressor.decompress(
  6130. compressed_data.data(), compressed_data.size(),
  6131. [&](const char *decompressed_data_chunk,
  6132. size_t decompressed_data_chunk_size) {
  6133. decompressed_data.insert(decompressed_data.size(),
  6134. decompressed_data_chunk,
  6135. decompressed_data_chunk_size);
  6136. return true;
  6137. });
  6138. ASSERT_TRUE(result);
  6139. }
  6140. ASSERT_EQ(original_text, decompressed_data);
  6141. }
  6142. #endif
  6143. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6144. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6145. Headers headers;
  6146. headers.emplace("Accept-Encoding", "br");
  6147. auto res = cli_.Get("/streamed-chunked", headers);
  6148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6149. EXPECT_EQ(StatusCode::OK_200, res->status);
  6150. EXPECT_EQ(std::string("123456789"), res->body);
  6151. }
  6152. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6153. Headers headers;
  6154. headers.emplace("Accept-Encoding", "br");
  6155. auto res = cli_.Get("/streamed-chunked2", headers);
  6156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6157. EXPECT_EQ(StatusCode::OK_200, res->status);
  6158. EXPECT_EQ(std::string("123456789"), res->body);
  6159. }
  6160. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6161. cli_.set_compress(true);
  6162. auto res = cli_.Put(
  6163. "/put", 3,
  6164. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6165. sink.os << "PUT";
  6166. return true;
  6167. },
  6168. "text/plain");
  6169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6170. EXPECT_EQ(StatusCode::OK_200, res->status);
  6171. EXPECT_EQ("PUT", res->body);
  6172. }
  6173. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6174. cli_.set_compress(true);
  6175. auto res = cli_.Put(
  6176. "/put",
  6177. [](size_t /*offset*/, DataSink &sink) {
  6178. sink.os << "PUT";
  6179. sink.done();
  6180. return true;
  6181. },
  6182. "text/plain");
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. EXPECT_EQ(StatusCode::OK_200, res->status);
  6185. EXPECT_EQ("PUT", res->body);
  6186. }
  6187. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6188. cli_.set_compress(true);
  6189. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. EXPECT_EQ(StatusCode::OK_200, res->status);
  6192. EXPECT_EQ(LARGE_DATA, res->body);
  6193. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6194. }
  6195. #endif
  6196. TEST_F(ServerTest, Patch) {
  6197. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::OK_200, res->status);
  6200. EXPECT_EQ("PATCH", res->body);
  6201. }
  6202. TEST_F(ServerTest, Delete) {
  6203. auto res = cli_.Delete("/delete");
  6204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6205. EXPECT_EQ(StatusCode::OK_200, res->status);
  6206. EXPECT_EQ("DELETE", res->body);
  6207. }
  6208. TEST_F(ServerTest, DeleteContentReceiver) {
  6209. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. EXPECT_EQ(StatusCode::OK_200, res->status);
  6212. EXPECT_EQ("content", res->body);
  6213. }
  6214. TEST_F(ServerTest, Options) {
  6215. auto res = cli_.Options("*");
  6216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6217. EXPECT_EQ(StatusCode::OK_200, res->status);
  6218. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6219. EXPECT_TRUE(res->body.empty());
  6220. }
  6221. TEST_F(ServerTest, URL) {
  6222. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. EXPECT_EQ(StatusCode::OK_200, res->status);
  6225. }
  6226. TEST_F(ServerTest, ArrayParam) {
  6227. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6229. EXPECT_EQ(StatusCode::OK_200, res->status);
  6230. }
  6231. TEST_F(ServerTest, ArrayParamValues) {
  6232. auto res =
  6233. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6235. EXPECT_EQ(StatusCode::OK_200, res->status);
  6236. }
  6237. TEST_F(ServerTest, NoMultipleHeaders) {
  6238. Headers headers = {{"Content-Length", "5"}};
  6239. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6240. "text/plain");
  6241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6242. EXPECT_EQ(StatusCode::OK_200, res->status);
  6243. }
  6244. TEST_F(ServerTest, PostContentReceiver) {
  6245. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. ASSERT_EQ(StatusCode::OK_200, res->status);
  6248. ASSERT_EQ("content", res->body);
  6249. }
  6250. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6251. UploadFormDataItems items = {
  6252. {"text1", "text default", "", ""},
  6253. {"text2", "aωb", "", ""},
  6254. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6255. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6256. {"file3", "", "", "application/octet-stream"},
  6257. };
  6258. auto res = cli_.Post("/content_receiver", items);
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. EXPECT_EQ(StatusCode::OK_200, res->status);
  6261. }
  6262. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6263. UploadFormDataItems items = {
  6264. {"text1", "text default", "", ""},
  6265. {"text2", "aωb", "", ""},
  6266. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6267. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6268. {"file3", "", "", "application/octet-stream"},
  6269. };
  6270. auto boundary = std::string("+++++");
  6271. std::string body;
  6272. for (const auto &item : items) {
  6273. body += "--" + boundary + "\r\n";
  6274. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6275. if (!item.filename.empty()) {
  6276. body += "; filename=\"" + item.filename + "\"";
  6277. }
  6278. body += "\r\n";
  6279. if (!item.content_type.empty()) {
  6280. body += "Content-Type: " + item.content_type + "\r\n";
  6281. }
  6282. body += "\r\n";
  6283. body += item.content + "\r\n";
  6284. }
  6285. body += "--" + boundary + "--\r\n";
  6286. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6287. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6289. EXPECT_EQ(StatusCode::OK_200, res->status);
  6290. }
  6291. TEST(MultipartFormDataTest, FieldEscaping) {
  6292. Server svr;
  6293. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6294. const ContentReader &content_reader) {
  6295. ASSERT_TRUE(req.is_multipart_form_data());
  6296. std::vector<FormData> received;
  6297. content_reader(
  6298. [&](const FormData &file) {
  6299. received.push_back(file);
  6300. return true;
  6301. },
  6302. [&](const char *data, size_t data_length) {
  6303. received.back().content.append(data, data_length);
  6304. return true;
  6305. });
  6306. // '"', CR and LF in names and filenames are escaped following the
  6307. // WHATWG HTML standard, so each part still parses as a single part
  6308. // with no injected headers. Content types get CR/LF escaped too,
  6309. // while '"' (legal there, e.g. quoted charset) is preserved.
  6310. ASSERT_EQ(4U, received.size());
  6311. EXPECT_EQ("na%22me", received[0].name);
  6312. EXPECT_EQ("quoted name", received[0].content);
  6313. EXPECT_EQ("file", received[1].name);
  6314. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6315. received[1].filename);
  6316. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6317. EXPECT_EQ("injected", received[1].content);
  6318. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6319. EXPECT_EQ("my%22file.txt", received[2].filename);
  6320. EXPECT_EQ("cr lf name", received[2].content);
  6321. EXPECT_EQ("typed", received[3].name);
  6322. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6323. received[3].content_type);
  6324. EXPECT_EQ("typed content", received[3].content);
  6325. });
  6326. auto port = svr.bind_to_any_port("localhost");
  6327. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6328. auto se = detail::scope_exit([&] {
  6329. svr.stop();
  6330. t.join();
  6331. ASSERT_FALSE(svr.is_running());
  6332. });
  6333. svr.wait_until_ready();
  6334. Client cli("localhost", port);
  6335. UploadFormDataItems items = {
  6336. {"na\"me", "quoted name", "", ""},
  6337. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6338. "application/octet-stream"},
  6339. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6340. {"typed", "typed content", "",
  6341. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6342. };
  6343. auto res = cli.Post("/post", items);
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::OK_200, res->status);
  6346. }
  6347. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6348. const UploadFormDataItems items = {
  6349. {"name1", "Content 1", "", ""},
  6350. {"name2", "Content 2", "file2.txt", "text/plain"},
  6351. };
  6352. Server svr;
  6353. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6354. const ContentReader &content_reader) {
  6355. ASSERT_TRUE(req.is_multipart_form_data());
  6356. std::vector<FormData> received;
  6357. content_reader(
  6358. [&](const FormData &file) {
  6359. received.push_back(file);
  6360. return true;
  6361. },
  6362. [&](const char *data, size_t data_length) {
  6363. received.back().content.append(data, data_length);
  6364. return true;
  6365. });
  6366. ASSERT_EQ(2U, received.size());
  6367. EXPECT_EQ("name1", received[0].name);
  6368. EXPECT_EQ("Content 1", received[0].content);
  6369. EXPECT_EQ("name2", received[1].name);
  6370. EXPECT_EQ("Content 2", received[1].content);
  6371. EXPECT_EQ("file2.txt", received[1].filename);
  6372. EXPECT_EQ("text/plain", received[1].content_type);
  6373. });
  6374. auto port = svr.bind_to_any_port("localhost");
  6375. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6376. auto se = detail::scope_exit([&] {
  6377. svr.stop();
  6378. t.join();
  6379. ASSERT_FALSE(svr.is_running());
  6380. });
  6381. svr.wait_until_ready();
  6382. Client cli("localhost", port);
  6383. // Whole-body serialization with a generated boundary
  6384. {
  6385. MultipartFormDataWriter writer;
  6386. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6387. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6388. writer.content_type());
  6389. auto body = writer.serialize(items);
  6390. EXPECT_EQ(body.size(), writer.content_length(items));
  6391. auto res = cli.Post("/post", body, writer.content_type());
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::OK_200, res->status);
  6394. }
  6395. // Per-part framing with a custom boundary via a content provider
  6396. {
  6397. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6398. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6399. MultipartFormDataWriter writer("custom-boundary_123");
  6400. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6401. std::string body;
  6402. for (const auto &item : items) {
  6403. body += writer.item_begin(item);
  6404. body += item.content;
  6405. body += MultipartFormDataWriter::item_end();
  6406. }
  6407. body += writer.finish();
  6408. EXPECT_EQ(body.size(), writer.content_length(items));
  6409. auto res = cli.Post(
  6410. "/post", body.size(),
  6411. [&](size_t offset, size_t length, DataSink &sink) {
  6412. sink.write(body.data() + offset, length);
  6413. return true;
  6414. },
  6415. writer.content_type());
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::OK_200, res->status);
  6418. }
  6419. }
  6420. TEST_F(ServerTest, PostContentReceiverGzip) {
  6421. cli_.set_compress(true);
  6422. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. ASSERT_EQ(StatusCode::OK_200, res->status);
  6425. ASSERT_EQ("content", res->body);
  6426. }
  6427. TEST_F(ServerTest, PutContentReceiver) {
  6428. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. ASSERT_EQ(StatusCode::OK_200, res->status);
  6431. ASSERT_EQ("content", res->body);
  6432. }
  6433. TEST_F(ServerTest, PatchContentReceiver) {
  6434. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6436. ASSERT_EQ(StatusCode::OK_200, res->status);
  6437. ASSERT_EQ("content", res->body);
  6438. }
  6439. template <typename ClientType>
  6440. void TestWithHeadersAndContentReceiver(
  6441. ClientType &cli,
  6442. std::function<Result(ClientType &, const std::string &, const Headers &,
  6443. const std::string &, const std::string &,
  6444. ContentReceiver, DownloadProgress)>
  6445. request_func) {
  6446. Headers headers;
  6447. headers.emplace("X-Custom-Header", "test-value");
  6448. std::string received_body;
  6449. auto res = request_func(
  6450. cli, "/content_receiver", headers, "content", "application/json",
  6451. [&](const char *data, size_t data_length) {
  6452. received_body.append(data, data_length);
  6453. return true;
  6454. },
  6455. nullptr);
  6456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6457. EXPECT_EQ(StatusCode::OK_200, res->status);
  6458. EXPECT_EQ("content", received_body);
  6459. }
  6460. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6461. #ifdef CPPHTTPLIB_SSL_ENABLED
  6462. using ClientT = SSLClient;
  6463. #else
  6464. using ClientT = Client;
  6465. #endif
  6466. TestWithHeadersAndContentReceiver<ClientT>(
  6467. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6468. const std::string &body, const std::string &content_type,
  6469. ContentReceiver receiver, DownloadProgress progress) {
  6470. return cli.Post(path, headers, body, content_type, receiver, progress);
  6471. });
  6472. }
  6473. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6474. #ifdef CPPHTTPLIB_SSL_ENABLED
  6475. using ClientT = SSLClient;
  6476. #else
  6477. using ClientT = Client;
  6478. #endif
  6479. TestWithHeadersAndContentReceiver<ClientT>(
  6480. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6481. const std::string &body, const std::string &content_type,
  6482. ContentReceiver receiver, DownloadProgress progress) {
  6483. return cli.Put(path, headers, body, content_type, receiver, progress);
  6484. });
  6485. }
  6486. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6487. #ifdef CPPHTTPLIB_SSL_ENABLED
  6488. using ClientT = SSLClient;
  6489. #else
  6490. using ClientT = Client;
  6491. #endif
  6492. TestWithHeadersAndContentReceiver<ClientT>(
  6493. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6494. const std::string &body, const std::string &content_type,
  6495. ContentReceiver receiver, DownloadProgress progress) {
  6496. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6497. });
  6498. }
  6499. template <typename ClientType>
  6500. void TestWithHeadersAndContentReceiverWithProgress(
  6501. ClientType &cli,
  6502. std::function<Result(ClientType &, const std::string &, const Headers &,
  6503. const std::string &, const std::string &,
  6504. ContentReceiver, DownloadProgress)>
  6505. request_func) {
  6506. Headers headers;
  6507. headers.emplace("X-Test-Header", "progress-test");
  6508. std::string received_body;
  6509. auto progress_called = false;
  6510. auto res = request_func(
  6511. cli, "/content_receiver", headers, "content", "text/plain",
  6512. [&](const char *data, size_t data_length) {
  6513. received_body.append(data, data_length);
  6514. return true;
  6515. },
  6516. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6517. progress_called = true;
  6518. return true;
  6519. });
  6520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. EXPECT_EQ("content", received_body);
  6523. EXPECT_TRUE(progress_called);
  6524. }
  6525. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6526. #ifdef CPPHTTPLIB_SSL_ENABLED
  6527. using ClientT = SSLClient;
  6528. #else
  6529. using ClientT = Client;
  6530. #endif
  6531. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6532. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6533. const std::string &body, const std::string &content_type,
  6534. ContentReceiver receiver, DownloadProgress progress) {
  6535. return cli.Post(path, headers, body, content_type, receiver, progress);
  6536. });
  6537. }
  6538. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6539. #ifdef CPPHTTPLIB_SSL_ENABLED
  6540. using ClientT = SSLClient;
  6541. #else
  6542. using ClientT = Client;
  6543. #endif
  6544. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6545. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6546. const std::string &body, const std::string &content_type,
  6547. ContentReceiver receiver, DownloadProgress progress) {
  6548. return cli.Put(path, headers, body, content_type, receiver, progress);
  6549. });
  6550. }
  6551. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6552. #ifdef CPPHTTPLIB_SSL_ENABLED
  6553. using ClientT = SSLClient;
  6554. #else
  6555. using ClientT = Client;
  6556. #endif
  6557. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6558. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6559. const std::string &body, const std::string &content_type,
  6560. ContentReceiver receiver, DownloadProgress progress) {
  6561. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6562. });
  6563. }
  6564. template <typename ClientType>
  6565. void TestWithHeadersAndContentReceiverError(
  6566. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6567. const Headers &, const std::string &,
  6568. const std::string &, ContentReceiver)>
  6569. request_func) {
  6570. Headers headers;
  6571. headers.emplace("X-Error-Test", "true");
  6572. std::string received_body;
  6573. auto receiver_failed = false;
  6574. auto res =
  6575. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6576. [&](const char *data, size_t data_length) {
  6577. received_body.append(data, data_length);
  6578. receiver_failed = true;
  6579. return false;
  6580. });
  6581. ASSERT_FALSE(res);
  6582. EXPECT_TRUE(receiver_failed);
  6583. }
  6584. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6585. #ifdef CPPHTTPLIB_SSL_ENABLED
  6586. using ClientT = SSLClient;
  6587. #else
  6588. using ClientT = Client;
  6589. #endif
  6590. TestWithHeadersAndContentReceiverError<ClientT>(
  6591. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6592. const std::string &body, const std::string &content_type,
  6593. ContentReceiver receiver) {
  6594. return cli.Post(path, headers, body, content_type, receiver);
  6595. });
  6596. }
  6597. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6598. #ifdef CPPHTTPLIB_SSL_ENABLED
  6599. using ClientT = SSLClient;
  6600. #else
  6601. using ClientT = Client;
  6602. #endif
  6603. TestWithHeadersAndContentReceiverError<ClientT>(
  6604. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6605. const std::string &body, const std::string &content_type,
  6606. ContentReceiver receiver) {
  6607. return cli.Put(path, headers, body, content_type, receiver);
  6608. });
  6609. }
  6610. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6611. #ifdef CPPHTTPLIB_SSL_ENABLED
  6612. using ClientT = SSLClient;
  6613. #else
  6614. using ClientT = Client;
  6615. #endif
  6616. TestWithHeadersAndContentReceiverError<ClientT>(
  6617. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6618. const std::string &body, const std::string &content_type,
  6619. ContentReceiver receiver) {
  6620. return cli.Patch(path, headers, body, content_type, receiver);
  6621. });
  6622. }
  6623. TEST_F(ServerTest, PostQueryStringAndBody) {
  6624. auto res =
  6625. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. ASSERT_EQ(StatusCode::OK_200, res->status);
  6628. }
  6629. TEST_F(ServerTest, HTTP2Magic) {
  6630. Request req;
  6631. req.method = "PRI";
  6632. req.path = "*";
  6633. req.body = "SM";
  6634. auto res = std::make_shared<Response>();
  6635. auto error = Error::Success;
  6636. auto ret = cli_.send(req, *res, error);
  6637. ASSERT_TRUE(ret);
  6638. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6639. }
  6640. TEST_F(ServerTest, KeepAlive) {
  6641. auto res = cli_.Get("/hi");
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::OK_200, res->status);
  6644. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6645. EXPECT_EQ("Hello World!", res->body);
  6646. res = cli_.Get("/hi");
  6647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6648. EXPECT_EQ(StatusCode::OK_200, res->status);
  6649. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6650. EXPECT_EQ("Hello World!", res->body);
  6651. res = cli_.Get("/hi");
  6652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6653. EXPECT_EQ(StatusCode::OK_200, res->status);
  6654. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6655. EXPECT_EQ("Hello World!", res->body);
  6656. res = cli_.Get("/not-exist");
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6659. res = cli_.Post("/empty", "", "text/plain");
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::OK_200, res->status);
  6662. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6663. EXPECT_EQ("empty", res->body);
  6664. EXPECT_EQ("close", res->get_header_value("Connection"));
  6665. res = cli_.Post(
  6666. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6667. "text/plain");
  6668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6669. EXPECT_EQ(StatusCode::OK_200, res->status);
  6670. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6671. EXPECT_EQ("empty", res->body);
  6672. cli_.set_keep_alive(false);
  6673. res = cli_.Get("/last-request");
  6674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6675. EXPECT_EQ(StatusCode::OK_200, res->status);
  6676. EXPECT_EQ("close", res->get_header_value("Connection"));
  6677. }
  6678. TEST_F(ServerTest, TooManyRedirect) {
  6679. cli_.set_follow_location(true);
  6680. auto res = cli_.Get("/redirect/0");
  6681. ASSERT_TRUE(!res);
  6682. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6683. }
  6684. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6685. Request req;
  6686. req.method = "FOOBAR";
  6687. req.path = "/hi";
  6688. cli_.set_keep_alive(true);
  6689. auto res = cli_.send(req);
  6690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6691. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6692. EXPECT_EQ("close", res->get_header_value("Connection"));
  6693. EXPECT_FALSE(cli_.is_socket_open());
  6694. }
  6695. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6696. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6697. TEST_F(ServerTest, Gzip) {
  6698. Headers headers;
  6699. headers.emplace("Accept-Encoding", "gzip, deflate");
  6700. auto res = cli_.Get("/compress", headers);
  6701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6702. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6704. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6705. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6706. "7890123456789012345678901234567890",
  6707. res->body);
  6708. EXPECT_EQ(StatusCode::OK_200, res->status);
  6709. }
  6710. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6711. Headers headers;
  6712. headers.emplace("Accept-Encoding", "gzip, deflate");
  6713. auto res = cli_.Get("/compress-with-charset", headers);
  6714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6715. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6716. EXPECT_EQ("application/json; charset=utf-8",
  6717. res->get_header_value("Content-Type"));
  6718. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6719. "7890123456789012345678901234567890",
  6720. res->body);
  6721. EXPECT_EQ(StatusCode::OK_200, res->status);
  6722. }
  6723. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6724. Headers headers;
  6725. headers.emplace("Accept-Encoding", "");
  6726. auto res = cli_.Get("/compress", headers);
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6729. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6730. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6731. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6732. "7890123456789012345678901234567890",
  6733. res->body);
  6734. EXPECT_EQ(StatusCode::OK_200, res->status);
  6735. }
  6736. TEST_F(ServerTest, GzipWithContentReceiver) {
  6737. Headers headers;
  6738. headers.emplace("Accept-Encoding", "gzip, deflate");
  6739. std::string body;
  6740. auto res = cli_.Get("/compress", headers,
  6741. [&](const char *data, uint64_t data_length) {
  6742. EXPECT_EQ(100U, data_length);
  6743. body.append(data, data_length);
  6744. return true;
  6745. });
  6746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6747. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6748. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6749. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6750. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6751. "7890123456789012345678901234567890",
  6752. body);
  6753. EXPECT_EQ(StatusCode::OK_200, res->status);
  6754. }
  6755. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6756. Headers headers;
  6757. headers.emplace("Accept-Encoding", "gzip, deflate");
  6758. cli_.set_decompress(false);
  6759. auto res = cli_.Get("/compress", headers);
  6760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6761. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6762. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6763. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6764. EXPECT_EQ(33U, res->body.size());
  6765. EXPECT_EQ(StatusCode::OK_200, res->status);
  6766. }
  6767. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6768. Headers headers;
  6769. headers.emplace("Accept-Encoding", "");
  6770. std::string body;
  6771. auto res = cli_.Get("/compress", headers,
  6772. [&](const char *data, uint64_t data_length) {
  6773. EXPECT_EQ(100U, data_length);
  6774. body.append(data, data_length);
  6775. return true;
  6776. });
  6777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6778. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6779. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6780. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6781. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6782. "7890123456789012345678901234567890",
  6783. body);
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. }
  6786. TEST_F(ServerTest, NoGzip) {
  6787. Headers headers;
  6788. headers.emplace("Accept-Encoding", "gzip, deflate");
  6789. auto res = cli_.Get("/nocompress", headers);
  6790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6791. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6792. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6793. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6794. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6795. "7890123456789012345678901234567890",
  6796. res->body);
  6797. EXPECT_EQ(StatusCode::OK_200, res->status);
  6798. }
  6799. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6800. Headers headers;
  6801. headers.emplace("Accept-Encoding", "gzip, deflate");
  6802. std::string body;
  6803. auto res = cli_.Get("/nocompress", headers,
  6804. [&](const char *data, uint64_t data_length) {
  6805. EXPECT_EQ(100U, data_length);
  6806. body.append(data, data_length);
  6807. return true;
  6808. });
  6809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6810. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6811. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6812. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6813. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6814. "7890123456789012345678901234567890",
  6815. body);
  6816. EXPECT_EQ(StatusCode::OK_200, res->status);
  6817. }
  6818. TEST_F(ServerTest, MultipartFormDataGzip) {
  6819. UploadFormDataItems items = {
  6820. {"key1", "test", "", ""},
  6821. {"key2", "--abcdefg123", "", ""},
  6822. };
  6823. cli_.set_compress(true);
  6824. auto res = cli_.Post("/compress-multipart", items);
  6825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6826. EXPECT_EQ(StatusCode::OK_200, res->status);
  6827. }
  6828. #endif
  6829. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6830. TEST_F(ServerTest, Brotli) {
  6831. Headers headers;
  6832. headers.emplace("Accept-Encoding", "br");
  6833. auto res = cli_.Get("/compress", headers);
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6837. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6838. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6839. "7890123456789012345678901234567890",
  6840. res->body);
  6841. EXPECT_EQ(StatusCode::OK_200, res->status);
  6842. }
  6843. #endif
  6844. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6845. TEST_F(ServerTest, Zstd) {
  6846. Headers headers;
  6847. headers.emplace("Accept-Encoding", "zstd");
  6848. auto res = cli_.Get("/compress", headers);
  6849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6850. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6851. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6852. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6853. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6854. "7890123456789012345678901234567890",
  6855. res->body);
  6856. EXPECT_EQ(StatusCode::OK_200, res->status);
  6857. }
  6858. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6859. Headers headers;
  6860. headers.emplace("Accept-Encoding", "");
  6861. auto res = cli_.Get("/compress", headers);
  6862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6863. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6864. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6865. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6866. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6867. "7890123456789012345678901234567890",
  6868. res->body);
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. }
  6871. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6872. Headers headers;
  6873. headers.emplace("Accept-Encoding", "zstd");
  6874. std::string body;
  6875. auto res = cli_.Get("/compress", headers,
  6876. [&](const char *data, uint64_t data_length) {
  6877. EXPECT_EQ(100U, data_length);
  6878. body.append(data, data_length);
  6879. return true;
  6880. });
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6884. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6885. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6886. "7890123456789012345678901234567890",
  6887. body);
  6888. EXPECT_EQ(StatusCode::OK_200, res->status);
  6889. }
  6890. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6891. Headers headers;
  6892. headers.emplace("Accept-Encoding", "zstd");
  6893. cli_.set_decompress(false);
  6894. auto res = cli_.Get("/compress", headers);
  6895. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6896. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6897. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6898. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6901. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6902. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6903. EXPECT_EQ(StatusCode::OK_200, res->status);
  6904. ASSERT_EQ(26U, res->body.size());
  6905. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6906. 0);
  6907. }
  6908. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6909. Headers headers;
  6910. headers.emplace("Accept-Encoding", "");
  6911. std::string body;
  6912. auto res = cli_.Get("/compress", headers,
  6913. [&](const char *data, uint64_t data_length) {
  6914. EXPECT_EQ(100U, data_length);
  6915. body.append(data, data_length);
  6916. return true;
  6917. });
  6918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6919. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6920. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6921. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6922. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6923. "7890123456789012345678901234567890",
  6924. body);
  6925. EXPECT_EQ(StatusCode::OK_200, res->status);
  6926. }
  6927. TEST_F(ServerTest, NoZstd) {
  6928. Headers headers;
  6929. headers.emplace("Accept-Encoding", "zstd");
  6930. auto res = cli_.Get("/nocompress", headers);
  6931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6932. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6933. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6934. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6935. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6936. "7890123456789012345678901234567890",
  6937. res->body);
  6938. EXPECT_EQ(StatusCode::OK_200, res->status);
  6939. }
  6940. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6941. Headers headers;
  6942. headers.emplace("Accept-Encoding", "zstd");
  6943. std::string body;
  6944. auto res = cli_.Get("/nocompress", headers,
  6945. [&](const char *data, uint64_t data_length) {
  6946. EXPECT_EQ(100U, data_length);
  6947. body.append(data, data_length);
  6948. return true;
  6949. });
  6950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6951. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6952. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6953. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6954. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6955. "7890123456789012345678901234567890",
  6956. body);
  6957. EXPECT_EQ(StatusCode::OK_200, res->status);
  6958. }
  6959. // TODO: How to enable zstd ??
  6960. TEST_F(ServerTest, MultipartFormDataZstd) {
  6961. UploadFormDataItems items = {
  6962. {"key1", "test", "", ""},
  6963. {"key2", "--abcdefg123", "", ""},
  6964. };
  6965. Headers headers;
  6966. headers.emplace("Accept-Encoding", "zstd");
  6967. cli_.set_compress(true);
  6968. auto res = cli_.Post("/compress-multipart", headers, items);
  6969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6970. EXPECT_EQ(StatusCode::OK_200, res->status);
  6971. }
  6972. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6973. Headers headers;
  6974. headers.emplace("Accept-Encoding", "zstd");
  6975. cli_.set_compress(true);
  6976. auto res = cli_.Put(
  6977. "/put", headers, 3,
  6978. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6979. sink.os << "PUT";
  6980. return true;
  6981. },
  6982. "text/plain");
  6983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6984. EXPECT_EQ(StatusCode::OK_200, res->status);
  6985. EXPECT_EQ("PUT", res->body);
  6986. }
  6987. // Pre-compression logging tests
  6988. TEST_F(ServerTest, PreCompressionLogging) {
  6989. // Test data for compression (matches the actual /compress endpoint content)
  6990. const std::string test_content =
  6991. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6992. "3456789012345678901234567890";
  6993. // Variables to capture logging data
  6994. std::string pre_compression_body;
  6995. std::string pre_compression_content_type;
  6996. std::string pre_compression_content_encoding;
  6997. std::string post_compression_body;
  6998. std::string post_compression_content_type;
  6999. std::string post_compression_content_encoding;
  7000. // Set up pre-compression logger
  7001. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  7002. const Response &res) {
  7003. pre_compression_body = res.body;
  7004. pre_compression_content_type = res.get_header_value("Content-Type");
  7005. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  7006. });
  7007. // Set up post-compression logger
  7008. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7009. post_compression_body = res.body;
  7010. post_compression_content_type = res.get_header_value("Content-Type");
  7011. post_compression_content_encoding =
  7012. res.get_header_value("Content-Encoding");
  7013. });
  7014. // Test with gzip compression
  7015. Headers headers;
  7016. headers.emplace("Accept-Encoding", "gzip");
  7017. auto res = cli_.Get("/compress", headers);
  7018. // Verify response was compressed
  7019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7020. EXPECT_EQ(StatusCode::OK_200, res->status);
  7021. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7022. // Verify pre-compression logger captured uncompressed content
  7023. EXPECT_EQ(test_content, pre_compression_body);
  7024. EXPECT_EQ("text/plain", pre_compression_content_type);
  7025. EXPECT_TRUE(pre_compression_content_encoding
  7026. .empty()); // No encoding header before compression
  7027. // Verify post-compression logger captured compressed content
  7028. EXPECT_NE(test_content,
  7029. post_compression_body); // Should be different after compression
  7030. EXPECT_EQ("text/plain", post_compression_content_type);
  7031. EXPECT_EQ("gzip", post_compression_content_encoding);
  7032. // Verify compressed content is smaller
  7033. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7034. }
  7035. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7036. const std::string test_content =
  7037. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7038. "3456789012345678901234567890";
  7039. std::string pre_compression_body;
  7040. std::string post_compression_body;
  7041. svr_.set_pre_compression_logger(
  7042. [&](const Request & /*req*/, const Response &res) {
  7043. pre_compression_body = res.body;
  7044. });
  7045. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7046. post_compression_body = res.body;
  7047. });
  7048. Headers headers;
  7049. headers.emplace("Accept-Encoding", "br");
  7050. auto res = cli_.Get("/compress", headers);
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. EXPECT_EQ(StatusCode::OK_200, res->status);
  7053. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7054. // Verify pre-compression content is uncompressed
  7055. EXPECT_EQ(test_content, pre_compression_body);
  7056. // Verify post-compression content is compressed
  7057. EXPECT_NE(test_content, post_compression_body);
  7058. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7059. }
  7060. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7061. const std::string test_content =
  7062. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7063. "3456789012345678901234567890";
  7064. std::string pre_compression_body;
  7065. std::string post_compression_body;
  7066. svr_.set_pre_compression_logger(
  7067. [&](const Request & /*req*/, const Response &res) {
  7068. pre_compression_body = res.body;
  7069. });
  7070. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7071. post_compression_body = res.body;
  7072. });
  7073. // Request without compression (use /nocompress endpoint)
  7074. Headers headers;
  7075. auto res = cli_.Get("/nocompress", headers);
  7076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7077. EXPECT_EQ(StatusCode::OK_200, res->status);
  7078. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7079. // Pre-compression logger should not be called when no compression is applied
  7080. EXPECT_TRUE(
  7081. pre_compression_body.empty()); // Pre-compression logger not called
  7082. EXPECT_EQ(
  7083. test_content,
  7084. post_compression_body); // Post-compression logger captures final content
  7085. }
  7086. TEST_F(ServerTest, LoggerSeesContentLength) {
  7087. size_t logged_content_length = 0;
  7088. std::string logged_content_length_header;
  7089. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7090. logged_content_length = res.content_length_;
  7091. logged_content_length_header = res.get_header_value("Content-Length");
  7092. });
  7093. auto res = cli_.Get("/nocompress");
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. EXPECT_EQ(StatusCode::OK_200, res->status);
  7096. EXPECT_EQ(res->body.size(), logged_content_length);
  7097. EXPECT_EQ(std::to_string(logged_content_length),
  7098. logged_content_length_header);
  7099. }
  7100. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7101. const std::string test_content =
  7102. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7103. "3456789012345678901234567890";
  7104. std::string pre_compression_body;
  7105. bool pre_logger_called = false;
  7106. // Set only pre-compression logger
  7107. svr_.set_pre_compression_logger(
  7108. [&](const Request & /*req*/, const Response &res) {
  7109. pre_compression_body = res.body;
  7110. pre_logger_called = true;
  7111. });
  7112. Headers headers;
  7113. headers.emplace("Accept-Encoding", "gzip");
  7114. auto res = cli_.Get("/compress", headers);
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::OK_200, res->status);
  7117. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7118. // Verify pre-compression logger was called
  7119. EXPECT_TRUE(pre_logger_called);
  7120. EXPECT_EQ(test_content, pre_compression_body);
  7121. }
  7122. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7123. {
  7124. // Test with Expect: 100-continue header - success case
  7125. // Server returns 100 Continue, client sends body, server returns 200 OK
  7126. Request req;
  7127. req.method = "POST";
  7128. req.path = "/post-large";
  7129. req.set_header("Expect", "100-continue");
  7130. req.body = LARGE_DATA;
  7131. Response res;
  7132. auto error = Error::Success;
  7133. cli_.set_keep_alive(true);
  7134. auto ret = cli_.send(req, res, error);
  7135. EXPECT_TRUE(ret);
  7136. EXPECT_EQ(StatusCode::OK_200, res.status);
  7137. EXPECT_EQ(LARGE_DATA, res.body);
  7138. }
  7139. {
  7140. // Test with Expect: 100-continue header - error case
  7141. // Client should not send the body when server returns an error
  7142. Request req;
  7143. req.method = "POST";
  7144. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7145. req.set_header("Expect", "100-continue");
  7146. req.body = LARGE_DATA;
  7147. Response res;
  7148. auto error = Error::Success;
  7149. auto start = std::chrono::high_resolution_clock::now();
  7150. cli_.set_keep_alive(true);
  7151. auto ret = cli_.send(req, res, error);
  7152. auto end = std::chrono::high_resolution_clock::now();
  7153. auto elapsed =
  7154. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7155. .count();
  7156. // With Expect: 100-continue, request completes successfully but with error
  7157. EXPECT_TRUE(ret);
  7158. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7159. EXPECT_EQ("close", res.get_header_value("Connection"));
  7160. EXPECT_FALSE(cli_.is_socket_open());
  7161. EXPECT_LE(elapsed, 2000);
  7162. }
  7163. {
  7164. // Send an extra GET request to ensure error recovery without hanging
  7165. Request req;
  7166. req.method = "GET";
  7167. req.path = "/hi";
  7168. auto start = std::chrono::high_resolution_clock::now();
  7169. auto res = cli_.send(req);
  7170. auto end = std::chrono::high_resolution_clock::now();
  7171. auto elapsed =
  7172. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7173. .count();
  7174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7175. EXPECT_EQ(StatusCode::OK_200, res->status);
  7176. EXPECT_EQ("Hello World!", res->body);
  7177. EXPECT_LE(elapsed, 500);
  7178. }
  7179. }
  7180. TEST(ZstdDecompressor, ChunkedDecompression) {
  7181. std::string data;
  7182. for (size_t i = 0; i < 32 * 1024; ++i) {
  7183. data.push_back(static_cast<char>('a' + i % 26));
  7184. }
  7185. std::string compressed_data;
  7186. {
  7187. httplib::detail::zstd_compressor compressor;
  7188. bool result = compressor.compress(
  7189. data.data(), data.size(),
  7190. /*last=*/true,
  7191. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7192. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7193. compressed_data_size);
  7194. return true;
  7195. });
  7196. ASSERT_TRUE(result);
  7197. }
  7198. std::string decompressed_data;
  7199. {
  7200. httplib::detail::zstd_decompressor decompressor;
  7201. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7202. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7203. size_t chunk_size = 130;
  7204. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7205. chunk_begin += chunk_size) {
  7206. size_t current_chunk_size =
  7207. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7208. bool result = decompressor.decompress(
  7209. compressed_data.data() + chunk_begin, current_chunk_size,
  7210. [&](const char *decompressed_data_chunk,
  7211. size_t decompressed_data_chunk_size) {
  7212. decompressed_data.insert(decompressed_data.size(),
  7213. decompressed_data_chunk,
  7214. decompressed_data_chunk_size);
  7215. return true;
  7216. });
  7217. ASSERT_TRUE(result);
  7218. }
  7219. }
  7220. ASSERT_EQ(data, decompressed_data);
  7221. }
  7222. TEST(ZstdDecompressor, Decompress) {
  7223. std::string original_text = "Compressed with ZSTD";
  7224. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7225. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7226. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7227. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7228. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7229. std::string decompressed_data;
  7230. {
  7231. httplib::detail::zstd_decompressor decompressor;
  7232. bool result = decompressor.decompress(
  7233. compressed_data.data(), compressed_data.size(),
  7234. [&](const char *decompressed_data_chunk,
  7235. size_t decompressed_data_chunk_size) {
  7236. decompressed_data.insert(decompressed_data.size(),
  7237. decompressed_data_chunk,
  7238. decompressed_data_chunk_size);
  7239. return true;
  7240. });
  7241. ASSERT_TRUE(result);
  7242. }
  7243. ASSERT_EQ(original_text, decompressed_data);
  7244. }
  7245. #endif
  7246. // Sends a raw request to a server listening at HOST:PORT.
  7247. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7248. std::string *resp = nullptr, int port = PORT) {
  7249. auto error = Error::Success;
  7250. auto client_sock = detail::create_client_socket(
  7251. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7252. /*connection_timeout_sec=*/5, 0,
  7253. /*read_timeout_sec=*/5, 0,
  7254. /*write_timeout_sec=*/5, 0, std::string(), error);
  7255. if (client_sock == INVALID_SOCKET) { return false; }
  7256. auto ret = detail::process_client_socket(
  7257. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7258. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7259. if (req.size() !=
  7260. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7261. return false;
  7262. }
  7263. char buf[512];
  7264. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7265. while (line_reader.getline()) {
  7266. if (resp) { *resp += line_reader.ptr(); }
  7267. }
  7268. return true;
  7269. });
  7270. detail::close_socket(client_sock);
  7271. return ret;
  7272. }
  7273. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7274. Server svr;
  7275. std::string header_value;
  7276. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7277. header_value = req.get_header_value("foo");
  7278. res.set_content("ok", "text/plain");
  7279. });
  7280. thread t = thread([&] { svr.listen(HOST, PORT); });
  7281. auto se = detail::scope_exit([&] {
  7282. svr.stop();
  7283. t.join();
  7284. ASSERT_FALSE(svr.is_running());
  7285. });
  7286. svr.wait_until_ready();
  7287. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7288. // like characters are not treated the same - use vertical tab and escape.
  7289. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7290. "foo: \t \v bar \x1B\t \r\n"
  7291. "Connection: close\r\n"
  7292. "\r\n";
  7293. std::string res;
  7294. ASSERT_TRUE(send_request(5, req, &res));
  7295. EXPECT_EQ(header_value, "");
  7296. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7297. }
  7298. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7299. Server svr;
  7300. std::string received;
  7301. svr.Get("/order", [&](const Request &req, Response &res) {
  7302. received = entries_to_string(req.headers);
  7303. res.set_content("ok", "text/plain");
  7304. });
  7305. auto port = svr.bind_to_any_port(HOST);
  7306. thread t = thread([&] { svr.listen_after_bind(); });
  7307. auto se = detail::scope_exit([&] {
  7308. svr.stop();
  7309. t.join();
  7310. ASSERT_FALSE(svr.is_running());
  7311. });
  7312. svr.wait_until_ready();
  7313. const std::string req = "GET /order HTTP/1.1\r\n"
  7314. "X-First: 1\r\n"
  7315. "X-Dup: a\r\n"
  7316. "X-Second: 2\r\n"
  7317. "X-Dup: b\r\n"
  7318. "Connection: close\r\n"
  7319. "\r\n";
  7320. std::string res;
  7321. ASSERT_TRUE(send_request(5, req, &res, port));
  7322. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7323. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7324. }
  7325. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7326. Server svr;
  7327. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7328. res.set_header("Set-Cookie", "first=1");
  7329. res.set_header("X-Between", "y");
  7330. res.set_header("Set-Cookie", "second=2");
  7331. res.set_content("ok", "text/plain");
  7332. });
  7333. auto port = svr.bind_to_any_port(HOST);
  7334. thread t = thread([&] { svr.listen_after_bind(); });
  7335. auto se = detail::scope_exit([&] {
  7336. svr.stop();
  7337. t.join();
  7338. ASSERT_FALSE(svr.is_running());
  7339. });
  7340. svr.wait_until_ready();
  7341. Client cli(HOST, port);
  7342. auto res = cli.Get("/cookies");
  7343. ASSERT_TRUE(res);
  7344. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7345. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7346. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7347. }
  7348. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7349. Server svr;
  7350. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7351. auto i = new int(0);
  7352. res.set_header("Trailer", "X-Safe, X-Reflected");
  7353. res.set_chunked_content_provider(
  7354. "text/plain",
  7355. [i](size_t /*offset*/, DataSink &sink) {
  7356. if (*i == 0) {
  7357. sink.os << "body";
  7358. } else {
  7359. Headers trailer;
  7360. // A valid trailer that must survive.
  7361. trailer.emplace("X-Safe", "safe");
  7362. // Attacker-controlled value carrying CR/LF (response splitting).
  7363. trailer.emplace("X-Reflected",
  7364. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7365. // Attacker-controlled name carrying CR/LF.
  7366. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7367. sink.done_with_trailer(trailer);
  7368. }
  7369. (*i)++;
  7370. return true;
  7371. },
  7372. [i](bool /*success*/) { delete i; });
  7373. });
  7374. thread t = thread([&] { svr.listen(HOST, PORT); });
  7375. auto se = detail::scope_exit([&] {
  7376. svr.stop();
  7377. t.join();
  7378. ASSERT_FALSE(svr.is_running());
  7379. });
  7380. svr.wait_until_ready();
  7381. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7382. "Host: " + HOST +
  7383. "\r\n"
  7384. "Connection: close\r\n"
  7385. "\r\n";
  7386. std::string res;
  7387. ASSERT_TRUE(send_request(5, req, &res));
  7388. // The injected fields must not appear anywhere in the raw response.
  7389. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7390. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7391. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7392. // Invalid trailers are dropped entirely, matching set_header().
  7393. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7394. // The valid trailer still passes through.
  7395. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7396. }
  7397. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7398. Server svr;
  7399. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7400. // res.headers is a public field an application can populate directly,
  7401. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7402. // A valid header that must survive.
  7403. res.headers.emplace("X-Safe", "safe");
  7404. // Attacker-controlled value carrying CR/LF (response splitting).
  7405. res.headers.emplace("X-Reflected",
  7406. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7407. // Attacker-controlled name carrying CR/LF.
  7408. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7409. res.set_content("body", "text/plain");
  7410. });
  7411. thread t = thread([&] { svr.listen(HOST, PORT); });
  7412. auto se = detail::scope_exit([&] {
  7413. svr.stop();
  7414. t.join();
  7415. ASSERT_FALSE(svr.is_running());
  7416. });
  7417. svr.wait_until_ready();
  7418. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7419. "Host: " + HOST +
  7420. "\r\n"
  7421. "Connection: close\r\n"
  7422. "\r\n";
  7423. std::string res;
  7424. ASSERT_TRUE(send_request(5, req, &res));
  7425. // The injected fields must not appear anywhere in the raw response.
  7426. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7427. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7428. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7429. // Invalid headers are dropped entirely, matching set_header().
  7430. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7431. // The valid header still passes through.
  7432. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7433. }
  7434. // Forward declaration: in split builds split.py strips `inline` and moves the
  7435. // definition into httplib.cc, so detail::write_request_line is not visible from
  7436. // the public httplib.h. Re-declaring it here lets the tests link against the
  7437. // symbol in both header-only and split builds.
  7438. namespace httplib {
  7439. namespace detail {
  7440. ssize_t write_request_line(Stream &strm, const std::string &method,
  7441. const std::string &path);
  7442. } // namespace detail
  7443. } // namespace httplib
  7444. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7445. // A well-formed target is written verbatim.
  7446. {
  7447. detail::BufferStream strm;
  7448. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7449. EXPECT_GT(n, 0);
  7450. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7451. }
  7452. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7453. // otherwise it splits the request line and injects a header or a whole
  7454. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7455. // when path encoding is disabled.
  7456. const std::string evil_targets[] = {
  7457. "/a\r\nInjected: pwned",
  7458. "/a\rInjected",
  7459. "/a\nInjected",
  7460. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7461. };
  7462. for (const auto &evil : evil_targets) {
  7463. detail::BufferStream strm;
  7464. auto n = detail::write_request_line(strm, "GET", evil);
  7465. EXPECT_LT(n, 0);
  7466. EXPECT_TRUE(strm.get_buffer().empty());
  7467. }
  7468. }
  7469. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7470. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7471. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7472. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7473. // client must fail cleanly with Error::Write instead of putting a
  7474. // request-line-less, header-injecting request on the wire.
  7475. Server svr;
  7476. svr.Get("/a", [](const Request &, Response &res) {
  7477. res.set_content("ok", "text/plain");
  7478. });
  7479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7480. auto se = detail::scope_exit([&] {
  7481. svr.stop();
  7482. thread.join();
  7483. ASSERT_FALSE(svr.is_running());
  7484. });
  7485. svr.wait_until_ready();
  7486. {
  7487. Client cli(HOST, PORT);
  7488. cli.set_path_encode(false);
  7489. // The request is rejected before anything is written, so the connection
  7490. // stays silent and the subsequent response read would otherwise block for
  7491. // the full default read timeout. Shorten it -- the assertion is on the
  7492. // error, not the timeout.
  7493. cli.set_read_timeout(1, 0);
  7494. auto res = cli.Get("/a\r\nInjected: pwned");
  7495. EXPECT_FALSE(res);
  7496. EXPECT_EQ(Error::Write, res.error());
  7497. }
  7498. }
  7499. // Sends a raw request and verifies that there isn't a crash or exception.
  7500. static void test_raw_request(const std::string &req,
  7501. std::string *out = nullptr) {
  7502. Server svr;
  7503. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7504. res.set_content("ok", "text/plain");
  7505. });
  7506. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7507. res.set_content("ok", "text/plain");
  7508. });
  7509. svr.Get("/header_field_value_check",
  7510. [&](const Request & /*req*/, Response &res) {
  7511. res.set_content("ok", "text/plain");
  7512. });
  7513. // Server read timeout must be longer than the client read timeout for the
  7514. // bug to reproduce, probably to force the server to process a request
  7515. // without a trailing blank line.
  7516. const time_t client_read_timeout_sec = 1;
  7517. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7518. bool listen_thread_ok = false;
  7519. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7520. auto se = detail::scope_exit([&] {
  7521. svr.stop();
  7522. t.join();
  7523. ASSERT_FALSE(svr.is_running());
  7524. EXPECT_TRUE(listen_thread_ok);
  7525. });
  7526. svr.wait_until_ready();
  7527. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7528. }
  7529. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7530. // A certain header line causes an exception if the header property is parsed
  7531. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7532. test_raw_request(
  7533. "GET /hi HTTP/1.1\r\n"
  7534. " : "
  7535. " "
  7536. " ");
  7537. }
  7538. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7539. // A certain header line causes an exception if the header property *name* is
  7540. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7541. // greedy matcher and requires backtracking when there are a lot of ":"
  7542. // characters.
  7543. // This occurs with libc++ but not libstdc++.
  7544. test_raw_request(
  7545. "GET /hi HTTP/1.1\r\n"
  7546. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7547. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7548. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7549. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7550. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7551. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7552. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7553. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7554. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7555. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7556. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7557. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7558. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7559. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7560. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7561. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7562. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7563. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7564. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7565. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7566. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7567. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7568. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7569. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7570. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7571. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7572. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7573. "&&&%%%");
  7574. }
  7575. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7576. // Make sure this doesn't crash the server.
  7577. // In a previous version of the header line regex, the "\r" rendered the line
  7578. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7579. // a new position where the leading white space ended and the field value
  7580. // began.
  7581. // The crash occurs with libc++ but not libstdc++.
  7582. test_raw_request("GET /hi HTTP/1.1\r\n"
  7583. "a:" +
  7584. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7585. "\r\n"
  7586. "\r\n");
  7587. }
  7588. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7589. std::string out;
  7590. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7591. "Content-Type: text/plain\r\n"
  7592. "Transfer-Encoding: chunked\r\n"
  7593. "\r\n"
  7594. "nothex\r\n",
  7595. &out);
  7596. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7597. }
  7598. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7599. std::string out;
  7600. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7601. "Content-Type: text/plain\r\n"
  7602. "Transfer-Encoding: chunked\r\n"
  7603. "\r\n"
  7604. "3\r\n"
  7605. "xyz\r\n"
  7606. "NaN\r\n",
  7607. &out);
  7608. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7609. }
  7610. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7611. std::string out;
  7612. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7613. "Content-Type: text/plain\r\n"
  7614. "Transfer-Encoding: chunked\r\n"
  7615. "\r\n"
  7616. // Length is too large for 64 bits.
  7617. "1ffffffffffffffff\r\n"
  7618. "xyz\r\n",
  7619. &out);
  7620. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7621. }
  7622. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7623. test_raw_request("GET /hi HTTP/1.1\r\n"
  7624. "Content-Type: text/plain\r\n\r");
  7625. }
  7626. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7627. std::string out;
  7628. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7629. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7630. }
  7631. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7632. Server svr;
  7633. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7634. EXPECT_TRUE(!req.remote_addr.empty());
  7635. });
  7636. thread t = thread([&] { svr.listen(HOST, PORT); });
  7637. auto se = detail::scope_exit([&] {
  7638. svr.stop();
  7639. t.join();
  7640. ASSERT_FALSE(svr.is_running());
  7641. });
  7642. svr.wait_until_ready();
  7643. // Send an invalid request line to trigger Bad Request
  7644. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7645. std::string out;
  7646. ASSERT_TRUE(send_request(5, bad_req, &out));
  7647. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7648. }
  7649. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7650. std::string out;
  7651. std::string request(
  7652. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7653. test_raw_request(request, &out);
  7654. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7655. }
  7656. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7657. std::string out;
  7658. std::string request(
  7659. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7660. test_raw_request(request, &out);
  7661. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7662. }
  7663. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7664. std::string out;
  7665. std::string request(
  7666. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7667. test_raw_request(request, &out);
  7668. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7669. }
  7670. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7671. std::string out;
  7672. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7673. "Test: \r\n\r\n",
  7674. &out);
  7675. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7676. }
  7677. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7678. Server svr;
  7679. std::string x_custom;
  7680. std::string cookie;
  7681. std::string xff;
  7682. std::string x_unicode;
  7683. std::string x_iis;
  7684. svr.Get("/check", [&](const Request &req, Response &res) {
  7685. x_custom = req.get_header_value("X-Custom");
  7686. cookie = req.get_header_value("Cookie");
  7687. xff = req.get_header_value("X-Forwarded-For");
  7688. x_unicode = req.get_header_value("X-Unicode");
  7689. x_iis = req.get_header_value("X-IIS");
  7690. res.set_content("ok", "text/plain");
  7691. });
  7692. thread t = thread([&] { svr.listen(HOST, PORT); });
  7693. auto se = detail::scope_exit([&] {
  7694. svr.stop();
  7695. t.join();
  7696. ASSERT_FALSE(svr.is_running());
  7697. });
  7698. svr.wait_until_ready();
  7699. const std::string req = "GET /check HTTP/1.1\r\n"
  7700. "Host: localhost\r\n"
  7701. "X-Custom: a%0D%0AInjected: b\r\n"
  7702. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7703. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7704. "X-Unicode: %E3%81%82\r\n"
  7705. "X-IIS: %u00E9\r\n"
  7706. "Connection: close\r\n"
  7707. "\r\n";
  7708. std::string res;
  7709. ASSERT_TRUE(send_request(5, req, &res));
  7710. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7711. // Every value must be returned verbatim (wire form), with no decoding.
  7712. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7713. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7714. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7715. EXPECT_EQ("%E3%81%82", x_unicode);
  7716. EXPECT_EQ("%u00E9", x_iis);
  7717. }
  7718. // Applications that previously relied on automatic percent-decoding can
  7719. // reproduce the old behavior by explicitly calling decode_path_component()
  7720. // or, for RFC 3986 conformance, decode_uri_component().
  7721. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7722. Server svr;
  7723. std::string decoded;
  7724. svr.Get("/check", [&](const Request &req, Response &res) {
  7725. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7726. res.set_content("ok", "text/plain");
  7727. });
  7728. thread t = thread([&] { svr.listen(HOST, PORT); });
  7729. auto se = detail::scope_exit([&] {
  7730. svr.stop();
  7731. t.join();
  7732. ASSERT_FALSE(svr.is_running());
  7733. });
  7734. svr.wait_until_ready();
  7735. const std::string req = "GET /check HTTP/1.1\r\n"
  7736. "Host: localhost\r\n"
  7737. "X-Custom: hello%20world\r\n"
  7738. "Connection: close\r\n"
  7739. "\r\n";
  7740. std::string res;
  7741. ASSERT_TRUE(send_request(5, req, &res));
  7742. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7743. EXPECT_EQ("hello world", decoded);
  7744. }
  7745. // Regression test for #2033. Browsers send Referer values that include
  7746. // percent-encoded characters such as %0A inside the URL. Decoding the
  7747. // header value would either trip the post-decode CR/LF/NUL guard (the
  7748. // original bug, returning 400) or, after that guard was relaxed, silently
  7749. // store a literal LF — both unacceptable. The wire form must round-trip.
  7750. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7751. Server svr;
  7752. std::string referer;
  7753. svr.Get("/check", [&](const Request &req, Response &res) {
  7754. referer = req.get_header_value("Referer");
  7755. res.set_content("ok", "text/plain");
  7756. });
  7757. thread t = thread([&] { svr.listen(HOST, PORT); });
  7758. auto se = detail::scope_exit([&] {
  7759. svr.stop();
  7760. t.join();
  7761. ASSERT_FALSE(svr.is_running());
  7762. });
  7763. svr.wait_until_ready();
  7764. const std::string req = "GET /check HTTP/1.1\r\n"
  7765. "Host: localhost\r\n"
  7766. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7767. "Connection: close\r\n"
  7768. "\r\n";
  7769. std::string res;
  7770. ASSERT_TRUE(send_request(5, req, &res));
  7771. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7772. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7773. }
  7774. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7775. Server svr;
  7776. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7777. res.set_header("Cache-Control", "no-cache");
  7778. res.set_chunked_content_provider(
  7779. "text/event-stream", [](size_t offset, DataSink &sink) {
  7780. std::string s = "data:";
  7781. s += std::to_string(offset);
  7782. s += "\n\n";
  7783. auto ret = sink.write(s.data(), s.size());
  7784. EXPECT_TRUE(ret);
  7785. std::this_thread::sleep_for(std::chrono::seconds(1));
  7786. return true;
  7787. });
  7788. });
  7789. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7790. svr.wait_until_ready();
  7791. Client client(HOST, PORT);
  7792. const Headers headers = {{"Accept", "text/event-stream"}};
  7793. auto get_thread = std::thread([&client, &headers]() {
  7794. auto res = client.Get(
  7795. "/events", headers,
  7796. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7797. });
  7798. auto se = detail::scope_exit([&] {
  7799. svr.stop();
  7800. get_thread.join();
  7801. listen_thread.join();
  7802. ASSERT_FALSE(svr.is_running());
  7803. });
  7804. // Give GET time to get a few messages.
  7805. std::this_thread::sleep_for(std::chrono::seconds(2));
  7806. }
  7807. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7808. httplib::Server svr;
  7809. svr.Post("/hi",
  7810. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7811. res.status = StatusCode::OK_200;
  7812. });
  7813. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7814. svr.wait_until_ready();
  7815. Client cli(HOST, PORT);
  7816. auto res = cli.Post("/hi", "data", "text/plain");
  7817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7818. EXPECT_EQ(StatusCode::OK_200, res->status);
  7819. svr.stop();
  7820. thread.join();
  7821. ASSERT_FALSE(svr.is_running());
  7822. res = cli.Post("/hi", "data", "text/plain");
  7823. ASSERT_FALSE(res);
  7824. }
  7825. TEST(ServerStopTest, ListenFailure) {
  7826. Server svr;
  7827. auto t = thread([&]() {
  7828. auto ret = svr.listen("????", PORT);
  7829. EXPECT_FALSE(ret);
  7830. });
  7831. svr.wait_until_ready();
  7832. svr.stop();
  7833. t.join();
  7834. }
  7835. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7836. TEST(ServerStopTest, Decommision) {
  7837. Server svr;
  7838. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7839. for (int i = 0; i < 4; i++) {
  7840. auto is_even = !(i % 2);
  7841. std::thread t{[&] {
  7842. try {
  7843. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7844. if (is_even) {
  7845. throw std::runtime_error("Some thing that happens to go wrong.");
  7846. }
  7847. svr.listen(HOST, PORT);
  7848. } catch (...) { svr.decommission(); }
  7849. }};
  7850. svr.wait_until_ready();
  7851. // Server is up
  7852. {
  7853. Client cli(HOST, PORT);
  7854. auto res = cli.Get("/hi");
  7855. if (is_even) {
  7856. EXPECT_FALSE(res);
  7857. } else {
  7858. EXPECT_TRUE(res);
  7859. EXPECT_EQ("hi...", res->body);
  7860. }
  7861. }
  7862. svr.stop();
  7863. t.join();
  7864. // Server is down...
  7865. {
  7866. Client cli(HOST, PORT);
  7867. auto res = cli.Get("/hi");
  7868. EXPECT_FALSE(res);
  7869. }
  7870. }
  7871. }
  7872. #endif
  7873. // Helper function for string body upload progress tests
  7874. template <typename SetupHandler, typename ClientCall>
  7875. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7876. ClientCall &&client_call,
  7877. const string &body) {
  7878. Server svr;
  7879. setup_handler(svr);
  7880. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7881. auto se = detail::scope_exit([&] {
  7882. svr.stop();
  7883. t.join();
  7884. });
  7885. svr.wait_until_ready();
  7886. Client cli(HOST, PORT);
  7887. vector<uint64_t> progress_values;
  7888. bool progress_called = false;
  7889. auto res =
  7890. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7891. progress_values.push_back(current);
  7892. progress_called = true;
  7893. return true;
  7894. });
  7895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7896. EXPECT_EQ(200, res->status);
  7897. EXPECT_TRUE(progress_called);
  7898. }
  7899. TEST(UploadProgressTest, PostStringBodyBasic) {
  7900. TestStringBodyUploadProgress(
  7901. [](Server &svr) {
  7902. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7903. res.set_content("received", "text/plain");
  7904. });
  7905. },
  7906. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7907. return cli.Post("/test", body, "text/plain", progress_callback);
  7908. },
  7909. "test data for upload progress");
  7910. }
  7911. TEST(UploadProgressTest, PutStringBodyBasic) {
  7912. TestStringBodyUploadProgress(
  7913. [](Server &svr) {
  7914. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7915. res.set_content("put received", "text/plain");
  7916. });
  7917. },
  7918. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7919. return cli.Put("/test", body, "text/plain", progress_callback);
  7920. },
  7921. "put test data for upload progress");
  7922. }
  7923. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7924. TestStringBodyUploadProgress(
  7925. [](Server &svr) {
  7926. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7927. res.set_content("patch received", "text/plain");
  7928. });
  7929. },
  7930. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7931. return cli.Patch("/test", body, "text/plain", progress_callback);
  7932. },
  7933. "patch test data for upload progress");
  7934. }
  7935. // Helper function for content provider upload progress tests
  7936. template <typename SetupHandler, typename ClientCall>
  7937. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7938. ClientCall &&client_call) {
  7939. Server svr;
  7940. setup_handler(svr);
  7941. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7942. auto se = detail::scope_exit([&] {
  7943. svr.stop();
  7944. t.join();
  7945. });
  7946. svr.wait_until_ready();
  7947. Client cli(HOST, PORT);
  7948. vector<uint64_t> progress_values;
  7949. auto res =
  7950. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7951. progress_values.push_back(current);
  7952. return true;
  7953. });
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(200, res->status);
  7956. EXPECT_FALSE(progress_values.empty());
  7957. }
  7958. TEST(UploadProgressTest, PostContentProviderProgress) {
  7959. TestContentProviderUploadProgress(
  7960. [](Server &svr) {
  7961. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7962. res.set_content("provider received", "text/plain");
  7963. });
  7964. },
  7965. [](Client &cli, UploadProgress progress_callback) {
  7966. return cli.Post(
  7967. "/test", 10,
  7968. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7969. sink.os << "test data";
  7970. return true;
  7971. },
  7972. "text/plain", progress_callback);
  7973. });
  7974. }
  7975. // Helper function for multipart upload progress tests
  7976. template <typename SetupHandler, typename ClientCall>
  7977. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7978. ClientCall &&client_call,
  7979. const string &endpoint) {
  7980. Server svr;
  7981. setup_handler(svr);
  7982. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7983. auto se = detail::scope_exit([&] {
  7984. svr.stop();
  7985. t.join();
  7986. });
  7987. svr.wait_until_ready();
  7988. Client cli(HOST, PORT);
  7989. vector<uint64_t> progress_values;
  7990. UploadFormDataItems items = {
  7991. {"field1", "value1", "", ""},
  7992. {"field2", "longer value for progress tracking test", "", ""},
  7993. {"file1", "file content data for upload progress", "test.txt",
  7994. "text/plain"}};
  7995. auto res = client_call(cli, endpoint, items,
  7996. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7997. progress_values.push_back(current);
  7998. return true;
  7999. });
  8000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8001. EXPECT_EQ(200, res->status);
  8002. EXPECT_FALSE(progress_values.empty());
  8003. }
  8004. TEST(UploadProgressTest, PostMultipartProgress) {
  8005. TestMultipartUploadProgress(
  8006. [](Server &svr) {
  8007. svr.Post("/multipart", [](const Request &req, Response &res) {
  8008. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  8009. res.set_content("multipart received", "text/plain");
  8010. });
  8011. },
  8012. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  8013. UploadProgress progress_callback) {
  8014. return cli.Post(endpoint, items, progress_callback);
  8015. },
  8016. "/multipart");
  8017. }
  8018. // Helper function for basic download progress tests
  8019. template <typename SetupHandler, typename ClientCall>
  8020. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8021. ClientCall &&client_call, const string &endpoint,
  8022. size_t expected_content_size) {
  8023. Server svr;
  8024. setup_handler(svr);
  8025. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8026. auto se = detail::scope_exit([&] {
  8027. svr.stop();
  8028. t.join();
  8029. });
  8030. svr.wait_until_ready();
  8031. Client cli(HOST, PORT);
  8032. vector<uint64_t> progress_values;
  8033. auto res = client_call(cli, endpoint,
  8034. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8035. progress_values.push_back(current);
  8036. return true;
  8037. });
  8038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8039. EXPECT_EQ(200, res->status);
  8040. EXPECT_FALSE(progress_values.empty());
  8041. EXPECT_EQ(expected_content_size, res->body.size());
  8042. }
  8043. TEST(DownloadProgressTest, GetBasic) {
  8044. TestBasicDownloadProgress(
  8045. [](Server &svr) {
  8046. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8047. string content(1000, 'D');
  8048. res.set_content(content, "text/plain");
  8049. });
  8050. },
  8051. [](Client &cli, const string &endpoint,
  8052. DownloadProgress progress_callback) {
  8053. return cli.Get(endpoint, progress_callback);
  8054. },
  8055. "/download", 1000u);
  8056. }
  8057. // Helper function for content receiver download progress tests
  8058. template <typename SetupHandler, typename ClientCall>
  8059. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8060. ClientCall &&client_call,
  8061. const string &endpoint,
  8062. size_t expected_content_size) {
  8063. Server svr;
  8064. setup_handler(svr);
  8065. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8066. auto se = detail::scope_exit([&] {
  8067. svr.stop();
  8068. t.join();
  8069. });
  8070. svr.wait_until_ready();
  8071. Client cli(HOST, PORT);
  8072. vector<uint64_t> progress_values;
  8073. string received_body;
  8074. auto res = client_call(
  8075. cli, endpoint,
  8076. [&](const char *data, size_t data_length) -> bool {
  8077. received_body.append(data, data_length);
  8078. return true;
  8079. },
  8080. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8081. progress_values.push_back(current);
  8082. return true;
  8083. });
  8084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8085. EXPECT_EQ(200, res->status);
  8086. EXPECT_FALSE(progress_values.empty());
  8087. EXPECT_EQ(expected_content_size, received_body.size());
  8088. EXPECT_TRUE(res->body.empty());
  8089. }
  8090. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8091. TestContentReceiverDownloadProgress(
  8092. [](Server &svr) {
  8093. svr.Get("/download-receiver",
  8094. [](const Request & /*req*/, Response &res) {
  8095. string content(2000, 'R');
  8096. res.set_content(content, "text/plain");
  8097. });
  8098. },
  8099. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8100. DownloadProgress progress_callback) {
  8101. return cli.Get(endpoint, content_receiver, progress_callback);
  8102. },
  8103. "/download-receiver", 2000u);
  8104. }
  8105. TEST(StreamingTest, NoContentLengthStreaming) {
  8106. Server svr;
  8107. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8108. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8109. if (offset < 6) {
  8110. sink.os << (offset < 3 ? "a" : "b");
  8111. } else {
  8112. sink.done();
  8113. }
  8114. return true;
  8115. });
  8116. });
  8117. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8118. auto listen_se = detail::scope_exit([&] {
  8119. svr.stop();
  8120. listen_thread.join();
  8121. ASSERT_FALSE(svr.is_running());
  8122. });
  8123. svr.wait_until_ready();
  8124. Client client(HOST, PORT);
  8125. auto get_thread = std::thread([&client]() {
  8126. std::string s;
  8127. auto res =
  8128. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8129. s += std::string(data, len);
  8130. return true;
  8131. });
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. EXPECT_EQ("aaabbb", s);
  8135. });
  8136. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8137. // Give GET time to get a few messages.
  8138. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8139. }
  8140. TEST(MountTest, Unmount) {
  8141. Server svr;
  8142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8143. auto se = detail::scope_exit([&] {
  8144. svr.stop();
  8145. listen_thread.join();
  8146. ASSERT_FALSE(svr.is_running());
  8147. });
  8148. svr.wait_until_ready();
  8149. Client cli("localhost", PORT);
  8150. svr.set_mount_point("/mount2", "./www2");
  8151. auto res = cli.Get("/");
  8152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8153. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8154. res = cli.Get("/mount2/dir/test.html");
  8155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8156. EXPECT_EQ(StatusCode::OK_200, res->status);
  8157. svr.set_mount_point("/", "./www");
  8158. res = cli.Get("/dir/");
  8159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8160. EXPECT_EQ(StatusCode::OK_200, res->status);
  8161. svr.remove_mount_point("/");
  8162. res = cli.Get("/dir/");
  8163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8164. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8165. svr.remove_mount_point("/mount2");
  8166. res = cli.Get("/mount2/dir/test.html");
  8167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8168. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8169. }
  8170. TEST(MountTest, PathSegmentBoundary) {
  8171. Server svr;
  8172. svr.set_mount_point("/mount2", "./www2");
  8173. svr.set_mount_point("/", "./www");
  8174. auto port = svr.bind_to_any_port(HOST);
  8175. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8176. auto se = detail::scope_exit([&] {
  8177. svr.stop();
  8178. listen_thread.join();
  8179. ASSERT_FALSE(svr.is_running());
  8180. });
  8181. svr.wait_until_ready();
  8182. Client cli(HOST, port);
  8183. auto res = cli.Get("/mount2/dir/test.html");
  8184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8185. EXPECT_EQ(StatusCode::OK_200, res->status);
  8186. // "/mount2" must not match part-way through a path segment.
  8187. res = cli.Get("/mount2dir/test.html");
  8188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8189. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8190. // A mount point ending in '/' keeps matching every path below it.
  8191. res = cli.Get("/dir/test.html");
  8192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. }
  8195. TEST(MountTest, Redicect) {
  8196. Server svr;
  8197. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8198. auto se = detail::scope_exit([&] {
  8199. svr.stop();
  8200. listen_thread.join();
  8201. ASSERT_FALSE(svr.is_running());
  8202. });
  8203. svr.set_mount_point("/", "./www");
  8204. svr.wait_until_ready();
  8205. Client cli("localhost", PORT);
  8206. auto res = cli.Get("/dir/");
  8207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8208. EXPECT_EQ(StatusCode::OK_200, res->status);
  8209. res = cli.Get("/dir");
  8210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8211. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8212. res = cli.Get("/file");
  8213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8214. EXPECT_EQ(StatusCode::OK_200, res->status);
  8215. res = cli.Get("/file/");
  8216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8217. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8218. cli.set_follow_location(true);
  8219. res = cli.Get("/dir");
  8220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8221. EXPECT_EQ(StatusCode::OK_200, res->status);
  8222. }
  8223. TEST(MountTest, MultibytesPathName) {
  8224. Server svr;
  8225. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8226. auto se = detail::scope_exit([&] {
  8227. svr.stop();
  8228. listen_thread.join();
  8229. ASSERT_FALSE(svr.is_running());
  8230. });
  8231. svr.set_mount_point("/", "./www");
  8232. svr.wait_until_ready();
  8233. Client cli("localhost", PORT);
  8234. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8236. EXPECT_EQ(StatusCode::OK_200, res->status);
  8237. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8238. }
  8239. #ifdef _WIN32
  8240. // Issue #2435: mmap::open() must succeed even when another handle holds
  8241. // the file open for writing (e.g. an active log file).
  8242. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8243. const char *path = "mmap_concurrent_writer_test.txt";
  8244. const char *content = "hello";
  8245. {
  8246. std::ofstream f(path, std::ios::binary);
  8247. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8248. }
  8249. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8250. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8251. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8252. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8253. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8254. detail::mmap m(path);
  8255. ASSERT_TRUE(m.is_open());
  8256. EXPECT_EQ(strlen(content), m.size());
  8257. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8258. }
  8259. #endif
  8260. #ifndef _WIN32
  8261. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8262. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8263. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8264. TEST(MmapTest, FailedMappingIsNotOpen) {
  8265. const char *path = "./mmap_failed_mapping_test_dir";
  8266. ASSERT_EQ(0, ::mkdir(path, 0755));
  8267. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8268. detail::mmap m(path);
  8269. EXPECT_FALSE(m.is_open());
  8270. EXPECT_EQ(0U, m.size());
  8271. EXPECT_NE(static_cast<const void *>(m.data()),
  8272. static_cast<const void *>(MAP_FAILED));
  8273. }
  8274. #endif
  8275. TEST(KeepAliveTest, ReadTimeout) {
  8276. Server svr;
  8277. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8278. std::this_thread::sleep_for(std::chrono::seconds(2));
  8279. res.set_content("a", "text/plain");
  8280. });
  8281. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8282. res.set_content("b", "text/plain");
  8283. });
  8284. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8285. auto se = detail::scope_exit([&] {
  8286. svr.stop();
  8287. listen_thread.join();
  8288. ASSERT_FALSE(svr.is_running());
  8289. });
  8290. svr.wait_until_ready();
  8291. Client cli("localhost", PORT);
  8292. cli.set_keep_alive(true);
  8293. cli.set_read_timeout(std::chrono::seconds(1));
  8294. auto resa = cli.Get("/a");
  8295. ASSERT_FALSE(resa);
  8296. EXPECT_EQ(Error::Read, resa.error());
  8297. auto resb = cli.Get("/b");
  8298. ASSERT_TRUE(resb);
  8299. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8300. EXPECT_EQ("b", resb->body);
  8301. }
  8302. TEST(KeepAliveTest, MaxCount) {
  8303. size_t keep_alive_max_count = 3;
  8304. Server svr;
  8305. svr.set_keep_alive_max_count(keep_alive_max_count);
  8306. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8307. res.set_content("Hello World!", "text/plain");
  8308. });
  8309. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8310. auto se = detail::scope_exit([&] {
  8311. svr.stop();
  8312. listen_thread.join();
  8313. ASSERT_FALSE(svr.is_running());
  8314. });
  8315. svr.wait_until_ready();
  8316. Client cli(HOST, PORT);
  8317. cli.set_keep_alive(true);
  8318. for (size_t i = 0; i < 5; i++) {
  8319. auto result = cli.Get("/hi");
  8320. ASSERT_TRUE(result);
  8321. EXPECT_EQ(StatusCode::OK_200, result->status);
  8322. if (i == keep_alive_max_count - 1) {
  8323. EXPECT_EQ("close", result->get_header_value("Connection"));
  8324. } else {
  8325. EXPECT_FALSE(result->has_header("Connection"));
  8326. }
  8327. }
  8328. }
  8329. TEST(KeepAliveTest, Issue1041) {
  8330. Server svr;
  8331. svr.set_keep_alive_timeout(3);
  8332. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8333. res.set_content("Hello World!", "text/plain");
  8334. });
  8335. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8336. auto se = detail::scope_exit([&] {
  8337. svr.stop();
  8338. listen_thread.join();
  8339. ASSERT_FALSE(svr.is_running());
  8340. });
  8341. svr.wait_until_ready();
  8342. Client cli(HOST, PORT);
  8343. cli.set_keep_alive(true);
  8344. auto result = cli.Get("/hi");
  8345. ASSERT_TRUE(result);
  8346. EXPECT_EQ(StatusCode::OK_200, result->status);
  8347. std::this_thread::sleep_for(std::chrono::seconds(5));
  8348. result = cli.Get("/hi");
  8349. ASSERT_TRUE(result);
  8350. EXPECT_EQ(StatusCode::OK_200, result->status);
  8351. }
  8352. TEST(KeepAliveTest, Issue1959) {
  8353. Server svr;
  8354. svr.set_keep_alive_timeout(5);
  8355. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8356. res.set_content("a", "text/plain");
  8357. });
  8358. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8359. auto se = detail::scope_exit([&] {
  8360. if (!svr.is_running()) return;
  8361. svr.stop();
  8362. listen_thread.join();
  8363. ASSERT_FALSE(svr.is_running());
  8364. });
  8365. svr.wait_until_ready();
  8366. Client cli("localhost", PORT);
  8367. cli.set_keep_alive(true);
  8368. using namespace std::chrono;
  8369. auto start = steady_clock::now();
  8370. cli.Get("/a");
  8371. svr.stop();
  8372. listen_thread.join();
  8373. auto end = steady_clock::now();
  8374. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8375. EXPECT_LT(elapsed, 5000);
  8376. }
  8377. #ifdef CPPHTTPLIB_SSL_ENABLED
  8378. TEST(KeepAliveTest, SSLClientReconnection) {
  8379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8380. ASSERT_TRUE(svr.is_valid());
  8381. svr.set_keep_alive_timeout(1);
  8382. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8383. res.set_content("Hello World!", "text/plain");
  8384. });
  8385. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8386. auto se = detail::scope_exit([&] {
  8387. svr.stop();
  8388. listen_thread.join();
  8389. ASSERT_FALSE(svr.is_running());
  8390. });
  8391. svr.wait_until_ready();
  8392. SSLClient cli(HOST, PORT);
  8393. cli.enable_server_certificate_verification(false);
  8394. cli.set_keep_alive(true);
  8395. auto result = cli.Get("/hi");
  8396. ASSERT_TRUE(result);
  8397. EXPECT_EQ(StatusCode::OK_200, result->status);
  8398. result = cli.Get("/hi");
  8399. ASSERT_TRUE(result);
  8400. EXPECT_EQ(StatusCode::OK_200, result->status);
  8401. std::this_thread::sleep_for(std::chrono::seconds(2));
  8402. // Recoonect
  8403. result = cli.Get("/hi");
  8404. ASSERT_TRUE(result);
  8405. EXPECT_EQ(StatusCode::OK_200, result->status);
  8406. result = cli.Get("/hi");
  8407. ASSERT_TRUE(result);
  8408. EXPECT_EQ(StatusCode::OK_200, result->status);
  8409. }
  8410. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8412. ASSERT_TRUE(svr.is_valid());
  8413. svr.set_keep_alive_timeout(1);
  8414. std::string content = "reconnect";
  8415. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8416. res.set_content("Hello World!", "text/plain");
  8417. });
  8418. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8419. auto se = detail::scope_exit([&] {
  8420. svr.stop();
  8421. listen_thread.join();
  8422. ASSERT_FALSE(svr.is_running());
  8423. });
  8424. svr.wait_until_ready();
  8425. SSLClient cli(HOST, PORT);
  8426. cli.enable_server_certificate_verification(false);
  8427. cli.set_keep_alive(true);
  8428. auto result = cli.Post(
  8429. "/hi", content.size(),
  8430. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8431. sink.write(content.c_str(), content.size());
  8432. return true;
  8433. },
  8434. "text/plain");
  8435. ASSERT_TRUE(result);
  8436. EXPECT_EQ(200, result->status);
  8437. std::this_thread::sleep_for(std::chrono::seconds(2));
  8438. // Recoonect
  8439. result = cli.Post(
  8440. "/hi", content.size(),
  8441. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8442. sink.write(content.c_str(), content.size());
  8443. return true;
  8444. },
  8445. "text/plain");
  8446. ASSERT_TRUE(result);
  8447. EXPECT_EQ(200, result->status);
  8448. result = cli.Post(
  8449. "/hi", content.size(),
  8450. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8451. sink.write(content.c_str(), content.size());
  8452. return true;
  8453. },
  8454. "text/plain");
  8455. ASSERT_TRUE(result);
  8456. EXPECT_EQ(200, result->status);
  8457. }
  8458. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8459. using namespace httplib::tls;
  8460. {
  8461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8462. ASSERT_TRUE(svr.is_valid());
  8463. svr.Get("/sni", [&](const Request &req, Response &res) {
  8464. std::string expected = req.sni();
  8465. EXPECT_EQ(expected, req.get_param_value("expected"));
  8466. res.set_content("ok", "text/plain");
  8467. });
  8468. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8469. auto se = detail::scope_exit([&] {
  8470. svr.stop();
  8471. listen_thread.join();
  8472. ASSERT_FALSE(svr.is_running());
  8473. });
  8474. svr.wait_until_ready();
  8475. {
  8476. SSLClient cli("localhost", PORT);
  8477. cli.enable_server_certificate_verification(false);
  8478. auto res = cli.Get("/sni?expected=localhost");
  8479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8480. }
  8481. {
  8482. SSLClient cli("::1", PORT);
  8483. cli.enable_server_certificate_verification(false);
  8484. auto res = cli.Get("/sni?expected=");
  8485. // NOTE: This may fail if the server is listening on IPv4 only
  8486. // (e.g., when localhost resolves to 127.0.0.1 only)
  8487. if (res) {
  8488. EXPECT_EQ(StatusCode::OK_200, res->status);
  8489. } else {
  8490. EXPECT_EQ(Error::Connection, res.error());
  8491. }
  8492. }
  8493. }
  8494. }
  8495. #endif
  8496. TEST(ClientProblemDetectionTest, ContentProvider) {
  8497. Server svr;
  8498. size_t content_length = 1024 * 1024;
  8499. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8500. res.set_content_provider(
  8501. content_length, "text/plain",
  8502. [&](size_t offset, size_t length, DataSink &sink) {
  8503. auto out_len = std::min(length, static_cast<size_t>(1024));
  8504. std::string out(out_len, '@');
  8505. sink.write(out.data(), out_len);
  8506. return offset < 4096;
  8507. },
  8508. [](bool success) { ASSERT_FALSE(success); });
  8509. });
  8510. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8511. res.set_content_provider(
  8512. 0, "text/plain",
  8513. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8514. EXPECT_TRUE(false);
  8515. return true;
  8516. },
  8517. [](bool success) { ASSERT_FALSE(success); });
  8518. });
  8519. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8520. auto se = detail::scope_exit([&] {
  8521. svr.stop();
  8522. listen_thread.join();
  8523. ASSERT_FALSE(svr.is_running());
  8524. });
  8525. svr.wait_until_ready();
  8526. Client cli("localhost", PORT);
  8527. {
  8528. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8529. size_t /*data_length*/) { return false; });
  8530. ASSERT_FALSE(res);
  8531. }
  8532. {
  8533. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8534. size_t /*data_length*/) { return false; });
  8535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8536. }
  8537. }
  8538. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8539. Server svr;
  8540. svr.set_error_handler([](Request const &, Response &res) -> void {
  8541. res.set_chunked_content_provider(
  8542. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8543. sink.os << "hello";
  8544. sink.os << "world";
  8545. sink.done();
  8546. return true;
  8547. });
  8548. });
  8549. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8550. auto se = detail::scope_exit([&] {
  8551. svr.stop();
  8552. listen_thread.join();
  8553. ASSERT_FALSE(svr.is_running());
  8554. });
  8555. svr.wait_until_ready();
  8556. Client cli("localhost", PORT);
  8557. auto res = cli.Get("/");
  8558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8560. EXPECT_EQ("helloworld", res->body);
  8561. }
  8562. TEST(LongPollingTest, ClientCloseDetection) {
  8563. Server svr;
  8564. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8565. res.set_chunked_content_provider(
  8566. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8567. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8568. sink.os << "hello";
  8569. auto count = 10;
  8570. while (count > 0 && sink.is_writable()) {
  8571. this_thread::sleep_for(chrono::milliseconds(10));
  8572. count--;
  8573. }
  8574. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8575. return true;
  8576. });
  8577. });
  8578. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8579. auto se = detail::scope_exit([&] {
  8580. svr.stop();
  8581. listen_thread.join();
  8582. ASSERT_FALSE(svr.is_running());
  8583. });
  8584. svr.wait_until_ready();
  8585. Client cli("localhost", PORT);
  8586. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8587. EXPECT_EQ("hello", string(data, data_length));
  8588. return false; // close the socket immediately.
  8589. });
  8590. ASSERT_FALSE(res);
  8591. }
  8592. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8593. Server svr;
  8594. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8595. res.set_chunked_content_provider(
  8596. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8597. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8598. sink.os << "hello";
  8599. EXPECT_TRUE(sink.os.good());
  8600. // Wait for the client to close the connection
  8601. auto count = 10;
  8602. while (count > 0 && sink.is_writable()) {
  8603. this_thread::sleep_for(chrono::milliseconds(10));
  8604. count--;
  8605. }
  8606. // After client disconnect, write repeatedly until the socket
  8607. // write actually fails (small writes may be absorbed by the
  8608. // kernel buffer)
  8609. std::string chunk(1024, 'x');
  8610. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8611. sink.os << chunk;
  8612. }
  8613. EXPECT_TRUE(sink.os.fail());
  8614. return true;
  8615. });
  8616. });
  8617. auto port = svr.bind_to_any_port("localhost");
  8618. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8619. auto se = detail::scope_exit([&] {
  8620. svr.stop();
  8621. listen_thread.join();
  8622. ASSERT_FALSE(svr.is_running());
  8623. });
  8624. svr.wait_until_ready();
  8625. Client cli("localhost", port);
  8626. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8627. EXPECT_EQ("hello", string(data, data_length));
  8628. return false; // close the socket immediately.
  8629. });
  8630. ASSERT_FALSE(res);
  8631. }
  8632. TEST(GetWithParametersTest, GetWithParameters) {
  8633. Server svr;
  8634. svr.Get("/", [&](const Request &req, Response &) {
  8635. EXPECT_EQ("world", req.get_param_value("hello"));
  8636. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8637. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8638. });
  8639. svr.Get("/params", [&](const Request &req, Response &) {
  8640. EXPECT_EQ("world", req.get_param_value("hello"));
  8641. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8642. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8643. });
  8644. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8645. EXPECT_EQ("resource-id", req.matches[1]);
  8646. EXPECT_EQ("foo", req.get_param_value("param1"));
  8647. EXPECT_EQ("bar", req.get_param_value("param2"));
  8648. });
  8649. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8650. EXPECT_EQ("user-id", req.path_params.at("id"));
  8651. EXPECT_EQ("foo", req.get_param_value("param1"));
  8652. EXPECT_EQ("bar", req.get_param_value("param2"));
  8653. });
  8654. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8655. auto se = detail::scope_exit([&] {
  8656. svr.stop();
  8657. listen_thread.join();
  8658. ASSERT_FALSE(svr.is_running());
  8659. });
  8660. svr.wait_until_ready();
  8661. {
  8662. Client cli(HOST, PORT);
  8663. Params params;
  8664. params.emplace("hello", "world");
  8665. params.emplace("hello2", "world2");
  8666. params.emplace("hello3", "world3");
  8667. auto res = cli.Get("/", params, Headers{});
  8668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8669. EXPECT_EQ(StatusCode::OK_200, res->status);
  8670. }
  8671. {
  8672. Client cli(HOST, PORT);
  8673. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8675. EXPECT_EQ(StatusCode::OK_200, res->status);
  8676. }
  8677. {
  8678. Client cli(HOST, PORT);
  8679. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8681. EXPECT_EQ(StatusCode::OK_200, res->status);
  8682. }
  8683. {
  8684. Client cli(HOST, PORT);
  8685. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8687. EXPECT_EQ(StatusCode::OK_200, res->status);
  8688. }
  8689. }
  8690. TEST(GetWithParametersTest, GetWithParameters2) {
  8691. Server svr;
  8692. svr.Get("/", [&](const Request &req, Response &res) {
  8693. auto text = req.get_param_value("hello");
  8694. res.set_content(text, "text/plain");
  8695. });
  8696. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8697. auto se = detail::scope_exit([&] {
  8698. svr.stop();
  8699. listen_thread.join();
  8700. ASSERT_FALSE(svr.is_running());
  8701. });
  8702. svr.wait_until_ready();
  8703. Client cli("localhost", PORT);
  8704. Params params;
  8705. params.emplace("hello", "world");
  8706. std::string body;
  8707. auto res = cli.Get("/", params, Headers{},
  8708. [&](const char *data, size_t data_length) {
  8709. body.append(data, data_length);
  8710. return true;
  8711. });
  8712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8713. EXPECT_EQ(StatusCode::OK_200, res->status);
  8714. EXPECT_EQ("world", body);
  8715. }
  8716. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8717. Server svr;
  8718. svr.Get("/search", [&](const Request &req, Response &res) {
  8719. auto q = req.get_param_value("q");
  8720. res.set_content(q, "text/plain");
  8721. });
  8722. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8723. auto se = detail::scope_exit([&] {
  8724. svr.stop();
  8725. listen_thread.join();
  8726. ASSERT_FALSE(svr.is_running());
  8727. });
  8728. svr.wait_until_ready();
  8729. Client cli("localhost", PORT);
  8730. // Verify that Get(path, params) works without requiring Headers argument
  8731. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8733. EXPECT_EQ(StatusCode::OK_200, res->status);
  8734. EXPECT_EQ("cpp-httplib", res->body);
  8735. }
  8736. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8737. auto host = "httpbingo.org";
  8738. auto path = std::string{"/range/32"};
  8739. #ifdef CPPHTTPLIB_SSL_ENABLED
  8740. SSLClient cli(host);
  8741. #else
  8742. Client cli(host);
  8743. #endif
  8744. cli.set_default_headers({make_range_header({{1, 10}})});
  8745. cli.set_connection_timeout(5);
  8746. {
  8747. auto res = cli.Get(path);
  8748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8749. EXPECT_EQ("bcdefghijk", res->body);
  8750. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8751. }
  8752. {
  8753. auto res = cli.Get(path);
  8754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8755. EXPECT_EQ("bcdefghijk", res->body);
  8756. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8757. }
  8758. }
  8759. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8760. Server svr;
  8761. svr.set_default_headers({{"Hello", "World"}});
  8762. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8763. res.set_content("ok", "text/plain");
  8764. });
  8765. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8766. auto se = detail::scope_exit([&] {
  8767. svr.stop();
  8768. listen_thread.join();
  8769. ASSERT_FALSE(svr.is_running());
  8770. });
  8771. svr.wait_until_ready();
  8772. Client cli("localhost", PORT);
  8773. auto res = cli.Get("/");
  8774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8775. EXPECT_EQ(StatusCode::OK_200, res->status);
  8776. EXPECT_EQ("ok", res->body);
  8777. EXPECT_EQ("World", res->get_header_value("Hello"));
  8778. }
  8779. #ifdef CPPHTTPLIB_SSL_ENABLED
  8780. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8782. ASSERT_TRUE(svr.is_valid());
  8783. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8784. std::this_thread::sleep_for(std::chrono::seconds(2));
  8785. res.set_content("a", "text/plain");
  8786. });
  8787. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8788. res.set_content("b", "text/plain");
  8789. });
  8790. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8791. auto se = detail::scope_exit([&] {
  8792. svr.stop();
  8793. listen_thread.join();
  8794. ASSERT_FALSE(svr.is_running());
  8795. });
  8796. svr.wait_until_ready();
  8797. SSLClient cli("localhost", PORT);
  8798. cli.enable_server_certificate_verification(false);
  8799. cli.set_keep_alive(true);
  8800. cli.set_read_timeout(std::chrono::seconds(1));
  8801. auto resa = cli.Get("/a");
  8802. ASSERT_TRUE(!resa);
  8803. EXPECT_EQ(Error::Read, resa.error());
  8804. auto resb = cli.Get("/b");
  8805. ASSERT_TRUE(resb);
  8806. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8807. EXPECT_EQ("b", resb->body);
  8808. }
  8809. #endif
  8810. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8811. protected:
  8812. ServerTestWithAI_PASSIVE()
  8813. : cli_(HOST, PORT)
  8814. #ifdef CPPHTTPLIB_SSL_ENABLED
  8815. ,
  8816. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8817. #endif
  8818. {
  8819. #ifdef CPPHTTPLIB_SSL_ENABLED
  8820. cli_.enable_server_certificate_verification(false);
  8821. #endif
  8822. }
  8823. virtual void SetUp() {
  8824. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8825. res.set_content("Hello World!", "text/plain");
  8826. });
  8827. t_ = thread(
  8828. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8829. svr_.wait_until_ready();
  8830. }
  8831. virtual void TearDown() {
  8832. svr_.stop();
  8833. t_.join();
  8834. }
  8835. #ifdef CPPHTTPLIB_SSL_ENABLED
  8836. SSLClient cli_;
  8837. SSLServer svr_;
  8838. #else
  8839. Client cli_;
  8840. Server svr_;
  8841. #endif
  8842. thread t_;
  8843. };
  8844. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8845. auto res = cli_.Get("/hi");
  8846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8847. EXPECT_EQ(StatusCode::OK_200, res->status);
  8848. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8849. EXPECT_EQ("Hello World!", res->body);
  8850. }
  8851. class ServerUpDownTest : public ::testing::Test {
  8852. protected:
  8853. ServerUpDownTest() : cli_(HOST, PORT) {}
  8854. virtual void SetUp() {
  8855. t_ = thread([&]() {
  8856. svr_.bind_to_any_port(HOST);
  8857. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8858. ASSERT_TRUE(svr_.listen_after_bind());
  8859. });
  8860. svr_.wait_until_ready();
  8861. }
  8862. virtual void TearDown() {
  8863. svr_.stop();
  8864. t_.join();
  8865. }
  8866. Client cli_;
  8867. Server svr_;
  8868. thread t_;
  8869. };
  8870. TEST_F(ServerUpDownTest, QuickStartStop) {
  8871. // Should not crash, especially when run with
  8872. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8873. }
  8874. class PayloadMaxLengthTest : public ::testing::Test {
  8875. protected:
  8876. PayloadMaxLengthTest()
  8877. : cli_(HOST, PORT)
  8878. #ifdef CPPHTTPLIB_SSL_ENABLED
  8879. ,
  8880. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8881. #endif
  8882. {
  8883. #ifdef CPPHTTPLIB_SSL_ENABLED
  8884. cli_.enable_server_certificate_verification(false);
  8885. #endif
  8886. }
  8887. virtual void SetUp() {
  8888. svr_.set_payload_max_length(8);
  8889. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8890. res.set_content("test", "text/plain");
  8891. });
  8892. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8893. svr_.wait_until_ready();
  8894. }
  8895. virtual void TearDown() {
  8896. svr_.stop();
  8897. t_.join();
  8898. }
  8899. #ifdef CPPHTTPLIB_SSL_ENABLED
  8900. SSLClient cli_;
  8901. SSLServer svr_;
  8902. #else
  8903. Client cli_;
  8904. Server svr_;
  8905. #endif
  8906. thread t_;
  8907. };
  8908. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8909. auto res = cli_.Post("/test", "123456789", "text/plain");
  8910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8911. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8912. res = cli_.Post("/test", "12345678", "text/plain");
  8913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8914. EXPECT_EQ(StatusCode::OK_200, res->status);
  8915. }
  8916. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8917. // Test chunked encoding with payload exceeding the 8-byte limit
  8918. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8919. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8921. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8922. }
  8923. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8924. // Test chunked encoding with payload within the 8-byte limit
  8925. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8926. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8928. EXPECT_EQ(StatusCode::OK_200, res->status);
  8929. }
  8930. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8931. // Test using send_request to send chunked data exceeding payload limit
  8932. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8933. "Host: " +
  8934. std::string(HOST) + ":" + std::to_string(PORT) +
  8935. "\r\n"
  8936. "Transfer-Encoding: chunked\r\n"
  8937. "Connection: close\r\n"
  8938. "\r\n"
  8939. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8940. "0123456789\r\n"
  8941. "0\r\n" // End chunk
  8942. "\r\n";
  8943. std::string response;
  8944. bool result = send_request(1, chunked_request, &response);
  8945. if (!result) {
  8946. // If send_request fails, it might be because the server closed the
  8947. // connection due to payload limit enforcement, which is acceptable
  8948. SUCCEED()
  8949. << "Server rejected oversized chunked request (connection closed)";
  8950. } else {
  8951. // If we got a response, check if it's an error response or connection was
  8952. // closed early Short response length indicates connection was closed due to
  8953. // payload limit
  8954. if (response.length() <= 10) {
  8955. SUCCEED() << "Server closed connection for oversized chunked request";
  8956. } else {
  8957. // Check for error status codes
  8958. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8959. response.find("Payload Too Large") != std::string::npos ||
  8960. response.find("400") != std::string::npos);
  8961. }
  8962. }
  8963. }
  8964. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8965. // Test request without Content-Length header exceeding payload limit
  8966. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8967. "Host: " +
  8968. std::string(HOST) + ":" +
  8969. std::to_string(PORT) +
  8970. "\r\n"
  8971. "Connection: close\r\n"
  8972. "\r\n";
  8973. // Add payload exceeding the 8-byte limit
  8974. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8975. request_without_content_length += large_payload;
  8976. std::string response;
  8977. bool result = send_request(1, request_without_content_length, &response);
  8978. if (!result) {
  8979. // If send_request fails, server likely closed connection due to payload
  8980. // limit
  8981. SUCCEED() << "Server rejected oversized request without Content-Length "
  8982. "(connection closed)";
  8983. } else {
  8984. // Check if server responded with error or closed connection early
  8985. if (response.length() <= 10) {
  8986. SUCCEED() << "Server closed connection for oversized request without "
  8987. "Content-Length";
  8988. } else {
  8989. // Check for error status codes
  8990. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8991. response.find("Payload Too Large") != std::string::npos ||
  8992. response.find("400") != std::string::npos);
  8993. }
  8994. }
  8995. }
  8996. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8997. // Test request without Content-Length header within payload limit
  8998. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8999. "Host: " +
  9000. std::string(HOST) + ":" +
  9001. std::to_string(PORT) +
  9002. "\r\n"
  9003. "Connection: close\r\n"
  9004. "\r\n";
  9005. // Add payload within the 8-byte limit
  9006. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  9007. request_without_content_length += small_payload;
  9008. std::string response;
  9009. bool result = send_request(1, request_without_content_length, &response);
  9010. // For requests without Content-Length, the server may have different behavior
  9011. // The key is that it should not reject due to payload limit for small
  9012. // payloads
  9013. if (result) {
  9014. // Check for any HTTP response (success or error, but not connection closed)
  9015. if (response.length() > 10) {
  9016. SUCCEED()
  9017. << "Server processed request without Content-Length within limit";
  9018. } else {
  9019. // Short response might indicate connection closed, which is acceptable
  9020. SUCCEED() << "Server closed connection for request without "
  9021. "Content-Length (acceptable behavior)";
  9022. }
  9023. } else {
  9024. // Connection failure might be due to protocol requirements
  9025. SUCCEED() << "Connection issue with request without Content-Length "
  9026. "(environment-specific)";
  9027. }
  9028. }
  9029. class LargePayloadMaxLengthTest : public ::testing::Test {
  9030. protected:
  9031. LargePayloadMaxLengthTest()
  9032. : cli_(HOST, PORT)
  9033. #ifdef CPPHTTPLIB_SSL_ENABLED
  9034. ,
  9035. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9036. #endif
  9037. {
  9038. #ifdef CPPHTTPLIB_SSL_ENABLED
  9039. cli_.enable_server_certificate_verification(false);
  9040. #endif
  9041. }
  9042. virtual void SetUp() {
  9043. // Set 10MB payload limit
  9044. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9045. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9046. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9047. res.set_content("Large payload test", "text/plain");
  9048. });
  9049. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9050. svr_.wait_until_ready();
  9051. }
  9052. virtual void TearDown() {
  9053. svr_.stop();
  9054. t_.join();
  9055. }
  9056. #ifdef CPPHTTPLIB_SSL_ENABLED
  9057. SSLClient cli_;
  9058. SSLServer svr_;
  9059. #else
  9060. Client cli_;
  9061. Server svr_;
  9062. #endif
  9063. thread t_;
  9064. };
  9065. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9066. // Test chunked encoding with payload within 10MB limit
  9067. std::string medium_payload(5 * 1024 * 1024,
  9068. 'A'); // 5MB payload, within 10MB limit
  9069. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9071. EXPECT_EQ(StatusCode::OK_200, res->status);
  9072. }
  9073. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9074. // Test chunked encoding with payload exceeding 10MB limit
  9075. std::string large_payload(12 * 1024 * 1024,
  9076. 'B'); // 12MB payload, exceeds 10MB limit
  9077. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9078. // Server may either return 413 or close the connection
  9079. if (res) {
  9080. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9081. } else {
  9082. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9083. }
  9084. }
  9085. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9086. // Test request without Content-Length header within 10MB limit
  9087. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9088. "Host: " +
  9089. std::string(HOST) + ":" +
  9090. std::to_string(PORT) +
  9091. "\r\n"
  9092. "Connection: close\r\n"
  9093. "\r\n";
  9094. // Add 1MB payload (within 10MB limit)
  9095. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9096. request_without_content_length += medium_payload;
  9097. std::string response;
  9098. bool result = send_request(5, request_without_content_length, &response);
  9099. if (result) {
  9100. // Should get a proper HTTP response for payloads within limit
  9101. if (response.length() > 10) {
  9102. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9103. "10MB limit";
  9104. } else {
  9105. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9106. "Content-Length)";
  9107. }
  9108. } else {
  9109. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9110. }
  9111. }
  9112. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9113. // Test request without Content-Length header exceeding 10MB limit
  9114. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9115. "Host: " +
  9116. std::string(HOST) + ":" +
  9117. std::to_string(PORT) +
  9118. "\r\n"
  9119. "Connection: close\r\n"
  9120. "\r\n";
  9121. // Add 12MB payload (exceeds 10MB limit)
  9122. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9123. request_without_content_length += large_payload;
  9124. std::string response;
  9125. bool result = send_request(10, request_without_content_length, &response);
  9126. if (!result) {
  9127. // Server should close connection due to payload limit
  9128. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9129. "(connection closed)";
  9130. } else {
  9131. // Check for error response
  9132. if (response.length() <= 10) {
  9133. SUCCEED()
  9134. << "Server closed connection for 12MB request exceeding 10MB limit";
  9135. } else {
  9136. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9137. response.find("Payload Too Large") != std::string::npos ||
  9138. response.find("400") != std::string::npos);
  9139. }
  9140. }
  9141. }
  9142. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9143. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9144. // path.
  9145. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9146. Server svr;
  9147. const size_t LIMIT = 64 * 1024; // 64KB
  9148. svr.set_payload_max_length(LIMIT);
  9149. size_t total = 0;
  9150. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9151. const ContentReader &content_reader) {
  9152. content_reader([&](const char * /*data*/, size_t len) {
  9153. total += len;
  9154. return true;
  9155. });
  9156. res.status = 200;
  9157. res.set_content("stream_ok", "text/plain");
  9158. });
  9159. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9160. auto se = detail::scope_exit([&] {
  9161. svr.stop();
  9162. thread.join();
  9163. ASSERT_FALSE(svr.is_running());
  9164. });
  9165. svr.wait_until_ready();
  9166. // Prepare 256KB raw data and gzip-compress it
  9167. std::string raw(256 * 1024, 'A');
  9168. std::string gz;
  9169. {
  9170. z_stream zs{};
  9171. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9172. Z_DEFAULT_STRATEGY);
  9173. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9174. zs.avail_in = static_cast<uInt>(raw.size());
  9175. char outbuf[4096];
  9176. int ret;
  9177. do {
  9178. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9179. zs.avail_out = sizeof(outbuf);
  9180. ret = deflate(&zs, Z_FINISH);
  9181. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9182. } while (ret != Z_STREAM_END);
  9183. deflateEnd(&zs);
  9184. }
  9185. Client cli(HOST, PORT);
  9186. cli.set_connection_timeout(std::chrono::seconds(5));
  9187. Headers headers = {{"Content-Encoding", "gzip"}};
  9188. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9189. "application/octet-stream");
  9190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9191. // Server must reject oversized decompressed payloads with 413.
  9192. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9193. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9194. EXPECT_LE(total, LIMIT);
  9195. }
  9196. #ifndef CPPHTTPLIB_SSL_ENABLED
  9197. // For a request with neither Content-Length nor Transfer-Encoding, the
  9198. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9199. // compressed wire bytes straight to the ContentReader without ever routing
  9200. // them through the decompressor, so payload_max_length_ only bounded the
  9201. // compressed size on the wire, not the decompressed size.
  9202. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9203. Server svr;
  9204. const size_t LIMIT = 64 * 1024; // 64KB
  9205. svr.set_payload_max_length(LIMIT);
  9206. size_t total = 0;
  9207. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9208. const ContentReader &content_reader) {
  9209. content_reader([&](const char * /*data*/, size_t len) {
  9210. total += len;
  9211. return true;
  9212. });
  9213. res.status = 200;
  9214. res.set_content("stream_ok", "text/plain");
  9215. });
  9216. auto port = svr.bind_to_any_port(HOST);
  9217. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9218. auto se = detail::scope_exit([&] {
  9219. svr.stop();
  9220. thread.join();
  9221. ASSERT_FALSE(svr.is_running());
  9222. });
  9223. svr.wait_until_ready();
  9224. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9225. // StreamingGzipDecompression test above.
  9226. std::string raw(256 * 1024, 'A');
  9227. std::string gz;
  9228. {
  9229. httplib::detail::gzip_compressor compressor;
  9230. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9231. [&](const char *chunk, size_t len) {
  9232. gz.append(chunk, len);
  9233. return true;
  9234. });
  9235. ASSERT_TRUE(result);
  9236. }
  9237. // Send the gzip body over raw TCP with neither Content-Length nor
  9238. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  9239. // kicks in.
  9240. std::string req = "POST /stream HTTP/1.1\r\n"
  9241. "Host: " +
  9242. std::string(HOST) + ":" + std::to_string(port) +
  9243. "\r\n"
  9244. "Content-Encoding: gzip\r\n"
  9245. "Connection: close\r\n"
  9246. "\r\n" +
  9247. gz;
  9248. std::string response;
  9249. ASSERT_TRUE(send_request(5, req, &response, port));
  9250. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9251. EXPECT_LE(total, LIMIT);
  9252. }
  9253. #endif
  9254. #endif
  9255. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9256. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9257. // the payload must be passed through untouched instead of being rejected.
  9258. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9259. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9260. Server svr;
  9261. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9262. res.set_content(body, "image/jpeg");
  9263. res.set_header("Content-Encoding", "UTF-8");
  9264. });
  9265. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9266. res.set_content(body, "image/jpeg");
  9267. res.set_header("Content-Encoding", "identity");
  9268. });
  9269. svr.Post("/echo", [](const Request &req, Response &res) {
  9270. res.set_content(req.body, "image/jpeg");
  9271. });
  9272. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9273. auto se = detail::scope_exit([&] {
  9274. svr.stop();
  9275. t.join();
  9276. ASSERT_FALSE(svr.is_running());
  9277. });
  9278. svr.wait_until_ready();
  9279. Client cli(HOST, PORT);
  9280. {
  9281. auto res = cli.Get("/image");
  9282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9283. EXPECT_EQ(StatusCode::OK_200, res->status);
  9284. EXPECT_EQ(body, res->body);
  9285. }
  9286. {
  9287. auto res = cli.Get("/identity");
  9288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9289. EXPECT_EQ(StatusCode::OK_200, res->status);
  9290. EXPECT_EQ(body, res->body);
  9291. }
  9292. {
  9293. // The same applies to a request body reaching the server.
  9294. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9295. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9297. EXPECT_EQ(StatusCode::OK_200, res->status);
  9298. EXPECT_EQ(body, res->body);
  9299. }
  9300. }
  9301. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9302. // gzip-encoded response even when the build has no zlib support.
  9303. static const char GZIPPED_HELLO_WORLD[] = {
  9304. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9305. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9306. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9307. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9308. // A content coding cpp-httplib recognizes but was not built with must be
  9309. // reported as such. Handing the still-compressed payload back to the caller
  9310. // would silently corrupt it.
  9311. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9312. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9313. Server svr;
  9314. // "image/jpeg" keeps the server from applying a content coding of its own,
  9315. // so the hand-crafted Content-Encoding below survives.
  9316. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9317. res.set_content(gzipped, "image/jpeg");
  9318. res.set_header("Content-Encoding", "gzip");
  9319. });
  9320. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9321. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9322. res.set_content(gzipped, "image/jpeg");
  9323. res.set_header("Content-Encoding", "GZIP");
  9324. });
  9325. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9326. auto se = detail::scope_exit([&] {
  9327. svr.stop();
  9328. t.join();
  9329. ASSERT_FALSE(svr.is_running());
  9330. });
  9331. svr.wait_until_ready();
  9332. Client cli(HOST, PORT);
  9333. {
  9334. auto res = cli.Get("/gzipped");
  9335. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9337. EXPECT_EQ("Hello World!", res->body);
  9338. #else
  9339. ASSERT_FALSE(res);
  9340. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9341. #endif
  9342. }
  9343. {
  9344. // open_stream() must behave the same way.
  9345. auto handle = cli.open_stream("GET", "/gzipped");
  9346. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9347. ASSERT_TRUE(handle.is_valid());
  9348. std::string received;
  9349. char buf[256];
  9350. ssize_t n;
  9351. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9352. received.append(buf, static_cast<size_t>(n));
  9353. }
  9354. EXPECT_EQ("Hello World!", received);
  9355. #else
  9356. EXPECT_FALSE(handle.is_valid());
  9357. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9358. #endif
  9359. }
  9360. {
  9361. // A differently-cased coding must not be mistaken for an unknown one, or
  9362. // the body would be handed back still compressed.
  9363. auto res = cli.Get("/gzipped-uppercase");
  9364. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9366. EXPECT_EQ("Hello World!", res->body);
  9367. #else
  9368. ASSERT_FALSE(res);
  9369. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9370. #endif
  9371. }
  9372. }
  9373. // Regression test for DoS vulnerability: a malicious server sending a response
  9374. // without Content-Length header must not cause unbounded memory consumption on
  9375. // the client side. The client should stop reading after a reasonable limit,
  9376. // similar to the server-side set_payload_max_length protection.
  9377. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9378. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9379. #ifndef _WIN32
  9380. signal(SIGPIPE, SIG_IGN);
  9381. #endif
  9382. auto server_thread = std::thread([] {
  9383. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9384. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9385. default_socket_options(srv);
  9386. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9387. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9388. sockaddr_in addr{};
  9389. addr.sin_family = AF_INET;
  9390. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9391. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9392. int opt = 1;
  9393. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9394. #ifdef _WIN32
  9395. reinterpret_cast<const char *>(&opt),
  9396. #else
  9397. &opt,
  9398. #endif
  9399. sizeof(opt));
  9400. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9401. ::listen(srv, 1);
  9402. sockaddr_in cli_addr{};
  9403. socklen_t cli_len = sizeof(cli_addr);
  9404. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9405. if (cli != INVALID_SOCKET) {
  9406. char buf[4096];
  9407. ::recv(cli, buf, sizeof(buf), 0);
  9408. // Malicious response: no Content-Length, no chunked encoding
  9409. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9410. "Connection: close\r\n"
  9411. "\r\n";
  9412. ::send(cli,
  9413. #ifdef _WIN32
  9414. static_cast<const char *>(response_header.c_str()),
  9415. static_cast<int>(response_header.size()),
  9416. #else
  9417. response_header.c_str(), response_header.size(),
  9418. #endif
  9419. 0);
  9420. // Send 10MB of data
  9421. std::string chunk(64 * 1024, 'A');
  9422. size_t total_sent = 0;
  9423. while (total_sent < MALICIOUS_DATA_SIZE) {
  9424. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9425. auto sent = ::send(cli,
  9426. #ifdef _WIN32
  9427. static_cast<const char *>(chunk.c_str()),
  9428. static_cast<int>(to_send),
  9429. #else
  9430. chunk.c_str(), to_send,
  9431. #endif
  9432. 0);
  9433. if (sent <= 0) break;
  9434. total_sent += static_cast<size_t>(sent);
  9435. }
  9436. detail::close_socket(cli);
  9437. }
  9438. detail::close_socket(srv);
  9439. });
  9440. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9441. size_t total_read = 0;
  9442. {
  9443. Client cli("127.0.0.1", PORT + 2);
  9444. cli.set_read_timeout(5, 0);
  9445. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9446. auto stream = cli.open_stream("GET", "/malicious");
  9447. ASSERT_TRUE(stream.is_valid());
  9448. char buffer[64 * 1024];
  9449. ssize_t n;
  9450. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9451. total_read += static_cast<size_t>(n);
  9452. }
  9453. } // StreamHandle and Client destroyed here, closing the socket
  9454. server_thread.join();
  9455. // With set_payload_max_length, the client must stop reading before consuming
  9456. // all 10MB. The read loop should be cut off at or near the configured limit.
  9457. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9458. << "Client read " << total_read << " bytes, exceeding the configured "
  9459. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9460. }
  9461. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9462. // the entire response body without truncation.
  9463. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9464. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9465. #ifndef _WIN32
  9466. signal(SIGPIPE, SIG_IGN);
  9467. #endif
  9468. auto server_thread = std::thread([] {
  9469. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9470. default_socket_options(srv);
  9471. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9472. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9473. sockaddr_in addr{};
  9474. addr.sin_family = AF_INET;
  9475. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9476. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9477. int opt = 1;
  9478. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9479. #ifdef _WIN32
  9480. reinterpret_cast<const char *>(&opt),
  9481. #else
  9482. &opt,
  9483. #endif
  9484. sizeof(opt));
  9485. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9486. ::listen(srv, 1);
  9487. sockaddr_in cli_addr{};
  9488. socklen_t cli_len = sizeof(cli_addr);
  9489. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9490. if (cli != INVALID_SOCKET) {
  9491. char buf[4096];
  9492. ::recv(cli, buf, sizeof(buf), 0);
  9493. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9494. "Connection: close\r\n"
  9495. "\r\n";
  9496. ::send(cli,
  9497. #ifdef _WIN32
  9498. static_cast<const char *>(response_header.c_str()),
  9499. static_cast<int>(response_header.size()),
  9500. #else
  9501. response_header.c_str(), response_header.size(),
  9502. #endif
  9503. 0);
  9504. std::string chunk(64 * 1024, 'A');
  9505. size_t total_sent = 0;
  9506. while (total_sent < DATA_SIZE) {
  9507. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9508. auto sent = ::send(cli,
  9509. #ifdef _WIN32
  9510. static_cast<const char *>(chunk.c_str()),
  9511. static_cast<int>(to_send),
  9512. #else
  9513. chunk.c_str(), to_send,
  9514. #endif
  9515. 0);
  9516. if (sent <= 0) break;
  9517. total_sent += static_cast<size_t>(sent);
  9518. }
  9519. #ifdef _WIN32
  9520. ::shutdown(cli, SD_SEND);
  9521. #else
  9522. ::shutdown(cli, SHUT_WR);
  9523. #endif
  9524. // Drain until the client closes its end, ensuring all data is delivered
  9525. char drain[1024];
  9526. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9527. detail::close_socket(cli);
  9528. }
  9529. detail::close_socket(srv);
  9530. });
  9531. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9532. size_t total_read = 0;
  9533. {
  9534. Client cli("127.0.0.1", PORT + 2);
  9535. cli.set_read_timeout(5, 0);
  9536. cli.set_payload_max_length(0); // 0 means no limit
  9537. auto stream = cli.open_stream("GET", "/data");
  9538. ASSERT_TRUE(stream.is_valid());
  9539. char buffer[64 * 1024];
  9540. ssize_t n;
  9541. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9542. total_read += static_cast<size_t>(n);
  9543. }
  9544. }
  9545. server_thread.join();
  9546. EXPECT_EQ(total_read, DATA_SIZE)
  9547. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9548. << " bytes without truncation, but only read " << total_read << " bytes.";
  9549. }
  9550. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9551. // enormous Content-Length must not cause the client to pre-allocate a huge
  9552. // response body buffer. The reservation is capped at payload_max_length_, and
  9553. // the read itself fails when the body exceeds the limit.
  9554. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9555. #ifndef _WIN32
  9556. signal(SIGPIPE, SIG_IGN);
  9557. #endif
  9558. auto server_thread = std::thread([] {
  9559. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9560. default_socket_options(srv);
  9561. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9562. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9563. sockaddr_in addr{};
  9564. addr.sin_family = AF_INET;
  9565. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9566. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9567. int opt = 1;
  9568. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9569. #ifdef _WIN32
  9570. reinterpret_cast<const char *>(&opt),
  9571. #else
  9572. &opt,
  9573. #endif
  9574. sizeof(opt));
  9575. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9576. ::listen(srv, 1);
  9577. sockaddr_in cli_addr{};
  9578. socklen_t cli_len = sizeof(cli_addr);
  9579. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9580. if (cli != INVALID_SOCKET) {
  9581. char buf[4096];
  9582. ::recv(cli, buf, sizeof(buf), 0);
  9583. // Malicious response: claim a 20GB body but send only a tiny payload.
  9584. std::string response = "HTTP/1.1 200 OK\r\n"
  9585. "Content-Length: 20000000000\r\n"
  9586. "\r\n"
  9587. "abc";
  9588. ::send(cli,
  9589. #ifdef _WIN32
  9590. static_cast<const char *>(response.c_str()),
  9591. static_cast<int>(response.size()),
  9592. #else
  9593. response.c_str(), response.size(),
  9594. #endif
  9595. 0);
  9596. detail::close_socket(cli);
  9597. }
  9598. detail::close_socket(srv);
  9599. });
  9600. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9601. {
  9602. Client cli("127.0.0.1", PORT + 2);
  9603. cli.set_read_timeout(5, 0);
  9604. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9605. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9606. // (server claims more bytes than payload_max_length permits), but it must
  9607. // not exhaust memory before getting there.
  9608. auto res = cli.Get("/malicious");
  9609. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9610. }
  9611. server_thread.join();
  9612. }
  9613. // Verify that content_receiver bypasses the default payload_max_length,
  9614. // allowing streaming downloads larger than 100MB without requiring an explicit
  9615. // set_payload_max_length call.
  9616. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9617. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9618. #ifndef _WIN32
  9619. signal(SIGPIPE, SIG_IGN);
  9620. #endif
  9621. auto server_thread = std::thread([] {
  9622. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9623. default_socket_options(srv);
  9624. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9625. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9626. sockaddr_in addr{};
  9627. addr.sin_family = AF_INET;
  9628. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9629. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9630. int opt = 1;
  9631. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9632. #ifdef _WIN32
  9633. reinterpret_cast<const char *>(&opt),
  9634. #else
  9635. &opt,
  9636. #endif
  9637. sizeof(opt));
  9638. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9639. ::listen(srv, 1);
  9640. sockaddr_in cli_addr{};
  9641. socklen_t cli_len = sizeof(cli_addr);
  9642. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9643. if (cli != INVALID_SOCKET) {
  9644. char buf[4096];
  9645. ::recv(cli, buf, sizeof(buf), 0);
  9646. // Response with Content-Length larger than default 100MB limit
  9647. auto content_length = std::to_string(DATA_SIZE);
  9648. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9649. "Content-Length: " +
  9650. content_length +
  9651. "\r\n"
  9652. "Connection: close\r\n"
  9653. "\r\n";
  9654. ::send(cli,
  9655. #ifdef _WIN32
  9656. static_cast<const char *>(response_header.c_str()),
  9657. static_cast<int>(response_header.size()),
  9658. #else
  9659. response_header.c_str(), response_header.size(),
  9660. #endif
  9661. 0);
  9662. std::string chunk(64 * 1024, 'A');
  9663. size_t total_sent = 0;
  9664. while (total_sent < DATA_SIZE) {
  9665. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9666. auto sent = ::send(cli,
  9667. #ifdef _WIN32
  9668. static_cast<const char *>(chunk.c_str()),
  9669. static_cast<int>(to_send),
  9670. #else
  9671. chunk.c_str(), to_send,
  9672. #endif
  9673. 0);
  9674. if (sent <= 0) break;
  9675. total_sent += static_cast<size_t>(sent);
  9676. }
  9677. detail::close_socket(cli);
  9678. }
  9679. detail::close_socket(srv);
  9680. });
  9681. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9682. size_t total_received = 0;
  9683. {
  9684. Client cli("127.0.0.1", PORT + 2);
  9685. cli.set_read_timeout(10, 0);
  9686. // Do NOT call set_payload_max_length — use the default 100MB limit
  9687. auto res =
  9688. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9689. total_received += data_length;
  9690. return true;
  9691. });
  9692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9693. EXPECT_EQ(StatusCode::OK_200, res->status);
  9694. }
  9695. server_thread.join();
  9696. EXPECT_EQ(total_received, DATA_SIZE)
  9697. << "With content_receiver, the client should read all " << DATA_SIZE
  9698. << " bytes despite the default 100MB payload_max_length, but only read "
  9699. << total_received << " bytes.";
  9700. }
  9701. // Verify that an explicit set_payload_max_length smaller than the response is
  9702. // enforced even when a content_receiver is used.
  9703. TEST(ClientVulnerabilityTest,
  9704. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9705. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9706. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  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. auto content_length = std::to_string(DATA_SIZE);
  9736. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9737. "Content-Length: " +
  9738. content_length +
  9739. "\r\n"
  9740. "Connection: close\r\n"
  9741. "\r\n";
  9742. ::send(cli,
  9743. #ifdef _WIN32
  9744. static_cast<const char *>(response_header.c_str()),
  9745. static_cast<int>(response_header.size()),
  9746. #else
  9747. response_header.c_str(), response_header.size(),
  9748. #endif
  9749. 0);
  9750. std::string chunk(64 * 1024, 'A');
  9751. size_t total_sent = 0;
  9752. while (total_sent < DATA_SIZE) {
  9753. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9754. auto sent = ::send(cli,
  9755. #ifdef _WIN32
  9756. static_cast<const char *>(chunk.c_str()),
  9757. static_cast<int>(to_send),
  9758. #else
  9759. chunk.c_str(), to_send,
  9760. #endif
  9761. 0);
  9762. if (sent <= 0) break;
  9763. total_sent += static_cast<size_t>(sent);
  9764. }
  9765. detail::close_socket(cli);
  9766. }
  9767. detail::close_socket(srv);
  9768. });
  9769. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9770. size_t total_received = 0;
  9771. {
  9772. Client cli("127.0.0.1", PORT + 2);
  9773. cli.set_read_timeout(10, 0);
  9774. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9775. auto res =
  9776. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9777. total_received += data_length;
  9778. return true;
  9779. });
  9780. // Should fail because 200MB exceeds the explicit 150MB limit
  9781. EXPECT_FALSE(res);
  9782. }
  9783. server_thread.join();
  9784. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9785. << "Client with content_receiver should respect the explicit "
  9786. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9787. << total_received << " bytes.";
  9788. }
  9789. // Verify that an explicit set_payload_max_length larger than the response
  9790. // allows the content_receiver to read all data successfully.
  9791. TEST(ClientVulnerabilityTest,
  9792. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9793. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9794. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9795. #ifndef _WIN32
  9796. signal(SIGPIPE, SIG_IGN);
  9797. #endif
  9798. auto server_thread = std::thread([] {
  9799. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9800. default_socket_options(srv);
  9801. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9802. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9803. sockaddr_in addr{};
  9804. addr.sin_family = AF_INET;
  9805. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9806. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9807. int opt = 1;
  9808. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9809. #ifdef _WIN32
  9810. reinterpret_cast<const char *>(&opt),
  9811. #else
  9812. &opt,
  9813. #endif
  9814. sizeof(opt));
  9815. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9816. ::listen(srv, 1);
  9817. sockaddr_in cli_addr{};
  9818. socklen_t cli_len = sizeof(cli_addr);
  9819. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9820. if (cli != INVALID_SOCKET) {
  9821. char buf[4096];
  9822. ::recv(cli, buf, sizeof(buf), 0);
  9823. auto content_length = std::to_string(DATA_SIZE);
  9824. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9825. "Content-Length: " +
  9826. content_length +
  9827. "\r\n"
  9828. "Connection: close\r\n"
  9829. "\r\n";
  9830. ::send(cli,
  9831. #ifdef _WIN32
  9832. static_cast<const char *>(response_header.c_str()),
  9833. static_cast<int>(response_header.size()),
  9834. #else
  9835. response_header.c_str(), response_header.size(),
  9836. #endif
  9837. 0);
  9838. std::string chunk(64 * 1024, 'A');
  9839. size_t total_sent = 0;
  9840. while (total_sent < DATA_SIZE) {
  9841. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9842. auto sent = ::send(cli,
  9843. #ifdef _WIN32
  9844. static_cast<const char *>(chunk.c_str()),
  9845. static_cast<int>(to_send),
  9846. #else
  9847. chunk.c_str(), to_send,
  9848. #endif
  9849. 0);
  9850. if (sent <= 0) break;
  9851. total_sent += static_cast<size_t>(sent);
  9852. }
  9853. #ifdef _WIN32
  9854. ::shutdown(cli, SD_SEND);
  9855. #else
  9856. ::shutdown(cli, SHUT_WR);
  9857. #endif
  9858. char drain[1024];
  9859. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9860. detail::close_socket(cli);
  9861. }
  9862. detail::close_socket(srv);
  9863. });
  9864. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9865. size_t total_received = 0;
  9866. {
  9867. Client cli("127.0.0.1", PORT + 2);
  9868. cli.set_read_timeout(10, 0);
  9869. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9870. auto res =
  9871. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9872. total_received += data_length;
  9873. return true;
  9874. });
  9875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9876. EXPECT_EQ(StatusCode::OK_200, res->status);
  9877. }
  9878. server_thread.join();
  9879. EXPECT_EQ(total_received, DATA_SIZE)
  9880. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9881. << " bytes (larger than " << DATA_SIZE
  9882. << " bytes response), content_receiver should read all data, but only "
  9883. "read "
  9884. << total_received << " bytes.";
  9885. }
  9886. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9887. // Regression test for "zip bomb" attack on the client side: a malicious server
  9888. // sends a small gzip-compressed response that decompresses to a huge payload.
  9889. // The client must enforce payload_max_length on the decompressed size.
  9890. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9891. constexpr size_t DECOMPRESSED_SIZE =
  9892. 10 * 1024 * 1024; // 10MB after decompression
  9893. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9894. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9895. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9896. std::string compressed;
  9897. {
  9898. httplib::detail::gzip_compressor compressor;
  9899. bool ok =
  9900. compressor.compress(uncompressed.data(), uncompressed.size(),
  9901. /*last=*/true, [&](const char *buf, size_t len) {
  9902. compressed.append(buf, len);
  9903. return true;
  9904. });
  9905. ASSERT_TRUE(ok);
  9906. }
  9907. // Sanity: compressed data should be much smaller than the decompressed size
  9908. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9909. #ifndef _WIN32
  9910. signal(SIGPIPE, SIG_IGN);
  9911. #endif
  9912. // Set up the listening socket in the main thread so the server is guaranteed
  9913. // to be ready before the client connects (eliminates race condition).
  9914. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9915. default_socket_options(srv);
  9916. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9917. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9918. sockaddr_in addr{};
  9919. addr.sin_family = AF_INET;
  9920. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9921. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9922. int opt = 1;
  9923. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9924. #ifdef _WIN32
  9925. reinterpret_cast<const char *>(&opt),
  9926. #else
  9927. &opt,
  9928. #endif
  9929. sizeof(opt));
  9930. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9931. ASSERT_EQ(0, ::listen(srv, 1));
  9932. auto server_thread = std::thread([&compressed, srv] {
  9933. sockaddr_in cli_addr{};
  9934. socklen_t cli_len = sizeof(cli_addr);
  9935. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9936. if (cli != INVALID_SOCKET) {
  9937. // Read the full HTTP request (until \r\n\r\n)
  9938. char buf[4096];
  9939. size_t total = 0;
  9940. while (total < sizeof(buf)) {
  9941. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9942. if (n <= 0) break;
  9943. total += static_cast<size_t>(n);
  9944. // Check for end of headers
  9945. if (total >= 4) {
  9946. std::string req(buf, total);
  9947. if (req.find("\r\n\r\n") != std::string::npos) break;
  9948. }
  9949. }
  9950. // Malicious response: gzip-compressed body, no Content-Length
  9951. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9952. "Content-Encoding: gzip\r\n"
  9953. "Connection: close\r\n"
  9954. "\r\n";
  9955. ::send(cli,
  9956. #ifdef _WIN32
  9957. static_cast<const char *>(response_header.c_str()),
  9958. static_cast<int>(response_header.size()),
  9959. #else
  9960. response_header.c_str(), response_header.size(),
  9961. #endif
  9962. 0);
  9963. // Send the compressed payload (small on the wire, huge when decompressed)
  9964. size_t total_sent = 0;
  9965. while (total_sent < compressed.size()) {
  9966. auto to_send = std::min(compressed.size() - total_sent,
  9967. static_cast<size_t>(64 * 1024));
  9968. auto sent =
  9969. ::send(cli,
  9970. #ifdef _WIN32
  9971. static_cast<const char *>(compressed.c_str() + total_sent),
  9972. static_cast<int>(to_send),
  9973. #else
  9974. compressed.c_str() + total_sent, to_send,
  9975. #endif
  9976. 0);
  9977. if (sent <= 0) break;
  9978. total_sent += static_cast<size_t>(sent);
  9979. }
  9980. detail::close_socket(cli);
  9981. }
  9982. });
  9983. auto se = detail::scope_exit([&] {
  9984. detail::close_socket(srv);
  9985. server_thread.join();
  9986. });
  9987. size_t total_decompressed = 0;
  9988. {
  9989. Client cli("127.0.0.1", PORT + 3);
  9990. cli.set_read_timeout(5, 0);
  9991. cli.set_decompress(true);
  9992. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9993. auto stream = cli.open_stream("GET", "/zipbomb");
  9994. ASSERT_TRUE(stream.is_valid());
  9995. char buffer[64 * 1024];
  9996. ssize_t n;
  9997. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9998. total_decompressed += static_cast<size_t>(n);
  9999. }
  10000. }
  10001. // The decompressed size must be capped by payload_max_length. Without
  10002. // protection, the client would decompress the full 10MB from a tiny
  10003. // compressed payload, enabling a zip bomb DoS attack.
  10004. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  10005. << "Client decompressed " << total_decompressed
  10006. << " bytes from a gzip response. The decompressed size should be "
  10007. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  10008. }
  10009. #endif
  10010. TEST(HostAndPortPropertiesTest, NoSSL) {
  10011. httplib::Client cli("www.google.com", 1234);
  10012. ASSERT_EQ("www.google.com", cli.host());
  10013. ASSERT_EQ(1234, cli.port());
  10014. }
  10015. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10016. httplib::Client cli("www.google.com:1234");
  10017. ASSERT_EQ("www.google.com", cli.host());
  10018. ASSERT_EQ(1234, cli.port());
  10019. }
  10020. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10021. // Port number that overflows int — should not crash, client becomes invalid
  10022. httplib::Client cli("http://www.google.com:99999999999999999999");
  10023. ASSERT_FALSE(cli.is_valid());
  10024. }
  10025. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10026. // Port 99999 exceeds valid range (1-65535) — should not crash
  10027. httplib::Client cli("http://www.google.com:99999");
  10028. ASSERT_FALSE(cli.is_valid());
  10029. }
  10030. #ifdef CPPHTTPLIB_SSL_ENABLED
  10031. TEST(HostAndPortPropertiesTest, SSL) {
  10032. httplib::SSLClient cli("www.google.com");
  10033. ASSERT_EQ("www.google.com", cli.host());
  10034. ASSERT_EQ(443, cli.port());
  10035. }
  10036. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10037. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10038. std::string cert;
  10039. read_file(CA_CERT_FILE, cert);
  10040. httplib::SSLClient httplib_client("www.google.com");
  10041. // Load CA store first time
  10042. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10043. // Load CA store second time (update)
  10044. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10045. // Verify client is still valid and can make connections
  10046. httplib_client.enable_server_certificate_verification(true);
  10047. auto res = httplib_client.Get("/");
  10048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10049. // Google may return 200 or 301 depending on various factors
  10050. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10051. res->status == StatusCode::MovedPermanently_301);
  10052. }
  10053. TEST(SSLClientTest, ServerNameIndication_Online) {
  10054. auto host = "httpbingo.org";
  10055. auto path = std::string{"/get"};
  10056. SSLClient cli(host, 443);
  10057. auto res = cli.Get(path);
  10058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10059. ASSERT_EQ(StatusCode::OK_200, res->status);
  10060. }
  10061. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10062. // Use a site that will cause SSL verification failure due to self-signed cert
  10063. SSLClient cli("self-signed.badssl.com", 443);
  10064. cli.enable_server_certificate_verification(true);
  10065. auto res = cli.Get("/");
  10066. ASSERT_TRUE(!res);
  10067. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10068. // Verify backend error is captured for SSLServerVerification
  10069. // This occurs when certificate verification fails
  10070. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10071. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10072. EXPECT_NE(0UL, res.ssl_backend_error());
  10073. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10074. // For OpenSSL, ssl_error is 0 for verification errors
  10075. EXPECT_EQ(0, res.ssl_error());
  10076. #if !defined(_WIN32) || \
  10077. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10078. // On non-Windows or when Windows Schannel is disabled, the error comes
  10079. // from OpenSSL's verification
  10080. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10081. res.ssl_backend_error());
  10082. #endif
  10083. #endif
  10084. }
  10085. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10086. // Use a site where hostname doesn't match the certificate
  10087. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10088. SSLClient cli("wrong.host.badssl.com", 443);
  10089. cli.enable_server_certificate_verification(true);
  10090. cli.enable_server_hostname_verification(true);
  10091. auto res = cli.Get("/");
  10092. ASSERT_TRUE(!res);
  10093. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10094. // Verify backend error is captured for hostname verification failure
  10095. EXPECT_NE(0UL, res.ssl_backend_error());
  10096. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10097. // For OpenSSL, ssl_error is 0 for verification errors
  10098. EXPECT_EQ(0, res.ssl_error());
  10099. #if !defined(_WIN32) || \
  10100. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10101. // On non-Windows or when Windows Schannel is disabled, the error comes
  10102. // from OpenSSL's hostname verification
  10103. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10104. res.ssl_backend_error());
  10105. #endif
  10106. #endif
  10107. }
  10108. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10109. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10110. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10111. SSLClient cli("www.google.com", 443);
  10112. cli.enable_server_certificate_verification(true);
  10113. auto res = cli.Get("/");
  10114. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10115. }
  10116. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10117. SSLClient cli("www.google.com", 443);
  10118. cli.enable_server_certificate_verification(true);
  10119. cli.enable_windows_certificate_verification(false);
  10120. auto res = cli.Get("/");
  10121. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10122. }
  10123. #endif
  10124. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10125. Client cli("https://google.com");
  10126. auto res = cli.Get("/");
  10127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10128. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10129. }
  10130. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10131. SSLClient cli("google.com");
  10132. cli.set_ca_cert_path(CA_CERT_FILE);
  10133. auto res = cli.Get("/");
  10134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10135. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10136. }
  10137. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10138. SSLClient cli("google.com");
  10139. cli.enable_server_certificate_verification(true);
  10140. cli.set_ca_cert_path("hello");
  10141. auto res = cli.Get("/");
  10142. ASSERT_TRUE(!res);
  10143. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10144. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10145. // should be set
  10146. EXPECT_EQ(0, res.ssl_error());
  10147. // Verify backend error is captured for SSLLoadingCerts
  10148. // This error occurs when loading CA certificates fails
  10149. EXPECT_NE(0UL, res.ssl_backend_error());
  10150. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10151. // OpenSSL specific error codes:
  10152. // > openssl errstr 0x80000002
  10153. // error:80000002:system library::No such file or directory
  10154. // > openssl errstr 0xA000126
  10155. // error:0A000126:SSL routines::unexpected eof while reading
  10156. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10157. res.ssl_backend_error() == 0xA000126);
  10158. #endif
  10159. }
  10160. TEST(SSLClientTest, ServerCertificateVerification4) {
  10161. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10162. ASSERT_TRUE(svr.is_valid());
  10163. svr.Get("/test", [&](const Request &, Response &res) {
  10164. res.set_content("test", "text/plain");
  10165. svr.stop();
  10166. ASSERT_TRUE(true);
  10167. });
  10168. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10169. auto se = detail::scope_exit([&] {
  10170. t.join();
  10171. ASSERT_FALSE(svr.is_running());
  10172. });
  10173. svr.wait_until_ready();
  10174. SSLClient cli("127.0.0.1", PORT);
  10175. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10176. cli.enable_server_certificate_verification(true);
  10177. cli.set_connection_timeout(30);
  10178. auto res = cli.Get("/test");
  10179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10180. ASSERT_EQ(StatusCode::OK_200, res->status);
  10181. }
  10182. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10183. std::string cert;
  10184. read_file(CA_CERT_FILE, cert);
  10185. SSLClient cli("google.com");
  10186. cli.load_ca_cert_store(cert.data(), cert.size());
  10187. const auto res = cli.Get("/");
  10188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10189. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10190. }
  10191. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10192. // clang-format off
  10193. static constexpr char cert[] =
  10194. "GlobalSign Root CA\n"
  10195. "==================\n"
  10196. "-----BEGIN CERTIFICATE-----\n"
  10197. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10198. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10199. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10200. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10201. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10202. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10203. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10204. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10205. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10206. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10207. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10208. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10209. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10210. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10211. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10212. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10213. "-----END CERTIFICATE-----\n";
  10214. // clang-format on
  10215. SSLClient cli("google.com");
  10216. cli.load_ca_cert_store(cert, sizeof(cert));
  10217. const auto res = cli.Get("/");
  10218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10219. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10220. }
  10221. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10222. SSLClient cli("www.youtube.com");
  10223. cli.set_ca_cert_path(CA_CERT_FILE);
  10224. cli.enable_server_certificate_verification(true);
  10225. cli.set_follow_location(true);
  10226. auto res = cli.Get("/");
  10227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10228. ASSERT_EQ(StatusCode::OK_200, res->status);
  10229. }
  10230. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10231. SSLClient cli("wWw.YouTube.Com");
  10232. cli.set_ca_cert_path(CA_CERT_FILE);
  10233. cli.enable_server_certificate_verification(true);
  10234. cli.enable_server_hostname_verification(true);
  10235. cli.set_follow_location(true);
  10236. auto res = cli.Get("/");
  10237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10238. ASSERT_EQ(StatusCode::OK_200, res->status);
  10239. }
  10240. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10241. SSLClient cli("gOoGlE.COm");
  10242. cli.enable_server_certificate_verification(true);
  10243. cli.enable_server_hostname_verification(true);
  10244. cli.set_follow_location(true);
  10245. auto res = cli.Get("/");
  10246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10247. ASSERT_EQ(StatusCode::OK_200, res->status);
  10248. }
  10249. TEST(SSLClientTest, Issue2004_Online) {
  10250. Client client("https://google.com");
  10251. client.set_follow_location(true);
  10252. auto res = client.Get("/");
  10253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10254. ASSERT_EQ(StatusCode::OK_200, res->status);
  10255. auto body = res->body;
  10256. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10257. }
  10258. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10259. // Create SSLClient with invalid cert/key to make is_valid() return false
  10260. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10261. "nonexistent_key.pem");
  10262. // is_valid() should be false due to cert loading failure
  10263. ASSERT_FALSE(cli.is_valid());
  10264. auto res = cli.Get("/");
  10265. ASSERT_FALSE(res);
  10266. EXPECT_EQ(Error::SSLConnection, res.error());
  10267. }
  10268. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10269. // Test for Issue #2251: SSL error not properly reported when client cert
  10270. // and key paths are swapped or mismatched
  10271. // This simulates the scenario where user accidentally swaps the cert and key
  10272. // files
  10273. // Using client cert file as private key and vice versa (completely wrong)
  10274. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10275. // Should fail validation due to cert/key mismatch
  10276. ASSERT_FALSE(cli.is_valid());
  10277. // Attempt to make a request should fail with proper error
  10278. auto res = cli.Get("/");
  10279. ASSERT_FALSE(res);
  10280. EXPECT_EQ(Error::SSLConnection, res.error());
  10281. // SSL error should be recorded in the Result object (this is the key fix for
  10282. // Issue #2251)
  10283. auto backend_error = res.ssl_backend_error();
  10284. EXPECT_NE(0u, backend_error);
  10285. }
  10286. // Tests cert/key mismatch detection at the TLS context level
  10287. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10288. // Test that using mismatched cert/key causes connection failure.
  10289. // We verify this at the SSLClient level rather than through internal
  10290. // TLS API functions.
  10291. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10292. cli.enable_server_certificate_verification(false);
  10293. cli.set_connection_timeout(2);
  10294. // The mismatch should cause a connection or handshake error
  10295. auto res = cli.Get("/test");
  10296. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10297. // Either way, the request should fail
  10298. EXPECT_FALSE(res);
  10299. }
  10300. #endif
  10301. #if 0
  10302. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10303. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10304. ASSERT_TRUE(cli != nullptr);
  10305. cli->set_address_family(AF_INET6);
  10306. cli->set_interface("en0");
  10307. auto res = cli->Get("/get");
  10308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10309. ASSERT_EQ(StatusCode::OK_200, res->status);
  10310. }
  10311. #endif
  10312. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10313. #ifdef CPPHTTPLIB_SSL_ENABLED
  10314. void ClientCertPresent(
  10315. const std::string &client_cert_file,
  10316. const std::string &client_private_key_file,
  10317. const std::string &client_encrypted_private_key_pass = std::string()) {
  10318. using namespace httplib::tls;
  10319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10320. CLIENT_CA_CERT_DIR);
  10321. ASSERT_TRUE(svr.is_valid());
  10322. svr.Get("/test", [&](const Request &req, Response &res) {
  10323. res.set_content("test", "text/plain");
  10324. auto cert = req.peer_cert();
  10325. ASSERT_TRUE(static_cast<bool>(cert));
  10326. std::string common_name = cert.subject_cn();
  10327. EXPECT_EQ("Common Name", common_name);
  10328. });
  10329. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10330. auto se = detail::scope_exit([&] {
  10331. svr.stop();
  10332. t.join();
  10333. ASSERT_FALSE(svr.is_running());
  10334. });
  10335. svr.wait_until_ready();
  10336. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10337. client_encrypted_private_key_pass);
  10338. cli.enable_server_certificate_verification(false);
  10339. cli.set_connection_timeout(30);
  10340. auto res = cli.Get("/test");
  10341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10342. ASSERT_EQ(StatusCode::OK_200, res->status);
  10343. }
  10344. TEST(SSLClientServerTest, ClientCertPresent) {
  10345. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10346. }
  10347. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10348. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10349. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10350. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10351. }
  10352. // PEM memory-based constructor tests (works with all TLS backends)
  10353. void PemMemoryClientCertPresent(
  10354. const std::string &client_cert_file,
  10355. const std::string &client_private_key_file,
  10356. const std::string &client_encrypted_private_key_pass = std::string()) {
  10357. // Read PEM files into memory
  10358. std::string server_cert_pem, server_key_pem;
  10359. std::string client_ca_pem;
  10360. std::string client_cert_pem, client_key_pem;
  10361. read_file(SERVER_CERT_FILE, server_cert_pem);
  10362. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10363. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10364. read_file(client_cert_file, client_cert_pem);
  10365. read_file(client_private_key_file, client_key_pem);
  10366. // Create server with PEM memory
  10367. SSLServer::PemMemory server_pem = {
  10368. server_cert_pem.c_str(),
  10369. server_cert_pem.size(),
  10370. server_key_pem.c_str(),
  10371. server_key_pem.size(),
  10372. client_ca_pem.c_str(),
  10373. client_ca_pem.size(),
  10374. nullptr // no password for server key
  10375. };
  10376. SSLServer svr(server_pem);
  10377. ASSERT_TRUE(svr.is_valid());
  10378. svr.Get("/test", [&](const Request &, Response &res) {
  10379. res.set_content("test", "text/plain");
  10380. });
  10381. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10382. auto se = detail::scope_exit([&] {
  10383. svr.stop();
  10384. t.join();
  10385. ASSERT_FALSE(svr.is_running());
  10386. });
  10387. svr.wait_until_ready();
  10388. // Create client with PEM memory
  10389. const char *password = client_encrypted_private_key_pass.empty()
  10390. ? nullptr
  10391. : client_encrypted_private_key_pass.c_str();
  10392. SSLClient::PemMemory client_pem = {
  10393. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10394. client_key_pem.size(), password};
  10395. SSLClient cli(HOST, PORT, client_pem);
  10396. cli.enable_server_certificate_verification(false);
  10397. cli.set_connection_timeout(30);
  10398. auto res = cli.Get("/test");
  10399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10400. ASSERT_EQ(StatusCode::OK_200, res->status);
  10401. }
  10402. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10403. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10404. }
  10405. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10406. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10407. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10408. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10409. }
  10410. TEST(SSLClientServerTest, ClientCertMissing) {
  10411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10412. CLIENT_CA_CERT_DIR);
  10413. ASSERT_TRUE(svr.is_valid());
  10414. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10415. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10416. auto se = detail::scope_exit([&] {
  10417. svr.stop();
  10418. t.join();
  10419. ASSERT_FALSE(svr.is_running());
  10420. });
  10421. svr.wait_until_ready();
  10422. SSLClient cli(HOST, PORT);
  10423. cli.set_connection_timeout(30);
  10424. auto res = cli.Get("/test");
  10425. ASSERT_TRUE(!res);
  10426. // When client cert is missing and server requires it, connection fails
  10427. // Error type depends on backend implementation
  10428. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10429. res.error() == Error::SSLConnection);
  10430. // Verify backend error is captured
  10431. // Note: This test may have different error codes depending on the exact
  10432. // verification failure
  10433. EXPECT_NE(0UL, res.ssl_backend_error());
  10434. }
  10435. TEST(SSLClientServerTest, TrustDirOptional) {
  10436. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10437. ASSERT_TRUE(svr.is_valid());
  10438. svr.Get("/test", [&](const Request &, Response &res) {
  10439. res.set_content("test", "text/plain");
  10440. });
  10441. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10442. auto se = detail::scope_exit([&] {
  10443. svr.stop();
  10444. t.join();
  10445. ASSERT_FALSE(svr.is_running());
  10446. });
  10447. svr.wait_until_ready();
  10448. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10449. cli.enable_server_certificate_verification(false);
  10450. cli.set_connection_timeout(30);
  10451. auto res = cli.Get("/test");
  10452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10453. ASSERT_EQ(StatusCode::OK_200, res->status);
  10454. }
  10455. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10456. class NoListenSSLServer : public SSLServer {
  10457. public:
  10458. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10459. const char *client_ca_cert_file_path,
  10460. const char *client_ca_cert_dir_path = nullptr)
  10461. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10462. client_ca_cert_dir_path),
  10463. stop_(false) {}
  10464. std::atomic_bool stop_;
  10465. private:
  10466. bool process_and_close_socket(socket_t /*sock*/) override {
  10467. // Don't create SSL context
  10468. while (!stop_.load()) {
  10469. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10470. }
  10471. return true;
  10472. }
  10473. };
  10474. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10475. CLIENT_CA_CERT_FILE);
  10476. ASSERT_TRUE(svr.is_valid());
  10477. svr.Get("/test", [&](const Request &, Response &res) {
  10478. res.set_content("test", "text/plain");
  10479. });
  10480. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10481. auto se = detail::scope_exit([&] {
  10482. svr.stop_ = true;
  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. cli.enable_server_certificate_verification(false);
  10490. cli.set_connection_timeout(1);
  10491. auto res = cli.Get("/test");
  10492. ASSERT_TRUE(!res);
  10493. EXPECT_EQ(Error::SSLConnection, res.error());
  10494. // Timeout results in WantRead error code (maps to backend-specific value)
  10495. EXPECT_NE(0, res.ssl_error());
  10496. }
  10497. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10498. // Test SSLServer with client certificate verification using the standard
  10499. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10500. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10501. CLIENT_CA_CERT_DIR);
  10502. ASSERT_TRUE(svr.is_valid());
  10503. svr.Get("/test", [&](const Request &req, Response &res) {
  10504. res.set_content("test", "text/plain");
  10505. auto cert = req.peer_cert();
  10506. ASSERT_TRUE(static_cast<bool>(cert));
  10507. auto common_name = cert.subject_cn();
  10508. EXPECT_EQ("Common Name", common_name);
  10509. });
  10510. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10511. auto se = detail::scope_exit([&] {
  10512. svr.stop();
  10513. t.join();
  10514. ASSERT_FALSE(svr.is_running());
  10515. });
  10516. svr.wait_until_ready();
  10517. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10518. cli.enable_server_certificate_verification(false);
  10519. cli.set_connection_timeout(30);
  10520. auto res = cli.Get("/test");
  10521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10522. ASSERT_EQ(StatusCode::OK_200, res->status);
  10523. }
  10524. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10525. // Verifies that wildcard matching and exact matching work consistently
  10526. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10527. using namespace httplib::tls;
  10528. // We need a running server to test against
  10529. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10530. ASSERT_TRUE(svr.is_valid());
  10531. svr.Get("/test", [](const Request &, Response &res) {
  10532. res.set_content("ok", "text/plain");
  10533. });
  10534. thread t([&]() { svr.listen(HOST, PORT); });
  10535. auto se = detail::scope_exit([&] {
  10536. svr.stop();
  10537. t.join();
  10538. });
  10539. svr.wait_until_ready();
  10540. bool verify_callback_called = false;
  10541. bool verify_result_wrong = false;
  10542. SSLClient cli(HOST, PORT);
  10543. cli.enable_server_certificate_verification(true);
  10544. cli.set_ca_cert_path(CA_CERT_FILE);
  10545. cli.set_connection_timeout(5);
  10546. // Note: Test certificate has CN="Common Name", not "localhost"
  10547. bool verify_result_cn = false;
  10548. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10549. verify_callback_called = true;
  10550. if (!ctx.cert) return false;
  10551. // Test 1: "Common Name" should match (our test server cert CN)
  10552. verify_result_cn = ctx.check_hostname("Common Name");
  10553. // Test 2: wrong hostname should not match
  10554. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10555. return true; // Accept for the purpose of this test
  10556. });
  10557. auto res = cli.Get("/test");
  10558. // The request may succeed or fail depending on cert configuration
  10559. // but the callback should have been called
  10560. ASSERT_TRUE(verify_callback_called)
  10561. << "Verify callback should have been called";
  10562. // CN="Common Name" should match our test certificate
  10563. //
  10564. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10565. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10566. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10567. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10568. // <openssl/base.h>, which is included transitively when
  10569. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10570. #if defined(OPENSSL_IS_BORINGSSL)
  10571. EXPECT_FALSE(verify_result_cn)
  10572. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10573. #else
  10574. EXPECT_TRUE(verify_result_cn)
  10575. << "verify_hostname should match 'Common Name' (certificate CN)";
  10576. #endif
  10577. // Wrong hostname should not match
  10578. EXPECT_FALSE(verify_result_wrong)
  10579. << "verify_hostname should not match 'wronghost.example.com'";
  10580. }
  10581. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10582. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10583. // X509_check_ip behavior and must hold for every backend.
  10584. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10585. using namespace httplib::tls;
  10586. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10587. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10588. ASSERT_TRUE(svr.is_valid());
  10589. svr.Get("/test", [](const Request &, Response &res) {
  10590. res.set_content("ok", "text/plain");
  10591. });
  10592. thread t([&]() { svr.listen(HOST, PORT); });
  10593. auto se = detail::scope_exit([&] {
  10594. svr.stop();
  10595. t.join();
  10596. });
  10597. svr.wait_until_ready();
  10598. bool verify_callback_called = false;
  10599. bool ip_matched_via_cn = true;
  10600. SSLClient cli(HOST, PORT);
  10601. cli.enable_server_certificate_verification(true);
  10602. cli.set_ca_cert_path(CA_CERT_FILE);
  10603. cli.set_connection_timeout(5);
  10604. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10605. verify_callback_called = true;
  10606. if (!ctx.cert) return false;
  10607. // The IP appears only in the CN, so it must NOT be accepted.
  10608. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10609. return true; // Accept for the purpose of this test
  10610. });
  10611. cli.Get("/test");
  10612. ASSERT_TRUE(verify_callback_called)
  10613. << "Verify callback should have been called";
  10614. EXPECT_FALSE(ip_matched_via_cn)
  10615. << "An IP host must not be authenticated via the certificate CN";
  10616. }
  10617. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10618. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10619. using namespace httplib::tls;
  10620. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10621. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10622. ASSERT_TRUE(svr.is_valid());
  10623. svr.Get("/test", [](const Request &, Response &res) {
  10624. res.set_content("ok", "text/plain");
  10625. });
  10626. thread t([&]() { svr.listen(HOST, PORT); });
  10627. auto se = detail::scope_exit([&] {
  10628. svr.stop();
  10629. t.join();
  10630. });
  10631. svr.wait_until_ready();
  10632. bool verify_callback_called = false;
  10633. bool san_matched = false;
  10634. bool wrong_ipv6_matched = true;
  10635. bool cn_ipv6_matched = true;
  10636. SSLClient cli(HOST, PORT);
  10637. cli.enable_server_certificate_verification(true);
  10638. cli.set_ca_cert_path(CA_CERT_FILE);
  10639. cli.set_connection_timeout(5);
  10640. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10641. verify_callback_called = true;
  10642. if (!ctx.cert) return false;
  10643. // Matches the IPv6 iPAddress SAN.
  10644. san_matched = ctx.check_hostname("2001:db8::1");
  10645. // A different IPv6 address must not match.
  10646. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10647. // "::1" lives only in the CN, so it must not be accepted.
  10648. cn_ipv6_matched = ctx.check_hostname("::1");
  10649. return true; // Accept for the purpose of this test
  10650. });
  10651. cli.Get("/test");
  10652. ASSERT_TRUE(verify_callback_called)
  10653. << "Verify callback should have been called";
  10654. EXPECT_TRUE(san_matched)
  10655. << "verify_hostname should match an IPv6 iPAddress SAN";
  10656. EXPECT_FALSE(wrong_ipv6_matched)
  10657. << "verify_hostname should not match a non-matching IPv6 address";
  10658. EXPECT_FALSE(cn_ipv6_matched)
  10659. << "An IPv6 host must not be authenticated via the certificate CN";
  10660. }
  10661. #endif
  10662. // mbedTLS-specific callback constructor test
  10663. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10664. #ifdef CPPHTTPLIB_SSL_ENABLED
  10665. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10667. ASSERT_TRUE(svr.is_valid());
  10668. // Set up a handler to verify client certificate is present
  10669. bool client_cert_verified = false;
  10670. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10671. // Verify that client certificate was provided
  10672. client_cert_verified = true;
  10673. res.set_content("success", "text/plain");
  10674. });
  10675. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. t.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.wait_until_ready();
  10682. // Client with certificate
  10683. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10684. cli.enable_server_certificate_verification(false);
  10685. cli.set_connection_timeout(30);
  10686. auto res = cli.Get("/test");
  10687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10688. ASSERT_EQ(StatusCode::OK_200, res->status);
  10689. ASSERT_TRUE(client_cert_verified);
  10690. EXPECT_EQ("success", res->body);
  10691. }
  10692. #endif
  10693. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10694. // backends
  10695. #ifdef CPPHTTPLIB_SSL_ENABLED
  10696. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10697. using namespace httplib::tls;
  10698. // Test that when client CA cert file is provided,
  10699. // the server properly requests and validates client certificates
  10700. // Create a server with client authentication
  10701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10702. ASSERT_TRUE(svr.is_valid());
  10703. bool handler_called = false;
  10704. svr.Get("/test", [&](const Request &req, Response &res) {
  10705. handler_called = true;
  10706. // Verify that a client certificate was provided
  10707. auto cert = req.peer_cert();
  10708. ASSERT_TRUE(static_cast<bool>(cert));
  10709. // Get the issuer name
  10710. std::string issuer_str = cert.issuer_name();
  10711. ASSERT_FALSE(issuer_str.empty());
  10712. // The client certificate should be issued by our test CA
  10713. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10714. res.set_content("authenticated", "text/plain");
  10715. });
  10716. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10717. auto se = detail::scope_exit([&] {
  10718. svr.stop();
  10719. t.join();
  10720. ASSERT_FALSE(svr.is_running());
  10721. });
  10722. svr.wait_until_ready();
  10723. // Connect with a client certificate issued by the CA
  10724. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10725. cli.enable_server_certificate_verification(false);
  10726. cli.set_connection_timeout(30);
  10727. auto res = cli.Get("/test");
  10728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10729. ASSERT_EQ(StatusCode::OK_200, res->status);
  10730. ASSERT_TRUE(handler_called);
  10731. EXPECT_EQ("authenticated", res->body);
  10732. }
  10733. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10734. using namespace httplib::tls;
  10735. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10736. ASSERT_TRUE(svr.is_valid());
  10737. svr.Get("/test", [](const Request &, Response &res) {
  10738. res.set_content("ok", "text/plain");
  10739. });
  10740. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10741. auto se = detail::scope_exit([&] {
  10742. svr.stop();
  10743. t.join();
  10744. });
  10745. svr.wait_until_ready();
  10746. SSLClient cli(HOST, PORT);
  10747. cli.enable_server_certificate_verification(false);
  10748. cli.set_connection_timeout(30);
  10749. bool cert_checked = false;
  10750. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10751. if (ctx.cert) {
  10752. auto sans = ctx.sans();
  10753. // Test certificate may or may not have SANs - just verify the API
  10754. // works If SANs exist, verify the types are valid
  10755. for (const auto &san : sans) {
  10756. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10757. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10758. san.type == SanType::OTHER);
  10759. EXPECT_FALSE(san.value.empty());
  10760. }
  10761. cert_checked = true;
  10762. }
  10763. return true;
  10764. });
  10765. auto res = cli.Get("/test");
  10766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10767. EXPECT_TRUE(cert_checked);
  10768. }
  10769. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10770. using namespace httplib::tls;
  10771. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10772. ASSERT_TRUE(svr.is_valid());
  10773. svr.Get("/test", [](const Request &, Response &res) {
  10774. res.set_content("ok", "text/plain");
  10775. });
  10776. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10777. auto se = detail::scope_exit([&] {
  10778. svr.stop();
  10779. t.join();
  10780. });
  10781. svr.wait_until_ready();
  10782. SSLClient cli(HOST, PORT);
  10783. cli.enable_server_certificate_verification(false);
  10784. cli.set_connection_timeout(30);
  10785. bool validity_checked = false;
  10786. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10787. if (ctx.cert) {
  10788. time_t not_before = 0, not_after = 0;
  10789. bool result = ctx.validity(not_before, not_after);
  10790. EXPECT_TRUE(result);
  10791. // Verify that not_before < now < not_after for a valid cert
  10792. time_t now = time(nullptr);
  10793. EXPECT_LT(not_before, now);
  10794. EXPECT_GT(not_after, now);
  10795. validity_checked = true;
  10796. }
  10797. return true;
  10798. });
  10799. auto res = cli.Get("/test");
  10800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10801. EXPECT_TRUE(validity_checked);
  10802. }
  10803. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10804. using namespace httplib::tls;
  10805. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10806. ASSERT_TRUE(svr.is_valid());
  10807. svr.Get("/test", [](const Request &, Response &res) {
  10808. res.set_content("ok", "text/plain");
  10809. });
  10810. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10811. auto se = detail::scope_exit([&] {
  10812. svr.stop();
  10813. t.join();
  10814. });
  10815. svr.wait_until_ready();
  10816. SSLClient cli(HOST, PORT);
  10817. cli.enable_server_certificate_verification(false);
  10818. cli.set_connection_timeout(30);
  10819. bool serial_checked = false;
  10820. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10821. if (ctx.cert) {
  10822. std::string serial = ctx.serial();
  10823. EXPECT_FALSE(serial.empty());
  10824. // Serial should be a hex string
  10825. for (char c : serial) {
  10826. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10827. (c >= 'a' && c <= 'f'));
  10828. }
  10829. serial_checked = true;
  10830. }
  10831. return true;
  10832. });
  10833. auto res = cli.Get("/test");
  10834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10835. EXPECT_TRUE(serial_checked);
  10836. }
  10837. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10838. // Test 1: Valid CA file - no error should be recorded
  10839. {
  10840. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10841. CLIENT_CA_CERT_FILE);
  10842. ASSERT_TRUE(svr.is_valid());
  10843. // With valid setup, last_ssl_error should be 0
  10844. EXPECT_EQ(0, svr.ssl_last_error());
  10845. }
  10846. // Test 2: Invalid CA file content
  10847. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10848. {
  10849. // Create a temporary file with completely invalid content
  10850. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10851. {
  10852. std::ofstream ofs(temp_invalid_ca);
  10853. ofs << "This is not a certificate file at all\n";
  10854. ofs << "Just plain text content\n";
  10855. }
  10856. // Create server with invalid CA file
  10857. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10858. // Clean up temporary file
  10859. std::remove(temp_invalid_ca);
  10860. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10861. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10862. // Note: SSL_CTX_load_verify_locations typically fails first,
  10863. // but our error handling code path is still exercised
  10864. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10865. }
  10866. }
  10867. TEST(VerifyCallbackTest, VerifyContextFields) {
  10868. using namespace httplib::tls;
  10869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10870. ASSERT_TRUE(svr.is_valid());
  10871. svr.Get("/test", [](const Request &, Response &res) {
  10872. res.set_content("ok", "text/plain");
  10873. });
  10874. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10875. auto se = detail::scope_exit([&] {
  10876. svr.stop();
  10877. t.join();
  10878. });
  10879. svr.wait_until_ready();
  10880. SSLClient cli(HOST, PORT);
  10881. cli.enable_server_certificate_verification(false);
  10882. cli.set_connection_timeout(30);
  10883. int callback_count = 0;
  10884. bool saw_leaf_cert = false;
  10885. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10886. if (ctx.cert) {
  10887. callback_count++;
  10888. // We should see at least one certificate (the leaf)
  10889. std::string cn = ctx.subject_cn();
  10890. if (!cn.empty()) { saw_leaf_cert = true; }
  10891. // Verify context fields are populated
  10892. EXPECT_NE(ctx.session, nullptr);
  10893. EXPECT_GE(ctx.depth, 0);
  10894. }
  10895. return true;
  10896. });
  10897. auto res = cli.Get("/test");
  10898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10899. EXPECT_GT(callback_count, 0);
  10900. EXPECT_TRUE(saw_leaf_cert);
  10901. }
  10902. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10903. using httplib::tls::TlsError;
  10904. // Test that verify_error_to_string returns empty for success
  10905. std::string success_str = TlsError::verify_error_to_string(0);
  10906. EXPECT_TRUE(success_str.empty());
  10907. // Test that verify_error_to_string returns non-empty for error codes
  10908. // Using a common error code (certificate expired)
  10909. std::string error_str =
  10910. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10911. EXPECT_FALSE(error_str.empty());
  10912. }
  10913. TEST(SessionVerifierTest, CertificateAccepted) {
  10914. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10915. ASSERT_TRUE(svr.is_valid());
  10916. svr.Get("/test", [](const Request &, Response &res) {
  10917. res.set_content("ok", "text/plain");
  10918. });
  10919. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10920. auto se = detail::scope_exit([&] {
  10921. svr.stop();
  10922. t.join();
  10923. });
  10924. svr.wait_until_ready();
  10925. SSLClient cli(HOST, PORT);
  10926. cli.enable_server_certificate_verification(false);
  10927. cli.set_connection_timeout(30);
  10928. bool callback_called = false;
  10929. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10930. EXPECT_NE(session, nullptr);
  10931. callback_called = true;
  10932. return SSLVerifierResponse::CertificateAccepted;
  10933. });
  10934. auto res = cli.Get("/test");
  10935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10936. EXPECT_EQ(200, res->status);
  10937. EXPECT_TRUE(callback_called);
  10938. }
  10939. TEST(SessionVerifierTest, CertificateRejected) {
  10940. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10941. ASSERT_TRUE(svr.is_valid());
  10942. svr.Get("/test", [](const Request &, Response &res) {
  10943. res.set_content("ok", "text/plain");
  10944. });
  10945. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10946. auto se = detail::scope_exit([&] {
  10947. svr.stop();
  10948. t.join();
  10949. });
  10950. svr.wait_until_ready();
  10951. SSLClient cli(HOST, PORT);
  10952. cli.enable_server_certificate_verification(false);
  10953. cli.set_connection_timeout(30);
  10954. bool callback_called = false;
  10955. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10956. EXPECT_NE(session, nullptr);
  10957. callback_called = true;
  10958. return SSLVerifierResponse::CertificateRejected;
  10959. });
  10960. auto res = cli.Get("/test");
  10961. EXPECT_FALSE(res);
  10962. EXPECT_TRUE(callback_called);
  10963. }
  10964. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10965. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10966. ASSERT_TRUE(svr.is_valid());
  10967. svr.Get("/test", [](const Request &, Response &res) {
  10968. res.set_content("ok", "text/plain");
  10969. });
  10970. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10971. auto se = detail::scope_exit([&] {
  10972. svr.stop();
  10973. t.join();
  10974. });
  10975. svr.wait_until_ready();
  10976. // NoDecisionMade with verification disabled should succeed (no default check)
  10977. SSLClient cli(HOST, PORT);
  10978. cli.enable_server_certificate_verification(false);
  10979. cli.set_connection_timeout(30);
  10980. bool callback_called = false;
  10981. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10982. EXPECT_NE(session, nullptr);
  10983. callback_called = true;
  10984. return SSLVerifierResponse::NoDecisionMade;
  10985. });
  10986. auto res = cli.Get("/test");
  10987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10988. EXPECT_EQ(200, res->status);
  10989. EXPECT_TRUE(callback_called);
  10990. }
  10991. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10993. ASSERT_TRUE(svr.is_valid());
  10994. svr.Get("/test", [](const Request &, Response &res) {
  10995. res.set_content("ok", "text/plain");
  10996. });
  10997. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10998. auto se = detail::scope_exit([&] {
  10999. svr.stop();
  11000. t.join();
  11001. });
  11002. svr.wait_until_ready();
  11003. // NoDecisionMade with verification enabled should fail (self-signed cert).
  11004. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  11005. // so we only check that the request fails, not whether the callback was
  11006. // called.
  11007. SSLClient cli(HOST, PORT);
  11008. cli.enable_server_certificate_verification(true);
  11009. cli.set_connection_timeout(30);
  11010. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  11011. EXPECT_NE(session, nullptr);
  11012. return SSLVerifierResponse::NoDecisionMade;
  11013. });
  11014. auto res = cli.Get("/test");
  11015. EXPECT_FALSE(res);
  11016. }
  11017. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11018. // Test SSL server using PemMemory constructor with client CA certificates
  11019. // Read PEM files
  11020. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11021. read_file(SERVER_CERT_FILE, server_cert_pem);
  11022. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11023. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11024. // Create SSLServer with PemMemory constructor including client CA
  11025. SSLServer::PemMemory server_pem = {
  11026. server_cert_pem.c_str(),
  11027. server_cert_pem.size(),
  11028. server_key_pem.c_str(),
  11029. server_key_pem.size(),
  11030. client_ca_pem.c_str(),
  11031. client_ca_pem.size(),
  11032. nullptr // no password for server key
  11033. };
  11034. SSLServer svr(server_pem);
  11035. ASSERT_TRUE(svr.is_valid());
  11036. // No SSL error should be recorded for valid setup
  11037. EXPECT_EQ(0, svr.ssl_last_error());
  11038. // Set up server endpoints
  11039. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11040. res.set_content("ok", "text/plain");
  11041. });
  11042. // Start server in a thread
  11043. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11044. svr.wait_until_ready();
  11045. // Connect with client certificate (using constructor with paths)
  11046. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11047. cli.enable_server_certificate_verification(false);
  11048. auto res = cli.Get("/test-pem-ca");
  11049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11050. EXPECT_EQ(200, res->status);
  11051. EXPECT_EQ("ok", res->body);
  11052. svr.stop();
  11053. server_thread.join();
  11054. }
  11055. #endif
  11056. #ifdef _WIN32
  11057. TEST(CleanupTest, WSACleanup) {
  11058. int ret = WSACleanup();
  11059. ASSERT_EQ(0, ret);
  11060. }
  11061. #endif
  11062. #ifndef CPPHTTPLIB_SSL_ENABLED
  11063. TEST(NoSSLSupport, SimpleInterface) {
  11064. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11065. }
  11066. #endif
  11067. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11068. TEST(InvalidScheme, SimpleInterface) {
  11069. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11070. }
  11071. #endif
  11072. TEST(NoScheme, SimpleInterface) {
  11073. Client cli("yahoo.com:80");
  11074. ASSERT_TRUE(cli.is_valid());
  11075. }
  11076. TEST(SendAPI, SimpleInterface_Online) {
  11077. Client cli("http://yahoo.com");
  11078. Request req;
  11079. req.method = "GET";
  11080. req.path = "/";
  11081. auto res = cli.send(req);
  11082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11083. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11084. }
  11085. TEST(SendAPI, WithParamsInRequest) {
  11086. Server svr;
  11087. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11088. EXPECT_TRUE(req.has_param("test"));
  11089. EXPECT_EQ("test_value", req.get_param_value("test"));
  11090. });
  11091. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11092. auto se = detail::scope_exit([&] {
  11093. svr.stop();
  11094. t.join();
  11095. ASSERT_FALSE(svr.is_running());
  11096. });
  11097. svr.wait_until_ready();
  11098. Client cli(HOST, PORT);
  11099. {
  11100. Request req;
  11101. req.method = "GET";
  11102. req.path = "/";
  11103. req.params.emplace("test", "test_value");
  11104. auto res = cli.send(req);
  11105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11106. }
  11107. {
  11108. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11110. }
  11111. }
  11112. TEST(ClientImplMethods, GetSocketTest) {
  11113. httplib::Server svr;
  11114. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11115. res.status = StatusCode::OK_200;
  11116. });
  11117. auto port = svr.bind_to_any_port("127.0.0.1");
  11118. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11119. auto se = detail::scope_exit([&] {
  11120. svr.stop();
  11121. thread.join();
  11122. ASSERT_FALSE(svr.is_running());
  11123. });
  11124. svr.wait_until_ready();
  11125. {
  11126. httplib::Client cli("127.0.0.1", port);
  11127. cli.set_keep_alive(true);
  11128. // Use the behavior of cpp-httplib of opening the connection
  11129. // only when the first request happens. If that changes,
  11130. // this test would be obsolete.
  11131. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11132. // This also implicitly tests the server. But other tests would fail much
  11133. // earlier than this one to be considered.
  11134. auto res = cli.Get("/");
  11135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11136. EXPECT_EQ(StatusCode::OK_200, res->status);
  11137. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11138. }
  11139. }
  11140. #ifdef CPPHTTPLIB_SSL_ENABLED
  11141. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11142. Client cli("http://yahoo.com");
  11143. auto res = cli.Get("/");
  11144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11145. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11146. cli.set_follow_location(true);
  11147. res = cli.Get("/");
  11148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11149. EXPECT_EQ(StatusCode::OK_200, res->status);
  11150. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11151. }
  11152. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11153. Client cli("https://yahoo.com");
  11154. auto res = cli.Get("/");
  11155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11156. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11157. cli.set_follow_location(true);
  11158. res = cli.Get("/");
  11159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11160. EXPECT_EQ(StatusCode::OK_200, res->status);
  11161. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11162. }
  11163. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11164. Client cli("https://yahoo.com");
  11165. auto res = cli.Get("/");
  11166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11167. ASSERT_FALSE(!res);
  11168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11169. ASSERT_FALSE(res == nullptr);
  11170. ASSERT_TRUE(res != nullptr);
  11171. EXPECT_EQ(Error::Success, res.error());
  11172. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11173. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11174. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11175. cli.set_follow_location(true);
  11176. res = cli.Get("/");
  11177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11178. EXPECT_EQ(Error::Success, res.error());
  11179. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11180. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11181. EXPECT_EQ(StatusCode::OK_200, res->status);
  11182. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11183. }
  11184. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11185. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11186. Client cli("https://cdnjs.cloudflare.com");
  11187. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11188. Headers{{"Accept-Encoding", "br"}});
  11189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11190. EXPECT_EQ(StatusCode::OK_200, res->status);
  11191. EXPECT_EQ(287630U, res->body.size());
  11192. EXPECT_EQ("application/javascript; charset=utf-8",
  11193. res->get_header_value("Content-Type"));
  11194. }
  11195. #endif
  11196. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11197. #undef REDIR_HOST // Silence compiler warning
  11198. #define REDIR_HOST "https://httpbingo.org"
  11199. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11200. Client cli(REDIR_HOST);
  11201. cli.set_follow_location(true);
  11202. auto res =
  11203. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11205. EXPECT_EQ(StatusCode::OK_200, res->status);
  11206. }
  11207. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11208. Client cli(REDIR_HOST);
  11209. cli.set_follow_location(true);
  11210. Params params;
  11211. params.emplace("url", "http://example.com");
  11212. params.emplace("status_code", "302");
  11213. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11215. EXPECT_EQ(StatusCode::OK_200, res->status);
  11216. }
  11217. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11218. Client cli(REDIR_HOST);
  11219. cli.set_follow_location(true);
  11220. Params params;
  11221. params.emplace("url", "http://example.com");
  11222. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11224. EXPECT_EQ(StatusCode::OK_200, res->status);
  11225. }
  11226. TEST(HttpToHttpsRedirectTest, CertFile) {
  11227. auto ssl_port = PORT + 1;
  11228. Server svr;
  11229. ASSERT_TRUE(svr.is_valid());
  11230. svr.Get("/index", [&](const Request &, Response &res) {
  11231. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11232. "/index");
  11233. svr.stop();
  11234. });
  11235. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11236. ASSERT_TRUE(ssl_svr.is_valid());
  11237. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11238. res.set_content("test", "text/plain");
  11239. ssl_svr.stop();
  11240. });
  11241. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11242. thread t2 =
  11243. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11244. auto se = detail::scope_exit([&] {
  11245. t2.join();
  11246. t.join();
  11247. ASSERT_FALSE(svr.is_running());
  11248. });
  11249. svr.wait_until_ready();
  11250. ssl_svr.wait_until_ready();
  11251. Client cli("127.0.0.1", PORT);
  11252. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11253. cli.enable_server_certificate_verification(true);
  11254. cli.set_follow_location(true);
  11255. cli.set_connection_timeout(30);
  11256. auto res = cli.Get("/index");
  11257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11258. ASSERT_EQ(StatusCode::OK_200, res->status);
  11259. }
  11260. TEST(SSLClientRedirectTest, CertFile) {
  11261. auto ssl_port = PORT + 1;
  11262. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11263. ASSERT_TRUE(ssl_svr1.is_valid());
  11264. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11265. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11266. "/index");
  11267. ssl_svr1.stop();
  11268. });
  11269. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11270. ASSERT_TRUE(ssl_svr2.is_valid());
  11271. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11272. res.set_content("test", "text/plain");
  11273. ssl_svr2.stop();
  11274. });
  11275. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11276. thread t2 =
  11277. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11278. auto se = detail::scope_exit([&] {
  11279. t2.join();
  11280. t.join();
  11281. ASSERT_FALSE(ssl_svr1.is_running());
  11282. });
  11283. ssl_svr1.wait_until_ready();
  11284. ssl_svr2.wait_until_ready();
  11285. SSLClient cli("127.0.0.1", PORT);
  11286. std::string cert;
  11287. read_file(SERVER_CERT2_FILE, cert);
  11288. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11289. cli.enable_server_certificate_verification(true);
  11290. cli.set_follow_location(true);
  11291. cli.set_connection_timeout(30);
  11292. auto res = cli.Get("/index");
  11293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11294. ASSERT_EQ(StatusCode::OK_200, res->status);
  11295. }
  11296. #endif
  11297. #ifdef CPPHTTPLIB_SSL_ENABLED
  11298. // Test that set_ca_cert_store() skips system certs (consistent with
  11299. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11300. // should be trusted - system certs should NOT be loaded.
  11301. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11302. // Load a specific cert that is NOT a system CA cert
  11303. std::string cert;
  11304. read_file(SERVER_CERT2_FILE, cert);
  11305. SSLClient cli("google.com");
  11306. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11307. cli.enable_server_certificate_verification(true);
  11308. // This should FAIL because:
  11309. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11310. // 2. System certs should NOT be loaded when custom store is set
  11311. // If system certs WERE loaded, this would succeed
  11312. auto res = cli.Get("/");
  11313. ASSERT_FALSE(res);
  11314. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11315. }
  11316. // Same as above, but through the native store handle path. Regression test:
  11317. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11318. // merged system certs into the user-provided store.
  11319. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11320. std::string cert;
  11321. read_file(SERVER_CERT2_FILE, cert);
  11322. SSLClient cli("google.com");
  11323. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11324. cli.enable_server_certificate_verification(true);
  11325. auto res = cli.Get("/");
  11326. ASSERT_FALSE(res);
  11327. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11328. }
  11329. // A custom store set via the native handle must still verify a server whose
  11330. // cert it does contain.
  11331. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11332. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11333. ASSERT_TRUE(svr.is_valid());
  11334. svr.Get("/test", [&](const Request &, Response &res) {
  11335. res.set_content("test", "text/plain");
  11336. });
  11337. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11338. auto se = detail::scope_exit([&] {
  11339. svr.stop();
  11340. t.join();
  11341. ASSERT_FALSE(svr.is_running());
  11342. });
  11343. svr.wait_until_ready();
  11344. SSLClient cli("127.0.0.1", PORT);
  11345. std::string cert;
  11346. read_file(SERVER_CERT2_FILE, cert);
  11347. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11348. cli.enable_server_certificate_verification(true);
  11349. cli.set_connection_timeout(30);
  11350. auto res = cli.Get("/test");
  11351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11352. ASSERT_EQ(StatusCode::OK_200, res->status);
  11353. }
  11354. // CA certs loaded through the universal Client must be transferred to the
  11355. // client created internally for following an HTTPS redirect. Regression test:
  11356. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11357. // the CA data for redirect transfer.
  11358. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11359. auto ssl_port = PORT + 1;
  11360. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11361. ASSERT_TRUE(ssl_svr1.is_valid());
  11362. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11363. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11364. "/index");
  11365. });
  11366. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11367. ASSERT_TRUE(ssl_svr2.is_valid());
  11368. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11369. res.set_content("test", "text/plain");
  11370. });
  11371. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11372. thread t2 =
  11373. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11374. auto se = detail::scope_exit([&] {
  11375. ssl_svr2.stop();
  11376. ssl_svr1.stop();
  11377. t2.join();
  11378. t.join();
  11379. ASSERT_FALSE(ssl_svr1.is_running());
  11380. });
  11381. ssl_svr1.wait_until_ready();
  11382. ssl_svr2.wait_until_ready();
  11383. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11384. std::string cert;
  11385. read_file(SERVER_CERT2_FILE, cert);
  11386. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11387. cli.enable_server_certificate_verification(true);
  11388. cli.set_follow_location(true);
  11389. cli.set_connection_timeout(30);
  11390. auto res = cli.Get("/index");
  11391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11392. ASSERT_EQ(StatusCode::OK_200, res->status);
  11393. }
  11394. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11395. // so a host signed by a system CA verifies even though a custom CA is set
  11396. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11397. std::string cert;
  11398. read_file(SERVER_CERT2_FILE, cert);
  11399. SSLClient cli("google.com");
  11400. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11401. cli.enable_system_ca(true);
  11402. cli.enable_server_certificate_verification(true);
  11403. auto res = cli.Get("/");
  11404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11405. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11406. }
  11407. // The custom CA remains effective when combined with the system CA
  11408. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11409. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11410. ASSERT_TRUE(svr.is_valid());
  11411. svr.Get("/test", [&](const Request &, Response &res) {
  11412. res.set_content("test", "text/plain");
  11413. });
  11414. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11415. auto se = detail::scope_exit([&] {
  11416. svr.stop();
  11417. t.join();
  11418. ASSERT_FALSE(svr.is_running());
  11419. });
  11420. svr.wait_until_ready();
  11421. SSLClient cli("127.0.0.1", PORT);
  11422. std::string cert;
  11423. read_file(SERVER_CERT2_FILE, cert);
  11424. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11425. cli.enable_system_ca(true);
  11426. cli.enable_server_certificate_verification(true);
  11427. cli.set_connection_timeout(30);
  11428. auto res = cli.Get("/test");
  11429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11430. ASSERT_EQ(StatusCode::OK_200, res->status);
  11431. }
  11432. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11433. // skip chain verification entirely (only the certificate identity was
  11434. // checked), so a server presenting an untrusted certificate with a matching
  11435. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11436. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11437. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11438. ASSERT_TRUE(svr.is_valid());
  11439. svr.Get("/test", [&](const Request &, Response &res) {
  11440. res.set_content("test", "text/plain");
  11441. });
  11442. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11443. auto se = detail::scope_exit([&] {
  11444. svr.stop();
  11445. t.join();
  11446. ASSERT_FALSE(svr.is_running());
  11447. });
  11448. svr.wait_until_ready();
  11449. SSLClient cli("127.0.0.1", PORT);
  11450. std::string cert;
  11451. // A trusted CA that did not sign the server certificate. The server cert
  11452. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11453. // this connection.
  11454. read_file(CLIENT_CA_CERT_FILE, cert);
  11455. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11456. cli.enable_server_certificate_verification(true);
  11457. cli.set_connection_timeout(30);
  11458. auto res = cli.Get("/test");
  11459. ASSERT_FALSE(res);
  11460. }
  11461. // enable_system_ca(false) prevents system CA loading entirely
  11462. TEST(SSLClientTest, DisableSystemCa_Online) {
  11463. SSLClient cli("google.com");
  11464. cli.enable_system_ca(false);
  11465. cli.enable_server_certificate_verification(true);
  11466. auto res = cli.Get("/");
  11467. ASSERT_FALSE(res);
  11468. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11469. // itself when the CA chain is empty
  11470. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11471. res.error() == Error::SSLConnection);
  11472. }
  11473. // The universal Client forwards enable_system_ca()
  11474. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11475. std::string cert;
  11476. read_file(SERVER_CERT2_FILE, cert);
  11477. Client cli("https://google.com");
  11478. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11479. cli.enable_system_ca(true);
  11480. cli.enable_server_certificate_verification(true);
  11481. auto res = cli.Get("/");
  11482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11483. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11484. }
  11485. // The system CA policy must carry over to the client created internally for
  11486. // following a cross-host HTTPS redirect
  11487. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11488. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11489. ASSERT_TRUE(svr.is_valid());
  11490. svr.Get("/index", [&](const Request &, Response &res) {
  11491. res.set_redirect("https://www.google.com/");
  11492. });
  11493. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11494. auto se = detail::scope_exit([&] {
  11495. svr.stop();
  11496. t.join();
  11497. ASSERT_FALSE(svr.is_running());
  11498. });
  11499. svr.wait_until_ready();
  11500. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11501. std::string cert;
  11502. read_file(SERVER_CERT2_FILE, cert);
  11503. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11504. cli.enable_system_ca(true);
  11505. cli.enable_server_certificate_verification(true);
  11506. cli.set_follow_location(true);
  11507. cli.set_connection_timeout(30);
  11508. // Receiving any response proves the redirect client completed the TLS
  11509. // handshake with a system-CA-signed host
  11510. auto res = cli.Get("/index");
  11511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11512. }
  11513. TEST(MultipartFormDataTest, LargeData) {
  11514. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11515. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11516. const ContentReader &content_reader) {
  11517. if (req.is_multipart_form_data()) {
  11518. std::vector<FormData> items;
  11519. content_reader(
  11520. [&](const FormData &file) {
  11521. items.push_back(file);
  11522. return true;
  11523. },
  11524. [&](const char *data, size_t data_length) {
  11525. items.back().content.append(data, data_length);
  11526. return true;
  11527. });
  11528. EXPECT_TRUE(std::string(items[0].name) == "document");
  11529. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11530. EXPECT_TRUE(items[0].filename == "2MB_data");
  11531. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11532. EXPECT_TRUE(items[1].name == "hello");
  11533. EXPECT_TRUE(items[1].content == "world");
  11534. EXPECT_TRUE(items[1].filename == "");
  11535. EXPECT_TRUE(items[1].content_type == "");
  11536. } else {
  11537. std::string body;
  11538. content_reader([&](const char *data, size_t data_length) {
  11539. body.append(data, data_length);
  11540. return true;
  11541. });
  11542. }
  11543. });
  11544. auto port = svr.bind_to_any_port(HOST);
  11545. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11546. auto se = detail::scope_exit([&] {
  11547. svr.stop();
  11548. t.join();
  11549. ASSERT_FALSE(svr.is_running());
  11550. });
  11551. svr.wait_until_ready();
  11552. {
  11553. std::string data(1024 * 1024 * 2, '.');
  11554. std::stringstream buffer;
  11555. buffer << data;
  11556. SSLClient cli(HOST, port);
  11557. cli.enable_server_certificate_verification(false);
  11558. UploadFormDataItems items{
  11559. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11560. {"hello", "world", "", ""},
  11561. };
  11562. auto res = cli.Post("/post", items);
  11563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11564. ASSERT_EQ(StatusCode::OK_200, res->status);
  11565. }
  11566. }
  11567. TEST(MultipartFormDataTest, DataProviderItems) {
  11568. std::random_device seed_gen;
  11569. std::mt19937 random(seed_gen());
  11570. std::string rand1;
  11571. rand1.resize(1000);
  11572. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11573. std::string rand2;
  11574. rand2.resize(3000);
  11575. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11576. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11577. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11578. const ContentReader &content_reader) {
  11579. ASSERT_FALSE(req.is_multipart_form_data());
  11580. std::string body;
  11581. content_reader([&](const char *data, size_t data_length) {
  11582. body.append(data, data_length);
  11583. return true;
  11584. });
  11585. EXPECT_EQ(body, "");
  11586. });
  11587. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11588. const ContentReader &content_reader) {
  11589. ASSERT_TRUE(req.is_multipart_form_data());
  11590. std::vector<FormData> items;
  11591. content_reader(
  11592. [&](const FormData &file) {
  11593. items.push_back(file);
  11594. return true;
  11595. },
  11596. [&](const char *data, size_t data_length) {
  11597. items.back().content.append(data, data_length);
  11598. return true;
  11599. });
  11600. ASSERT_TRUE(items.size() == 2);
  11601. EXPECT_EQ(std::string(items[0].name), "name1");
  11602. EXPECT_EQ(items[0].content, "Testing123");
  11603. EXPECT_EQ(items[0].filename, "filename1");
  11604. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11605. EXPECT_EQ(items[1].name, "name2");
  11606. EXPECT_EQ(items[1].content, "Testing456");
  11607. EXPECT_EQ(items[1].filename, "");
  11608. EXPECT_EQ(items[1].content_type, "");
  11609. });
  11610. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11611. const ContentReader &content_reader) {
  11612. ASSERT_TRUE(req.is_multipart_form_data());
  11613. std::vector<FormData> items;
  11614. content_reader(
  11615. [&](const FormData &file) {
  11616. items.push_back(file);
  11617. return true;
  11618. },
  11619. [&](const char *data, size_t data_length) {
  11620. items.back().content.append(data, data_length);
  11621. return true;
  11622. });
  11623. ASSERT_TRUE(items.size() == 2);
  11624. EXPECT_EQ(items[0].name, "name3");
  11625. EXPECT_EQ(items[0].content, rand1);
  11626. EXPECT_EQ(items[0].filename, "filename3");
  11627. EXPECT_EQ(items[0].content_type, "");
  11628. EXPECT_EQ(items[1].name, "name4");
  11629. EXPECT_EQ(items[1].content, rand2);
  11630. EXPECT_EQ(items[1].filename, "filename4");
  11631. EXPECT_EQ(items[1].content_type, "");
  11632. });
  11633. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11634. const ContentReader &content_reader) {
  11635. ASSERT_TRUE(req.is_multipart_form_data());
  11636. std::vector<FormData> items;
  11637. content_reader(
  11638. [&](const FormData &file) {
  11639. items.push_back(file);
  11640. return true;
  11641. },
  11642. [&](const char *data, size_t data_length) {
  11643. items.back().content.append(data, data_length);
  11644. return true;
  11645. });
  11646. ASSERT_TRUE(items.size() == 4);
  11647. EXPECT_EQ(std::string(items[0].name), "name1");
  11648. EXPECT_EQ(items[0].content, "Testing123");
  11649. EXPECT_EQ(items[0].filename, "filename1");
  11650. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11651. EXPECT_EQ(items[1].name, "name2");
  11652. EXPECT_EQ(items[1].content, "Testing456");
  11653. EXPECT_EQ(items[1].filename, "");
  11654. EXPECT_EQ(items[1].content_type, "");
  11655. EXPECT_EQ(items[2].name, "name3");
  11656. EXPECT_EQ(items[2].content, rand1);
  11657. EXPECT_EQ(items[2].filename, "filename3");
  11658. EXPECT_EQ(items[2].content_type, "");
  11659. EXPECT_EQ(items[3].name, "name4");
  11660. EXPECT_EQ(items[3].content, rand2);
  11661. EXPECT_EQ(items[3].filename, "filename4");
  11662. EXPECT_EQ(items[3].content_type, "");
  11663. });
  11664. auto port = svr.bind_to_any_port("localhost");
  11665. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11666. auto se = detail::scope_exit([&] {
  11667. svr.stop();
  11668. t.join();
  11669. ASSERT_FALSE(svr.is_running());
  11670. });
  11671. svr.wait_until_ready();
  11672. {
  11673. SSLClient cli("localhost", port);
  11674. cli.enable_server_certificate_verification(false);
  11675. UploadFormDataItems items{
  11676. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11677. {"name2", "Testing456", "", ""}, // not a file
  11678. };
  11679. {
  11680. auto res = cli.Post("/post-none", {}, {}, {});
  11681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11682. ASSERT_EQ(StatusCode::OK_200, res->status);
  11683. }
  11684. FormDataProviderItems providers;
  11685. {
  11686. auto res =
  11687. cli.Post("/post-items", {}, items, providers); // empty providers
  11688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11689. ASSERT_EQ(StatusCode::OK_200, res->status);
  11690. }
  11691. providers.push_back({"name3",
  11692. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11693. // test the offset is given correctly at each step
  11694. if (!offset)
  11695. sink.os.write(rand1.data(), 30);
  11696. else if (offset == 30)
  11697. sink.os.write(rand1.data() + 30, 300);
  11698. else if (offset == 330)
  11699. sink.os.write(rand1.data() + 330, 670);
  11700. else if (offset == rand1.size())
  11701. sink.done();
  11702. return true;
  11703. },
  11704. "filename3",
  11705. {}});
  11706. providers.push_back({"name4",
  11707. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11708. // test the offset is given correctly at each step
  11709. if (!offset)
  11710. sink.os.write(rand2.data(), 2000);
  11711. else if (offset == 2000)
  11712. sink.os.write(rand2.data() + 2000, 1);
  11713. else if (offset == 2001)
  11714. sink.os.write(rand2.data() + 2001, 999);
  11715. else if (offset == rand2.size())
  11716. sink.done();
  11717. return true;
  11718. },
  11719. "filename4",
  11720. {}});
  11721. {
  11722. auto res = cli.Post("/post-providers", {}, {}, providers);
  11723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11724. ASSERT_EQ(StatusCode::OK_200, res->status);
  11725. }
  11726. {
  11727. auto res = cli.Post("/post-both", {}, items, providers);
  11728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11729. ASSERT_EQ(StatusCode::OK_200, res->status);
  11730. }
  11731. }
  11732. }
  11733. TEST(MultipartFormDataTest, BadHeader) {
  11734. Server svr;
  11735. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11736. res.set_content("ok", "text/plain");
  11737. });
  11738. thread t = thread([&] { svr.listen(HOST, PORT); });
  11739. auto se = detail::scope_exit([&] {
  11740. svr.stop();
  11741. t.join();
  11742. ASSERT_FALSE(svr.is_running());
  11743. });
  11744. svr.wait_until_ready();
  11745. const std::string body =
  11746. "This is the preamble. It is to be ignored, though it\r\n"
  11747. "is a handy place for composition agents to include an\r\n"
  11748. "explanatory note to non-MIME conformant readers.\r\n"
  11749. "\r\n"
  11750. "\r\n"
  11751. "--simple boundary\r\n"
  11752. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11753. ": BAD...\r\n"
  11754. "\r\n"
  11755. "value1\r\n"
  11756. "--simple boundary\r\n"
  11757. "Content-Disposition: form-data; name=\"field2\"; "
  11758. "filename=\"example.txt\"\r\n"
  11759. "\r\n"
  11760. "value2\r\n"
  11761. "--simple boundary--\r\n"
  11762. "This is the epilogue. It is also to be ignored.\r\n";
  11763. std::string content_type =
  11764. R"(multipart/form-data; boundary="simple boundary")";
  11765. Client cli(HOST, PORT);
  11766. auto res = cli.Post("/post", body, content_type.c_str());
  11767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11768. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11769. }
  11770. TEST(MultipartFormDataTest, WithPreamble) {
  11771. Server svr;
  11772. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11773. res.set_content("ok", "text/plain");
  11774. });
  11775. thread t = thread([&] { svr.listen(HOST, PORT); });
  11776. auto se = detail::scope_exit([&] {
  11777. svr.stop();
  11778. t.join();
  11779. ASSERT_FALSE(svr.is_running());
  11780. });
  11781. svr.wait_until_ready();
  11782. const std::string body =
  11783. "This is the preamble. It is to be ignored, though it\r\n"
  11784. "is a handy place for composition agents to include an\r\n"
  11785. "explanatory note to non-MIME conformant readers.\r\n"
  11786. "\r\n"
  11787. "\r\n"
  11788. "--simple boundary\r\n"
  11789. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11790. "\r\n"
  11791. "value1\r\n"
  11792. "--simple boundary\r\n"
  11793. "Content-Disposition: form-data; name=\"field2\"; "
  11794. "filename=\"example.txt\"\r\n"
  11795. "\r\n"
  11796. "value2\r\n"
  11797. "--simple boundary--\r\n"
  11798. "This is the epilogue. It is also to be ignored.\r\n";
  11799. std::string content_type =
  11800. R"(multipart/form-data; boundary="simple boundary")";
  11801. Client cli(HOST, PORT);
  11802. auto res = cli.Post("/post", body, content_type.c_str());
  11803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11804. EXPECT_EQ(StatusCode::OK_200, res->status);
  11805. }
  11806. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11807. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11808. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11809. const ContentReader &content_reader) {
  11810. if (req.is_multipart_form_data()) {
  11811. std::vector<FormData> items;
  11812. content_reader(
  11813. [&](const FormData &file) {
  11814. items.push_back(file);
  11815. return true;
  11816. },
  11817. [&](const char *data, size_t data_length) {
  11818. items.back().content.append(data, data_length);
  11819. return true;
  11820. });
  11821. EXPECT_TRUE(std::string(items[0].name) == "document");
  11822. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11823. EXPECT_TRUE(items[0].filename == "2MB_data");
  11824. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11825. EXPECT_TRUE(items[1].name == "hello");
  11826. EXPECT_TRUE(items[1].content == "world");
  11827. EXPECT_TRUE(items[1].filename == "");
  11828. EXPECT_TRUE(items[1].content_type == "");
  11829. } else {
  11830. std::string body;
  11831. content_reader([&](const char *data, size_t data_length) {
  11832. body.append(data, data_length);
  11833. return true;
  11834. });
  11835. }
  11836. });
  11837. auto port = svr.bind_to_any_port("localhost");
  11838. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11839. auto se = detail::scope_exit([&] {
  11840. svr.stop();
  11841. t.join();
  11842. ASSERT_FALSE(svr.is_running());
  11843. });
  11844. svr.wait_until_ready();
  11845. {
  11846. std::string data(1024 * 1024 * 2, '.');
  11847. std::stringstream buffer;
  11848. buffer << data;
  11849. SSLClient cli("localhost", port);
  11850. cli.enable_server_certificate_verification(false);
  11851. UploadFormDataItems items{
  11852. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11853. {"hello", "world", "", ""},
  11854. };
  11855. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11857. ASSERT_EQ(StatusCode::OK_200, res->status);
  11858. }
  11859. }
  11860. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11861. std::string data(1024 * 1024 * 2, '&');
  11862. std::stringstream buffer;
  11863. buffer << data;
  11864. Client cli("https://localhost:8080");
  11865. UploadFormDataItems items{
  11866. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11867. {"hello", "world", "", ""},
  11868. };
  11869. for (const char &c : " \t\r\n") {
  11870. auto res =
  11871. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11872. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11873. ASSERT_FALSE(res);
  11874. }
  11875. }
  11876. TEST(MultipartFormDataTest, PutFormData) {
  11877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11878. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11879. const ContentReader &content_reader) {
  11880. if (req.is_multipart_form_data()) {
  11881. std::vector<FormData> items;
  11882. content_reader(
  11883. [&](const FormData &file) {
  11884. items.push_back(file);
  11885. return true;
  11886. },
  11887. [&](const char *data, size_t data_length) {
  11888. items.back().content.append(data, data_length);
  11889. return true;
  11890. });
  11891. EXPECT_TRUE(std::string(items[0].name) == "document");
  11892. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11893. EXPECT_TRUE(items[0].filename == "2MB_data");
  11894. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11895. EXPECT_TRUE(items[1].name == "hello");
  11896. EXPECT_TRUE(items[1].content == "world");
  11897. EXPECT_TRUE(items[1].filename == "");
  11898. EXPECT_TRUE(items[1].content_type == "");
  11899. } else {
  11900. std::string body;
  11901. content_reader([&](const char *data, size_t data_length) {
  11902. body.append(data, data_length);
  11903. return true;
  11904. });
  11905. }
  11906. });
  11907. auto port = svr.bind_to_any_port("localhost");
  11908. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11909. auto se = detail::scope_exit([&] {
  11910. svr.stop();
  11911. t.join();
  11912. ASSERT_FALSE(svr.is_running());
  11913. });
  11914. svr.wait_until_ready();
  11915. {
  11916. std::string data(1024 * 1024 * 2, '&');
  11917. std::stringstream buffer;
  11918. buffer << data;
  11919. SSLClient cli("localhost", port);
  11920. cli.enable_server_certificate_verification(false);
  11921. UploadFormDataItems items{
  11922. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11923. {"hello", "world", "", ""},
  11924. };
  11925. auto res = cli.Put("/put", items);
  11926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11927. ASSERT_EQ(StatusCode::OK_200, res->status);
  11928. }
  11929. }
  11930. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11931. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11932. svr.Put("/put_customboundary",
  11933. [&](const Request &req, const Response & /*res*/,
  11934. const ContentReader &content_reader) {
  11935. if (req.is_multipart_form_data()) {
  11936. std::vector<FormData> items;
  11937. content_reader(
  11938. [&](const FormData &file) {
  11939. items.push_back(file);
  11940. return true;
  11941. },
  11942. [&](const char *data, size_t data_length) {
  11943. items.back().content.append(data, data_length);
  11944. return true;
  11945. });
  11946. EXPECT_TRUE(std::string(items[0].name) == "document");
  11947. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11948. EXPECT_TRUE(items[0].filename == "2MB_data");
  11949. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11950. EXPECT_TRUE(items[1].name == "hello");
  11951. EXPECT_TRUE(items[1].content == "world");
  11952. EXPECT_TRUE(items[1].filename == "");
  11953. EXPECT_TRUE(items[1].content_type == "");
  11954. } else {
  11955. std::string body;
  11956. content_reader([&](const char *data, size_t data_length) {
  11957. body.append(data, data_length);
  11958. return true;
  11959. });
  11960. }
  11961. });
  11962. auto port = svr.bind_to_any_port("localhost");
  11963. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11964. auto se = detail::scope_exit([&] {
  11965. svr.stop();
  11966. t.join();
  11967. ASSERT_FALSE(svr.is_running());
  11968. });
  11969. svr.wait_until_ready();
  11970. {
  11971. std::string data(1024 * 1024 * 2, '&');
  11972. std::stringstream buffer;
  11973. buffer << data;
  11974. SSLClient cli("localhost", port);
  11975. cli.enable_server_certificate_verification(false);
  11976. UploadFormDataItems items{
  11977. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11978. {"hello", "world", "", ""},
  11979. };
  11980. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11982. ASSERT_EQ(StatusCode::OK_200, res->status);
  11983. }
  11984. }
  11985. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11986. std::string data(1024 * 1024 * 2, '&');
  11987. std::stringstream buffer;
  11988. buffer << data;
  11989. Client cli("https://localhost:8080");
  11990. cli.enable_server_certificate_verification(false);
  11991. UploadFormDataItems items{
  11992. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11993. {"hello", "world", "", ""},
  11994. };
  11995. for (const char &c : " \t\r\n") {
  11996. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11997. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11998. ASSERT_FALSE(res);
  11999. }
  12000. }
  12001. TEST(MultipartFormDataTest, AlternateFilename) {
  12002. auto handled = false;
  12003. Server svr;
  12004. svr.Post("/test", [&](const Request &req, Response &res) {
  12005. ASSERT_EQ(2u, req.form.files.size());
  12006. ASSERT_EQ(1u, req.form.fields.size());
  12007. // Test files
  12008. const auto &file1 = req.form.get_file("file1");
  12009. ASSERT_EQ("file1", file1.name);
  12010. ASSERT_EQ("A.txt", file1.filename);
  12011. ASSERT_EQ("text/plain", file1.content_type);
  12012. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  12013. const auto &file2 = req.form.get_file("file2");
  12014. ASSERT_EQ("file2", file2.name);
  12015. ASSERT_EQ("a.html", file2.filename);
  12016. ASSERT_EQ("text/html", file2.content_type);
  12017. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12018. file2.content);
  12019. // Test text field
  12020. const auto &text = req.form.get_field("text");
  12021. ASSERT_EQ("text default", text);
  12022. res.set_content("ok", "text/plain");
  12023. handled = true;
  12024. });
  12025. thread t = thread([&] { svr.listen(HOST, PORT); });
  12026. auto se = detail::scope_exit([&] {
  12027. svr.stop();
  12028. t.join();
  12029. ASSERT_FALSE(svr.is_running());
  12030. ASSERT_TRUE(handled);
  12031. });
  12032. svr.wait_until_ready();
  12033. auto req = "POST /test HTTP/1.1\r\n"
  12034. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12035. "Content-Length: 399\r\n"
  12036. "\r\n"
  12037. "----------\r\n"
  12038. "Content-Disposition: form-data; name=\"text\"\r\n"
  12039. "\r\n"
  12040. "text default\r\n"
  12041. "----------\r\n"
  12042. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12043. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12044. "Content-Type: text/plain\r\n"
  12045. "\r\n"
  12046. "Content of a.txt.\r\n"
  12047. "\r\n"
  12048. "----------\r\n"
  12049. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12050. "\"a.html\"\r\n"
  12051. "Content-Type: text/html\r\n"
  12052. "\r\n"
  12053. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12054. "\r\n"
  12055. "------------\r\n";
  12056. ASSERT_TRUE(send_request(1, req));
  12057. }
  12058. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12059. auto handled = false;
  12060. Server svr;
  12061. svr.Post("/test", [&](const Request &req, Response &res) {
  12062. // Case-insensitive "utf-8''" prefix with a long value
  12063. const auto &file = req.form.get_file("file1");
  12064. ASSERT_EQ("file1", file.name);
  12065. // 8000 chars exercises both the Content-Disposition parser and the
  12066. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12067. // Prior to the fix, std::regex_match on this header would cause O(N)
  12068. // stack recursion in libstdc++, leading to SIGSEGV.
  12069. std::string expected_filename(8000, 'A');
  12070. ASSERT_EQ(expected_filename, file.filename);
  12071. res.set_content("ok", "text/plain");
  12072. handled = true;
  12073. });
  12074. thread t = thread([&] { svr.listen(HOST, PORT); });
  12075. auto se = detail::scope_exit([&] {
  12076. svr.stop();
  12077. t.join();
  12078. ASSERT_FALSE(svr.is_running());
  12079. ASSERT_TRUE(handled);
  12080. });
  12081. svr.wait_until_ready();
  12082. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12083. // Regression test for GHSA-qq6v-r583-3h69
  12084. std::string long_filename(8000, 'A');
  12085. std::string body = "----------\r\n"
  12086. "Content-Disposition: form-data; name=\"file1\"; "
  12087. "filename*=\"Utf-8''" +
  12088. long_filename +
  12089. "\"\r\n"
  12090. "\r\n"
  12091. "hello\r\n"
  12092. "------------\r\n";
  12093. auto req = "POST /test HTTP/1.1\r\n"
  12094. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12095. "Content-Length: " +
  12096. std::to_string(body.size()) + "\r\n\r\n" + body;
  12097. ASSERT_TRUE(send_request(1, req));
  12098. }
  12099. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12100. auto handled = false;
  12101. Server svr;
  12102. svr.Post("/test", [&](const Request &req, Response &) {
  12103. ASSERT_EQ(2u, req.form.fields.size());
  12104. const auto &text1 = req.form.get_field("text1");
  12105. ASSERT_EQ("text1", text1);
  12106. const auto &text2 = req.form.get_field("text2");
  12107. ASSERT_EQ("text2", text2);
  12108. handled = true;
  12109. });
  12110. thread t = thread([&] { svr.listen(HOST, PORT); });
  12111. auto se = detail::scope_exit([&] {
  12112. svr.stop();
  12113. t.join();
  12114. ASSERT_FALSE(svr.is_running());
  12115. ASSERT_TRUE(handled);
  12116. });
  12117. svr.wait_until_ready();
  12118. auto req = "POST /test HTTP/1.1\r\n"
  12119. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12120. "Content-Length: 146\r\n"
  12121. "\r\n----------\r\n"
  12122. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12123. "\r\n"
  12124. "text1"
  12125. "\r\n----------\r\n"
  12126. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12127. "\r\n"
  12128. "text2"
  12129. "\r\n------------";
  12130. std::string response;
  12131. ASSERT_TRUE(send_request(1, req, &response));
  12132. ASSERT_EQ("200", response.substr(9, 3));
  12133. }
  12134. TEST(MultipartFormDataTest, ContentLength) {
  12135. auto handled = false;
  12136. Server svr;
  12137. svr.Post("/test", [&](const Request &req, Response &) {
  12138. ASSERT_EQ(2u, req.form.fields.size());
  12139. const auto &text1 = req.form.get_field("text1");
  12140. ASSERT_EQ("text1", text1);
  12141. const auto &text2 = req.form.get_field("text2");
  12142. ASSERT_EQ("text2", text2);
  12143. handled = true;
  12144. });
  12145. thread t = thread([&] { svr.listen(HOST, PORT); });
  12146. auto se = detail::scope_exit([&] {
  12147. svr.stop();
  12148. t.join();
  12149. ASSERT_FALSE(svr.is_running());
  12150. ASSERT_TRUE(handled);
  12151. });
  12152. svr.wait_until_ready();
  12153. auto req = "POST /test HTTP/1.1\r\n"
  12154. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12155. "Content-Length: 167\r\n"
  12156. "\r\n----------\r\n"
  12157. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12158. "Content-Length: 5\r\n"
  12159. "\r\n"
  12160. "text1"
  12161. "\r\n----------\r\n"
  12162. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12163. "\r\n"
  12164. "text2"
  12165. "\r\n------------\r\n";
  12166. std::string response;
  12167. ASSERT_TRUE(send_request(1, req, &response));
  12168. ASSERT_EQ("200", response.substr(9, 3));
  12169. }
  12170. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12171. auto handled = false;
  12172. Server svr;
  12173. svr.Post("/test", [&](const Request &req, Response &) {
  12174. ASSERT_EQ(2u, req.form.fields.size());
  12175. const auto &text1 = req.form.get_field("text1");
  12176. ASSERT_EQ("text1", text1);
  12177. // TODO: Add header access for text fields if needed
  12178. const auto &text2 = req.form.get_field("text2");
  12179. ASSERT_EQ("text2", text2);
  12180. // TODO: Header access for text fields needs to be implemented
  12181. // auto &headers = it->second.headers;
  12182. // ASSERT_EQ(3U, headers.size());
  12183. // auto custom_header = headers.find("x-whatever");
  12184. // ASSERT_TRUE(custom_header != headers.end());
  12185. // ASSERT_NE("customvalue", custom_header->second);
  12186. // ASSERT_EQ("CustomValue", custom_header->second);
  12187. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12188. handled = true;
  12189. });
  12190. thread t = thread([&] { svr.listen(HOST, PORT); });
  12191. auto se = detail::scope_exit([&] {
  12192. svr.stop();
  12193. t.join();
  12194. ASSERT_FALSE(svr.is_running());
  12195. ASSERT_TRUE(handled);
  12196. });
  12197. svr.wait_until_ready();
  12198. auto req = "POST /test HTTP/1.1\r\n"
  12199. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12200. "Content-Length: 232\r\n"
  12201. "\r\n----------\r\n"
  12202. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12203. "Content-Length: 5\r\n"
  12204. "X-Test: 1\r\n"
  12205. "\r\n"
  12206. "text1"
  12207. "\r\n----------\r\n"
  12208. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12209. "Content-Type: text/plain\r\n"
  12210. "X-Whatever: CustomValue\r\n"
  12211. "\r\n"
  12212. "text2"
  12213. "\r\n------------\r\n"
  12214. "That should be disregarded. Not even read";
  12215. std::string response;
  12216. ASSERT_TRUE(send_request(1, req, &response));
  12217. ASSERT_EQ("200", response.substr(9, 3));
  12218. }
  12219. TEST(MultipartFormDataTest, LargeHeader) {
  12220. auto handled = false;
  12221. Server svr;
  12222. svr.Post("/test", [&](const Request &req, Response &) {
  12223. ASSERT_EQ(1u, req.form.fields.size());
  12224. const auto &text = req.form.get_field("name1");
  12225. ASSERT_EQ("text1", text);
  12226. handled = true;
  12227. });
  12228. thread t = thread([&] { svr.listen(HOST, PORT); });
  12229. auto se = detail::scope_exit([&] {
  12230. svr.stop();
  12231. t.join();
  12232. ASSERT_FALSE(svr.is_running());
  12233. ASSERT_TRUE(handled);
  12234. });
  12235. svr.wait_until_ready();
  12236. auto boundary = std::string("cpp-httplib-multipart-data");
  12237. std::string content = "--" + boundary +
  12238. "\r\n"
  12239. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12240. "\r\n"
  12241. "text1\r\n"
  12242. "--" +
  12243. boundary + "--\r\n";
  12244. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12245. "Content-Type: multipart/form-data;boundary=" +
  12246. boundary +
  12247. "\r\n"
  12248. "Content-Length: " +
  12249. std::to_string(content.size()) +
  12250. "\r\n"
  12251. "Dummy-Header: ";
  12252. std::string header_suffix = "\r\n"
  12253. "\r\n";
  12254. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12255. size_t header_dummy_size =
  12256. read_buff_size -
  12257. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12258. auto header_dummy = std::string(header_dummy_size, '@');
  12259. auto req = header_prefix + header_dummy + header_suffix + content;
  12260. std::string response;
  12261. ASSERT_TRUE(send_request(1, req, &response));
  12262. ASSERT_EQ("200", response.substr(9, 3));
  12263. }
  12264. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12265. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12266. // (not chunked Transfer-Encoding) after the streaming refactor.
  12267. auto handled = false;
  12268. Server svr;
  12269. svr.Post("/upload", [&](const Request &req, Response &res) {
  12270. auto cl_it = req.headers.find("Content-Length");
  12271. EXPECT_TRUE(cl_it != req.headers.end());
  12272. auto te_it = req.headers.find("Transfer-Encoding");
  12273. EXPECT_TRUE(te_it == req.headers.end());
  12274. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12275. res.set_content("ok", "text/plain");
  12276. handled = true;
  12277. });
  12278. auto port = svr.bind_to_any_port(HOST);
  12279. auto t = thread([&] { svr.listen_after_bind(); });
  12280. auto se = detail::scope_exit([&] {
  12281. svr.stop();
  12282. t.join();
  12283. ASSERT_FALSE(svr.is_running());
  12284. ASSERT_TRUE(handled);
  12285. });
  12286. svr.wait_until_ready();
  12287. UploadFormDataItems items = {
  12288. {"field1", "hello", "", "text/plain"},
  12289. {"file1", "world", "test.txt", "application/octet-stream"},
  12290. };
  12291. Client cli(HOST, port);
  12292. auto res = cli.Post("/upload", {}, items);
  12293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12294. EXPECT_EQ(StatusCode::OK_200, res->status);
  12295. }
  12296. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12297. // Verify that make_multipart_content_provider coalesces many small segments
  12298. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12299. constexpr size_t kItemCount = 1000;
  12300. UploadFormDataItems items;
  12301. items.reserve(kItemCount);
  12302. for (size_t i = 0; i < kItemCount; i++) {
  12303. items.push_back(
  12304. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12305. }
  12306. const std::string boundary = "----test-boundary";
  12307. auto content_length = detail::get_multipart_content_length(items, boundary);
  12308. auto provider = detail::make_multipart_content_provider(items, boundary);
  12309. // Drive the provider the same way write_content_with_progress does
  12310. size_t write_count = 0;
  12311. size_t total_bytes = 0;
  12312. DataSink sink;
  12313. size_t offset = 0;
  12314. sink.write = [&](const char *d, size_t l) -> bool {
  12315. (void)d;
  12316. write_count++;
  12317. total_bytes += l;
  12318. offset += l;
  12319. return true;
  12320. };
  12321. sink.is_writable = []() -> bool { return true; };
  12322. while (offset < content_length) {
  12323. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12324. }
  12325. EXPECT_EQ(content_length, total_bytes);
  12326. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12327. // With buffering into 64KB blocks, write_count should be much smaller.
  12328. auto segment_count = 3 * kItemCount + 1;
  12329. EXPECT_LT(write_count, segment_count / 10);
  12330. }
  12331. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12332. // Integration test: send many UploadFormDataItems and verify the server
  12333. // receives all of them correctly (#2410).
  12334. constexpr size_t kItemCount = 500;
  12335. auto handled = false;
  12336. Server svr;
  12337. svr.Post("/upload", [&](const Request &req, Response &res) {
  12338. EXPECT_EQ(kItemCount, req.form.fields.size());
  12339. for (size_t i = 0; i < kItemCount; i++) {
  12340. auto key = "field" + std::to_string(i);
  12341. auto val = "value" + std::to_string(i);
  12342. auto it = req.form.fields.find(key);
  12343. if (it != req.form.fields.end()) {
  12344. EXPECT_EQ(val, it->second.content);
  12345. } else {
  12346. ADD_FAILURE() << "Missing field: " << key;
  12347. }
  12348. }
  12349. res.set_content("ok", "text/plain");
  12350. handled = true;
  12351. });
  12352. auto port = svr.bind_to_any_port(HOST);
  12353. auto t = thread([&] { svr.listen_after_bind(); });
  12354. auto se = detail::scope_exit([&] {
  12355. svr.stop();
  12356. t.join();
  12357. ASSERT_FALSE(svr.is_running());
  12358. ASSERT_TRUE(handled);
  12359. });
  12360. svr.wait_until_ready();
  12361. UploadFormDataItems items;
  12362. items.reserve(kItemCount);
  12363. for (size_t i = 0; i < kItemCount; i++) {
  12364. items.push_back(
  12365. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12366. }
  12367. Client cli(HOST, port);
  12368. auto res = cli.Post("/upload", items);
  12369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12370. EXPECT_EQ(StatusCode::OK_200, res->status);
  12371. }
  12372. TEST(MultipartFormDataTest, MakeFileProvider) {
  12373. // Verify make_file_provider sends a file's contents correctly.
  12374. const std::string file_content(4096, 'Z');
  12375. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12376. {
  12377. std::ofstream ofs(tmp_path, std::ios::binary);
  12378. ofs.write(file_content.data(),
  12379. static_cast<std::streamsize>(file_content.size()));
  12380. }
  12381. auto handled = false;
  12382. Server svr;
  12383. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12384. const ContentReader &content_reader) {
  12385. ASSERT_TRUE(req.is_multipart_form_data());
  12386. std::vector<FormData> items;
  12387. content_reader(
  12388. [&](const FormData &file) {
  12389. items.push_back(file);
  12390. return true;
  12391. },
  12392. [&](const char *data, size_t data_length) {
  12393. items.back().content.append(data, data_length);
  12394. return true;
  12395. });
  12396. ASSERT_EQ(1u, items.size());
  12397. EXPECT_EQ("myfile", items[0].name);
  12398. EXPECT_EQ("data.bin", items[0].filename);
  12399. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12400. EXPECT_EQ(file_content, items[0].content);
  12401. handled = true;
  12402. });
  12403. auto port = svr.bind_to_any_port(HOST);
  12404. auto t = thread([&] { svr.listen_after_bind(); });
  12405. auto se = detail::scope_exit([&] {
  12406. svr.stop();
  12407. t.join();
  12408. ASSERT_FALSE(svr.is_running());
  12409. ASSERT_TRUE(handled);
  12410. std::remove(tmp_path.c_str());
  12411. });
  12412. svr.wait_until_ready();
  12413. FormDataProviderItems providers;
  12414. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12415. "application/octet-stream"));
  12416. Client cli(HOST, port);
  12417. auto res = cli.Post("/upload", {}, {}, providers);
  12418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12419. EXPECT_EQ(StatusCode::OK_200, res->status);
  12420. }
  12421. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12422. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12423. // (100) headers is rejected with a 400 Bad Request response.
  12424. Server svr;
  12425. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12426. res.set_content("ok", "text/plain");
  12427. });
  12428. thread t = thread([&] { svr.listen(HOST, PORT); });
  12429. auto se = detail::scope_exit([&] {
  12430. svr.stop();
  12431. t.join();
  12432. ASSERT_FALSE(svr.is_running());
  12433. });
  12434. svr.wait_until_ready();
  12435. // Build a multipart part with 101 custom headers (exceeding
  12436. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12437. std::stringstream body;
  12438. body << "--simpleboundary\r\n"
  12439. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12440. for (int i = 0; i < 101; i++) {
  12441. body << "X-Custom-Header-" << i << ": value\r\n";
  12442. }
  12443. body << "\r\n"
  12444. << "value1\r\n"
  12445. << "--simpleboundary--\r\n";
  12446. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12447. Client cli(HOST, PORT);
  12448. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12450. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12451. }
  12452. TEST(MakeFileBodyTest, Basic) {
  12453. const std::string file_content(4096, 'Z');
  12454. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12455. {
  12456. std::ofstream ofs(tmp_path, std::ios::binary);
  12457. ofs.write(file_content.data(),
  12458. static_cast<std::streamsize>(file_content.size()));
  12459. }
  12460. auto handled = false;
  12461. Server svr;
  12462. svr.Post("/upload", [&](const Request &req, Response &res) {
  12463. EXPECT_EQ(file_content, req.body);
  12464. handled = true;
  12465. res.status = StatusCode::OK_200;
  12466. });
  12467. auto port = svr.bind_to_any_port(HOST);
  12468. auto t = thread([&] { svr.listen_after_bind(); });
  12469. auto se = detail::scope_exit([&] {
  12470. svr.stop();
  12471. t.join();
  12472. ASSERT_FALSE(svr.is_running());
  12473. ASSERT_TRUE(handled);
  12474. std::remove(tmp_path.c_str());
  12475. });
  12476. svr.wait_until_ready();
  12477. auto fb = make_file_body(tmp_path);
  12478. ASSERT_GT(fb.first, 0u);
  12479. Client cli(HOST, port);
  12480. auto res =
  12481. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12483. EXPECT_EQ(StatusCode::OK_200, res->status);
  12484. }
  12485. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12486. static constexpr unsigned int number_of_tasks{1000000};
  12487. std::atomic_uint count{0};
  12488. std::unique_ptr<TaskQueue> task_queue{
  12489. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12490. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12491. auto queued = task_queue->enqueue(
  12492. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12493. EXPECT_TRUE(queued);
  12494. }
  12495. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12496. task_queue->shutdown();
  12497. #else
  12498. EXPECT_NO_THROW(task_queue->shutdown());
  12499. #endif
  12500. EXPECT_EQ(number_of_tasks, count.load());
  12501. }
  12502. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12503. static constexpr unsigned int number_of_tasks{1000000};
  12504. static constexpr unsigned int qlimit{2};
  12505. unsigned int queued_count{0};
  12506. std::atomic_uint count{0};
  12507. std::unique_ptr<TaskQueue> task_queue{
  12508. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12509. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12510. if (task_queue->enqueue(
  12511. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12512. queued_count++;
  12513. }
  12514. }
  12515. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12516. task_queue->shutdown();
  12517. #else
  12518. EXPECT_NO_THROW(task_queue->shutdown());
  12519. #endif
  12520. EXPECT_EQ(queued_count, count.load());
  12521. EXPECT_TRUE(queued_count <= number_of_tasks);
  12522. EXPECT_TRUE(queued_count >= qlimit);
  12523. }
  12524. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12525. // Use a short idle timeout so a dynamic thread spawns, times out and
  12526. // exits during the test, and the pool keeps working afterwards.
  12527. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12528. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12529. /*idle_timeout_sec=*/1}};
  12530. std::atomic_uint count{0};
  12531. std::condition_variable cv;
  12532. std::mutex mtx;
  12533. bool release = false;
  12534. // Block the base thread so the second task spawns a dynamic thread.
  12535. EXPECT_TRUE(task_queue->enqueue([&] {
  12536. std::unique_lock<std::mutex> lock(mtx);
  12537. while (!release) {
  12538. cv.wait(lock);
  12539. }
  12540. count++;
  12541. }));
  12542. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12543. // Let the dynamic thread finish its task and exceed the idle timeout.
  12544. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12545. {
  12546. std::unique_lock<std::mutex> lock(mtx);
  12547. release = true;
  12548. }
  12549. cv.notify_all();
  12550. // The pool must still accept and run tasks after the dynamic thread exited.
  12551. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12552. task_queue->shutdown();
  12553. EXPECT_EQ(3u, count.load());
  12554. }
  12555. TEST(TaskQueueTest, MaxQueuedRequests) {
  12556. static constexpr unsigned int qlimit{3};
  12557. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12558. std::condition_variable sem_cv;
  12559. std::mutex sem_mtx;
  12560. int credits = 0;
  12561. bool queued;
  12562. /* Fill up the queue with tasks that will block until we give them credits to
  12563. * complete. */
  12564. for (unsigned int n = 0; n <= qlimit;) {
  12565. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12566. std::unique_lock<std::mutex> lock(sem_mtx);
  12567. while (credits <= 0) {
  12568. sem_cv.wait(lock);
  12569. }
  12570. /* Consume the credit and signal the test code if they are all gone. */
  12571. if (--credits == 0) { sem_cv.notify_one(); }
  12572. });
  12573. if (n < qlimit) {
  12574. /* The first qlimit enqueues must succeed. */
  12575. EXPECT_TRUE(queued);
  12576. } else {
  12577. /* The last one will succeed only when the worker thread
  12578. * starts and dequeues the first blocking task. Although
  12579. * not necessary for the correctness of this test, we sleep for
  12580. * a short while to avoid busy waiting. */
  12581. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12582. }
  12583. if (queued) { n++; }
  12584. }
  12585. /* Further enqueues must fail since the queue is full. */
  12586. for (auto i = 0; i < 4; i++) {
  12587. queued = task_queue->enqueue([] {});
  12588. EXPECT_FALSE(queued);
  12589. }
  12590. /* Give the credits to allow the previous tasks to complete. */
  12591. {
  12592. std::unique_lock<std::mutex> lock(sem_mtx);
  12593. credits += qlimit + 1;
  12594. }
  12595. sem_cv.notify_all();
  12596. /* Wait for all the credits to be consumed. */
  12597. {
  12598. std::unique_lock<std::mutex> lock(sem_mtx);
  12599. while (credits > 0) {
  12600. sem_cv.wait(lock);
  12601. }
  12602. }
  12603. /* Check that we are able again to enqueue at least qlimit tasks. */
  12604. for (unsigned int i = 0; i < qlimit; i++) {
  12605. queued = task_queue->enqueue([] {});
  12606. EXPECT_TRUE(queued);
  12607. }
  12608. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12609. task_queue->shutdown();
  12610. #else
  12611. EXPECT_NO_THROW(task_queue->shutdown());
  12612. #endif
  12613. }
  12614. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12615. Server svr;
  12616. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12617. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12618. });
  12619. svr.Get("/hello", [](const Request &req, Response &res) {
  12620. res.set_content(req.get_param_value("key"), "text/plain");
  12621. });
  12622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12623. auto se = detail::scope_exit([&] {
  12624. svr.stop();
  12625. thread.join();
  12626. ASSERT_FALSE(svr.is_running());
  12627. });
  12628. svr.wait_until_ready();
  12629. {
  12630. Client cli(HOST, PORT);
  12631. cli.set_follow_location(true);
  12632. auto res = cli.Get("/");
  12633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12634. EXPECT_EQ(StatusCode::OK_200, res->status);
  12635. EXPECT_EQ("val&key2=val2", res->body);
  12636. }
  12637. }
  12638. #endif
  12639. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12640. Server svr;
  12641. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12642. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12643. });
  12644. svr.Get("/hello", [](const Request &req, Response &res) {
  12645. res.set_content(req.get_param_value("key"), "text/plain");
  12646. });
  12647. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12648. auto se = detail::scope_exit([&] {
  12649. svr.stop();
  12650. thread.join();
  12651. ASSERT_FALSE(svr.is_running());
  12652. });
  12653. svr.wait_until_ready();
  12654. {
  12655. Client cli(HOST, PORT);
  12656. cli.set_follow_location(true);
  12657. auto res = cli.Get("/");
  12658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12659. EXPECT_EQ(StatusCode::OK_200, res->status);
  12660. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12661. }
  12662. }
  12663. TEST(RedirectTest, RedirectWithPlusInPath) {
  12664. Server svr;
  12665. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12666. res.set_redirect("/a+b");
  12667. });
  12668. // Route pattern uses regex; escape + as \\+
  12669. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12670. res.set_content(req.path, "text/plain");
  12671. });
  12672. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12673. auto se = detail::scope_exit([&] {
  12674. svr.stop();
  12675. thread.join();
  12676. ASSERT_FALSE(svr.is_running());
  12677. });
  12678. svr.wait_until_ready();
  12679. {
  12680. Client cli(HOST, PORT);
  12681. cli.set_follow_location(true);
  12682. auto res = cli.Get("/");
  12683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12684. EXPECT_EQ(StatusCode::OK_200, res->status);
  12685. EXPECT_EQ("/a+b", res->body);
  12686. }
  12687. }
  12688. #ifdef CPPHTTPLIB_SSL_ENABLED
  12689. TEST(RedirectTest, Issue2185_Online) {
  12690. SSLClient client("github.com");
  12691. client.set_follow_location(true);
  12692. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12693. "Coollab-Windows.zip");
  12694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12695. EXPECT_EQ(StatusCode::OK_200, res->status);
  12696. EXPECT_EQ(9920427U, res->body.size());
  12697. }
  12698. #endif
  12699. TEST(VulnerabilityTest, CRLFInjection) {
  12700. Server svr;
  12701. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12702. res.set_content("Hello 1", "text/plain");
  12703. });
  12704. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12705. res.set_content("Hello 2", "text/plain");
  12706. });
  12707. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12708. res.set_content("Hello 3", "text/plain");
  12709. });
  12710. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12711. res.set_content("Hello 4", "text/plain");
  12712. });
  12713. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12714. for (const auto &x : req.headers) {
  12715. auto key = x.first;
  12716. EXPECT_STRNE("evil", key.c_str());
  12717. }
  12718. });
  12719. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12720. auto se = detail::scope_exit([&] {
  12721. svr.stop();
  12722. thread.join();
  12723. ASSERT_FALSE(svr.is_running());
  12724. });
  12725. svr.wait_until_ready();
  12726. {
  12727. Client cli(HOST, PORT);
  12728. cli.Post("/test1", "A=B",
  12729. "application/x-www-form-urlencoded\r\nevil: hello1");
  12730. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12731. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12732. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12733. }
  12734. }
  12735. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12736. auto server_thread = std::thread([] {
  12737. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12738. default_socket_options(srv);
  12739. sockaddr_in addr{};
  12740. addr.sin_family = AF_INET;
  12741. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12742. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12743. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12744. ::listen(srv, 1);
  12745. sockaddr_in cli_addr{};
  12746. socklen_t cli_len = sizeof(cli_addr);
  12747. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12748. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12749. std::string buf_all;
  12750. char buf[2048];
  12751. ssize_t n;
  12752. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12753. buf_all.append(buf, static_cast<size_t>(n));
  12754. size_t pos;
  12755. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12756. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12757. auto e = request_block.find("\r\n");
  12758. if (e != std::string::npos) {
  12759. auto request_line = request_block.substr(0, e);
  12760. std::string msg =
  12761. "CRLF injection detected in request line: '" + request_line + "'";
  12762. EXPECT_FALSE(true) << msg;
  12763. }
  12764. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12765. ::send(cli,
  12766. #ifdef _WIN32
  12767. static_cast<const char *>(resp.c_str()),
  12768. static_cast<int>(resp.size()),
  12769. #else
  12770. resp.c_str(), resp.size(),
  12771. #endif
  12772. 0);
  12773. buf_all.erase(0, pos + 4);
  12774. }
  12775. }
  12776. detail::close_socket(cli);
  12777. detail::close_socket(srv);
  12778. });
  12779. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12780. auto cli = Client("127.0.0.1", PORT + 1);
  12781. auto headers = Headers{
  12782. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12783. {"Connection", "keep-alive"}};
  12784. auto res = cli.Get("/hi", headers);
  12785. EXPECT_FALSE(res);
  12786. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12787. server_thread.join();
  12788. }
  12789. TEST(PathParamsTest, StaticMatch) {
  12790. const auto pattern = "/users/all";
  12791. detail::PathParamsMatcher matcher(pattern);
  12792. Request request;
  12793. request.path = "/users/all";
  12794. ASSERT_TRUE(matcher.match(request));
  12795. std::unordered_map<std::string, std::string> expected_params = {};
  12796. EXPECT_EQ(request.path_params, expected_params);
  12797. }
  12798. TEST(PathParamsTest, StaticMismatch) {
  12799. const auto pattern = "/users/all";
  12800. detail::PathParamsMatcher matcher(pattern);
  12801. Request request;
  12802. request.path = "/users/1";
  12803. ASSERT_FALSE(matcher.match(request));
  12804. }
  12805. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12806. const auto pattern = "/users/:id/subscriptions";
  12807. detail::PathParamsMatcher matcher(pattern);
  12808. Request request;
  12809. request.path = "/users/42/subscriptions";
  12810. ASSERT_TRUE(matcher.match(request));
  12811. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12812. EXPECT_EQ(request.path_params, expected_params);
  12813. }
  12814. TEST(PathParamsTest, SingleParamInTheEnd) {
  12815. const auto pattern = "/users/:id";
  12816. detail::PathParamsMatcher matcher(pattern);
  12817. Request request;
  12818. request.path = "/users/24";
  12819. ASSERT_TRUE(matcher.match(request));
  12820. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12821. EXPECT_EQ(request.path_params, expected_params);
  12822. }
  12823. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12824. const auto pattern = "/users/:id/";
  12825. detail::PathParamsMatcher matcher(pattern);
  12826. Request request;
  12827. request.path = "/users/42/";
  12828. ASSERT_TRUE(matcher.match(request));
  12829. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12830. EXPECT_EQ(request.path_params, expected_params);
  12831. }
  12832. TEST(PathParamsTest, EmptyParam) {
  12833. const auto pattern = "/users/:id/";
  12834. detail::PathParamsMatcher matcher(pattern);
  12835. Request request;
  12836. request.path = "/users//";
  12837. ASSERT_TRUE(matcher.match(request));
  12838. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12839. EXPECT_EQ(request.path_params, expected_params);
  12840. }
  12841. TEST(PathParamsTest, FragmentMismatch) {
  12842. const auto pattern = "/users/:id/";
  12843. detail::PathParamsMatcher matcher(pattern);
  12844. Request request;
  12845. request.path = "/admins/24/";
  12846. ASSERT_FALSE(matcher.match(request));
  12847. }
  12848. TEST(PathParamsTest, ExtraFragments) {
  12849. const auto pattern = "/users/:id";
  12850. detail::PathParamsMatcher matcher(pattern);
  12851. Request request;
  12852. request.path = "/users/42/subscriptions";
  12853. ASSERT_FALSE(matcher.match(request));
  12854. }
  12855. TEST(PathParamsTest, MissingTrailingParam) {
  12856. const auto pattern = "/users/:id";
  12857. detail::PathParamsMatcher matcher(pattern);
  12858. Request request;
  12859. request.path = "/users";
  12860. ASSERT_FALSE(matcher.match(request));
  12861. }
  12862. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12863. const auto pattern = "/users/:id/subscriptions";
  12864. detail::PathParamsMatcher matcher(pattern);
  12865. Request request;
  12866. request.path = "/users/subscriptions";
  12867. ASSERT_FALSE(matcher.match(request));
  12868. }
  12869. TEST(PathParamsTest, MultipleParams) {
  12870. const auto pattern = "/users/:userid/subscriptions/:subid";
  12871. detail::PathParamsMatcher matcher(pattern);
  12872. Request request;
  12873. request.path = "/users/42/subscriptions/2";
  12874. ASSERT_TRUE(matcher.match(request));
  12875. std::unordered_map<std::string, std::string> expected_params = {
  12876. {"userid", "42"}, {"subid", "2"}};
  12877. EXPECT_EQ(request.path_params, expected_params);
  12878. }
  12879. TEST(PathParamsTest, SequenceOfParams) {
  12880. const auto pattern = "/values/:x/:y/:z";
  12881. detail::PathParamsMatcher matcher(pattern);
  12882. Request request;
  12883. request.path = "/values/1/2/3";
  12884. ASSERT_TRUE(matcher.match(request));
  12885. std::unordered_map<std::string, std::string> expected_params = {
  12886. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12887. EXPECT_EQ(request.path_params, expected_params);
  12888. }
  12889. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12890. const auto pattern = "/prefix:suffix";
  12891. detail::PathParamsMatcher matcher(pattern);
  12892. Request request;
  12893. request.path = "/prefix:suffix";
  12894. ASSERT_TRUE(matcher.match(request));
  12895. const std::unordered_map<std::string, std::string> expected_params = {};
  12896. EXPECT_EQ(request.path_params, expected_params);
  12897. }
  12898. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  12899. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  12900. // calling thread's stack on a long enough path for a quantified pattern;
  12901. // RegexMatcher must refuse to run regex matching on paths beyond
  12902. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  12903. detail::RegexMatcher matcher("/files/(.*)");
  12904. Request within_limit;
  12905. within_limit.path = "/files/" + std::string(10, 'A');
  12906. EXPECT_TRUE(matcher.match(within_limit));
  12907. Request over_limit;
  12908. over_limit.path =
  12909. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  12910. EXPECT_FALSE(matcher.match(over_limit));
  12911. }
  12912. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  12913. Server svr;
  12914. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  12915. res.set_content("ok", "text/plain");
  12916. });
  12917. auto port = svr.bind_to_any_port(HOST);
  12918. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12919. auto se = detail::scope_exit([&] {
  12920. svr.stop();
  12921. thread.join();
  12922. ASSERT_FALSE(svr.is_running());
  12923. });
  12924. svr.wait_until_ready();
  12925. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  12926. // request URI limit; this used to be able to crash the process.
  12927. std::string path =
  12928. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  12929. std::string req = "GET " + path +
  12930. " HTTP/1.1\r\n"
  12931. "Host: " +
  12932. std::string(HOST) + ":" + std::to_string(port) +
  12933. "\r\n"
  12934. "Connection: close\r\n"
  12935. "\r\n";
  12936. std::string response;
  12937. ASSERT_TRUE(send_request(5, req, &response, port));
  12938. EXPECT_NE(std::string::npos, response.find("404"));
  12939. }
  12940. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  12941. Server svr;
  12942. auto handler = [](const Request & /*req*/, Response &res) {
  12943. res.set_content("hit", "text/plain");
  12944. };
  12945. // No regex metacharacter, so this one is compared literally
  12946. svr.Get("/literal/route", handler);
  12947. // '.' is a regex metacharacter, so this one must keep regex semantics
  12948. svr.Get("/a.c", handler);
  12949. auto port = svr.bind_to_any_port(HOST);
  12950. std::thread t([&]() { svr.listen_after_bind(); });
  12951. auto se = detail::scope_exit([&] {
  12952. svr.stop();
  12953. t.join();
  12954. ASSERT_FALSE(svr.is_running());
  12955. });
  12956. svr.wait_until_ready();
  12957. Client cli(HOST, port);
  12958. struct {
  12959. const char *path;
  12960. int status;
  12961. } cases[] = {
  12962. {"/literal/route", StatusCode::OK_200},
  12963. {"/literal/routes", StatusCode::NotFound_404},
  12964. {"/literal/rout", StatusCode::NotFound_404},
  12965. {"/abc", StatusCode::OK_200},
  12966. {"/a.c", StatusCode::OK_200},
  12967. };
  12968. for (const auto &x : cases) {
  12969. auto res = cli.Get(x.path);
  12970. ASSERT_TRUE(res) << x.path;
  12971. EXPECT_EQ(x.status, res->status) << x.path;
  12972. }
  12973. }
  12974. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  12975. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  12976. // from exhausting the stack, so it must only constrain routes that actually
  12977. // run a regular expression. A literal route is matched by comparison and
  12978. // stays usable at any length.
  12979. Server svr;
  12980. const std::string pattern =
  12981. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  12982. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  12983. res.set_content("hit", "text/plain");
  12984. });
  12985. auto port = svr.bind_to_any_port(HOST);
  12986. std::thread t([&]() { svr.listen_after_bind(); });
  12987. auto se = detail::scope_exit([&] {
  12988. svr.stop();
  12989. t.join();
  12990. ASSERT_FALSE(svr.is_running());
  12991. });
  12992. svr.wait_until_ready();
  12993. Client cli(HOST, port);
  12994. auto res = cli.Get(pattern);
  12995. ASSERT_TRUE(res);
  12996. EXPECT_EQ(StatusCode::OK_200, res->status);
  12997. }
  12998. TEST(ParseUrlTest, VariousPatterns) {
  12999. {
  13000. detail::UrlComponents uc;
  13001. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  13002. EXPECT_EQ("http", uc.scheme);
  13003. EXPECT_EQ("example.com", uc.host);
  13004. EXPECT_EQ("8080", uc.port);
  13005. EXPECT_EQ("/path", uc.path);
  13006. EXPECT_EQ("?q=1", uc.query);
  13007. }
  13008. {
  13009. detail::UrlComponents uc;
  13010. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  13011. EXPECT_EQ("https", uc.scheme);
  13012. EXPECT_EQ("example.com", uc.host);
  13013. EXPECT_TRUE(uc.port.empty());
  13014. EXPECT_EQ("/path", uc.path);
  13015. }
  13016. {
  13017. detail::UrlComponents uc;
  13018. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13019. EXPECT_EQ("::1", uc.host);
  13020. EXPECT_EQ("8080", uc.port);
  13021. EXPECT_EQ("/path", uc.path);
  13022. }
  13023. {
  13024. detail::UrlComponents uc;
  13025. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13026. }
  13027. {
  13028. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13029. // the path while the connection still targets the bracketed host.
  13030. detail::UrlComponents uc;
  13031. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13032. }
  13033. {
  13034. detail::UrlComponents uc;
  13035. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13036. }
  13037. {
  13038. detail::UrlComponents uc;
  13039. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13040. EXPECT_EQ("::1", uc.host);
  13041. EXPECT_TRUE(uc.port.empty());
  13042. EXPECT_EQ("/path", uc.path);
  13043. }
  13044. {
  13045. detail::UrlComponents uc;
  13046. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13047. EXPECT_TRUE(uc.scheme.empty());
  13048. EXPECT_EQ("example.com", uc.host);
  13049. EXPECT_EQ("/path", uc.path);
  13050. EXPECT_EQ("?q=1", uc.query);
  13051. }
  13052. {
  13053. detail::UrlComponents uc;
  13054. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13055. EXPECT_TRUE(uc.host.empty());
  13056. EXPECT_EQ("/path", uc.path);
  13057. EXPECT_EQ("?q=1", uc.query);
  13058. }
  13059. {
  13060. detail::UrlComponents uc;
  13061. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13062. EXPECT_EQ("example.com", uc.host);
  13063. EXPECT_EQ("8080", uc.port);
  13064. }
  13065. {
  13066. // Unix socket path — must not be parsed as host
  13067. detail::UrlComponents uc;
  13068. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13069. EXPECT_TRUE(uc.host.empty());
  13070. }
  13071. {
  13072. detail::UrlComponents uc;
  13073. ASSERT_TRUE(detail::parse_url("", uc));
  13074. EXPECT_TRUE(uc.host.empty());
  13075. EXPECT_TRUE(uc.path.empty());
  13076. }
  13077. {
  13078. detail::UrlComponents uc;
  13079. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13080. }
  13081. {
  13082. detail::UrlComponents uc;
  13083. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13084. }
  13085. {
  13086. // Accepted by parse_url; callers restrict to http/https
  13087. detail::UrlComponents uc;
  13088. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13089. EXPECT_EQ("ftp", uc.scheme);
  13090. }
  13091. {
  13092. detail::UrlComponents uc;
  13093. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13094. }
  13095. {
  13096. detail::UrlComponents uc;
  13097. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13098. }
  13099. }
  13100. TEST(ParseUrlTest, FragmentHandling) {
  13101. {
  13102. detail::UrlComponents uc;
  13103. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13104. EXPECT_EQ("/path", uc.path);
  13105. EXPECT_TRUE(uc.query.empty());
  13106. }
  13107. {
  13108. detail::UrlComponents uc;
  13109. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13110. EXPECT_TRUE(uc.path.empty());
  13111. EXPECT_TRUE(uc.query.empty());
  13112. }
  13113. }
  13114. TEST(ParseUrlTest, UserinfoHandling) {
  13115. // Userinfo with @ but no colon — host includes @
  13116. detail::UrlComponents uc;
  13117. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13118. EXPECT_EQ("user@host.com", uc.host);
  13119. EXPECT_EQ("/path", uc.path);
  13120. }
  13121. TEST(ParseUrlTest, IPv6EdgeCases) {
  13122. {
  13123. detail::UrlComponents uc;
  13124. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13125. EXPECT_TRUE(uc.scheme.empty());
  13126. EXPECT_EQ("::1", uc.host);
  13127. EXPECT_EQ("8080", uc.port);
  13128. }
  13129. {
  13130. // Zone ID '%25' is not in [a-fA-F0-9:]
  13131. detail::UrlComponents uc;
  13132. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13133. }
  13134. }
  13135. TEST(ParseUrlTest, SchemeEdgeCases) {
  13136. {
  13137. detail::UrlComponents uc;
  13138. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13139. }
  13140. {
  13141. detail::UrlComponents uc;
  13142. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13143. }
  13144. {
  13145. detail::UrlComponents uc;
  13146. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13147. }
  13148. }
  13149. TEST(ParseUrlTest, PortEdgeCases) {
  13150. {
  13151. detail::UrlComponents uc;
  13152. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13153. EXPECT_TRUE(uc.port.empty());
  13154. EXPECT_EQ("/path", uc.path);
  13155. }
  13156. {
  13157. // parse_url accepts any port string; validation is done by parse_port
  13158. detail::UrlComponents uc;
  13159. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13160. EXPECT_EQ("abc", uc.port);
  13161. }
  13162. }
  13163. TEST(ParseUrlTest, WebSocketPatterns) {
  13164. {
  13165. detail::UrlComponents uc;
  13166. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13167. EXPECT_EQ("ws", uc.scheme);
  13168. EXPECT_EQ("echo.example.com", uc.host);
  13169. EXPECT_EQ("8080", uc.port);
  13170. EXPECT_EQ("/ws", uc.path);
  13171. }
  13172. {
  13173. detail::UrlComponents uc;
  13174. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13175. EXPECT_EQ("wss", uc.scheme);
  13176. EXPECT_EQ("echo.example.com", uc.host);
  13177. EXPECT_TRUE(uc.port.empty());
  13178. EXPECT_EQ("/ws", uc.path);
  13179. }
  13180. }
  13181. TEST(ParseUrlTest, QueryOnly) {
  13182. detail::UrlComponents uc;
  13183. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13184. EXPECT_TRUE(uc.host.empty());
  13185. EXPECT_TRUE(uc.path.empty());
  13186. EXPECT_EQ("?q=1&r=2", uc.query);
  13187. }
  13188. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13189. detail::UrlComponents uc;
  13190. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13191. EXPECT_TRUE(uc.scheme.empty());
  13192. EXPECT_EQ("example.com", uc.host);
  13193. EXPECT_EQ("443", uc.port);
  13194. EXPECT_EQ("/path", uc.path);
  13195. }
  13196. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13197. // If ipv6 regex working, regex match codepath is taken.
  13198. // else port will default to 80 in Client impl
  13199. int clientImplMagicPort = 80;
  13200. int port = 4321;
  13201. // above ports must be different to avoid false negative
  13202. EXPECT_NE(clientImplMagicPort, port);
  13203. std::string ipV6TestURL = "http://[ff06::c3]";
  13204. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13205. CLIENT_PRIVATE_KEY_FILE);
  13206. EXPECT_EQ(cli.port(), port);
  13207. }
  13208. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13209. auto file_path = "./www/dir/index.html";
  13210. auto dir_path = "./www/dir";
  13211. detail::FileStat stat_file(file_path);
  13212. EXPECT_TRUE(stat_file.is_file());
  13213. EXPECT_FALSE(stat_file.is_dir());
  13214. detail::FileStat stat_dir(dir_path);
  13215. EXPECT_FALSE(stat_dir.is_file());
  13216. EXPECT_TRUE(stat_dir.is_dir());
  13217. }
  13218. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13219. // IPv4 with default HTTP port (80)
  13220. EXPECT_EQ("example.com",
  13221. detail::make_host_and_port_string("example.com", 80, false));
  13222. // IPv4 with default HTTPS port (443)
  13223. EXPECT_EQ("example.com",
  13224. detail::make_host_and_port_string("example.com", 443, true));
  13225. // IPv4 with non-default HTTP port
  13226. EXPECT_EQ("example.com:8080",
  13227. detail::make_host_and_port_string("example.com", 8080, false));
  13228. // IPv4 with non-default HTTPS port
  13229. EXPECT_EQ("example.com:8443",
  13230. detail::make_host_and_port_string("example.com", 8443, true));
  13231. // IPv6 with default HTTP port (80)
  13232. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13233. // IPv6 with default HTTPS port (443)
  13234. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13235. // IPv6 with non-default HTTP port
  13236. EXPECT_EQ("[::1]:8080",
  13237. detail::make_host_and_port_string("::1", 8080, false));
  13238. // IPv6 with non-default HTTPS port
  13239. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13240. // IPv6 full address with default port
  13241. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13242. detail::make_host_and_port_string(
  13243. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13244. // IPv6 full address with non-default port
  13245. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13246. detail::make_host_and_port_string(
  13247. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13248. // IPv6 localhost with non-default port
  13249. EXPECT_EQ("[::1]:3000",
  13250. detail::make_host_and_port_string("::1", 3000, false));
  13251. // IPv6 with zone ID (link-local address) with default port
  13252. EXPECT_EQ("[fe80::1%eth0]",
  13253. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13254. // IPv6 with zone ID (link-local address) with non-default port
  13255. EXPECT_EQ("[fe80::1%eth0]:8080",
  13256. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13257. // Edge case: Port 443 with is_ssl=false (should add port)
  13258. EXPECT_EQ("example.com:443",
  13259. detail::make_host_and_port_string("example.com", 443, false));
  13260. // Edge case: Port 80 with is_ssl=true (should add port)
  13261. EXPECT_EQ("example.com:80",
  13262. detail::make_host_and_port_string("example.com", 80, true));
  13263. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13264. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13265. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13266. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13267. // Security fix: Already bracketed IPv6 should not get double brackets
  13268. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13269. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13270. EXPECT_EQ("[::1]:8080",
  13271. detail::make_host_and_port_string("[::1]", 8080, false));
  13272. EXPECT_EQ("[2001:db8::1]:8080",
  13273. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13274. EXPECT_EQ("[fe80::1%eth0]",
  13275. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13276. EXPECT_EQ("[fe80::1%eth0]:8080",
  13277. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13278. // Edge case: Empty host (should return as-is)
  13279. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13280. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13281. // This is a known limitation but shouldn't crash
  13282. EXPECT_EQ("[host:name]",
  13283. detail::make_host_and_port_string("host:name", 80, false));
  13284. // Port number edge cases (no validation, but should not crash)
  13285. EXPECT_EQ("example.com:0",
  13286. detail::make_host_and_port_string("example.com", 0, false));
  13287. EXPECT_EQ("example.com:-1",
  13288. detail::make_host_and_port_string("example.com", -1, false));
  13289. EXPECT_EQ("example.com:65535",
  13290. detail::make_host_and_port_string("example.com", 65535, false));
  13291. EXPECT_EQ("example.com:65536",
  13292. detail::make_host_and_port_string("example.com", 65536, false));
  13293. }
  13294. #ifdef CPPHTTPLIB_SSL_ENABLED
  13295. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13296. httplib::SSLClient cli("roblox.com", 443);
  13297. cli.set_follow_location(true);
  13298. auto res = cli.Get("/");
  13299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13300. EXPECT_EQ(StatusCode::OK_200, res->status);
  13301. }
  13302. #endif
  13303. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13304. Server svr;
  13305. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13306. EXPECT_EQ(res.status, 400);
  13307. });
  13308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13309. auto se = detail::scope_exit([&] {
  13310. svr.stop();
  13311. thread.join();
  13312. ASSERT_FALSE(svr.is_running());
  13313. });
  13314. svr.wait_until_ready();
  13315. Client cli(HOST, PORT);
  13316. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13317. }
  13318. TEST(InvalidHeaderCharsTest, is_field_name) {
  13319. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13320. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13321. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13322. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13323. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13324. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13325. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13326. EXPECT_FALSE(detail::fields::is_field_name(""));
  13327. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13328. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13329. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13330. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13331. }
  13332. TEST(InvalidHeaderCharsTest, is_field_value) {
  13333. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13334. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13335. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13336. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13337. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13338. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13339. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13340. EXPECT_TRUE(detail::fields::is_field_value(""));
  13341. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13342. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13343. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13344. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13345. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13346. }
  13347. TEST(InvalidHeaderCharsTest, OnServer) {
  13348. Server svr;
  13349. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13350. std::string header = "Not Set";
  13351. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13352. res.set_header(header, "value");
  13353. res.set_content("Page Content Page Content", "text/plain");
  13354. });
  13355. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13356. std::string header = "Not Set";
  13357. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13358. res.set_header("X-Test", header);
  13359. res.set_content("Page Content Page Content", "text/plain");
  13360. });
  13361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13362. auto se = detail::scope_exit([&] {
  13363. svr.stop();
  13364. thread.join();
  13365. ASSERT_FALSE(svr.is_running());
  13366. });
  13367. svr.wait_until_ready();
  13368. Client cli(HOST, PORT);
  13369. {
  13370. auto res = cli.Get(
  13371. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13373. EXPECT_EQ("Page Content Page Content", res->body);
  13374. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13375. }
  13376. {
  13377. auto res = cli.Get(
  13378. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13380. EXPECT_EQ("Page Content Page Content", res->body);
  13381. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13382. }
  13383. }
  13384. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13385. auto handled = false;
  13386. Server svr;
  13387. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13388. thread t = thread([&] { svr.listen(HOST, PORT); });
  13389. auto se = detail::scope_exit([&] {
  13390. svr.stop();
  13391. t.join();
  13392. ASSERT_FALSE(svr.is_running());
  13393. ASSERT_FALSE(handled);
  13394. });
  13395. svr.wait_until_ready();
  13396. auto req = "POST /test HTTP/1.1\r\n"
  13397. "Content-Length: x\r\n"
  13398. "\r\n";
  13399. std::string response;
  13400. ASSERT_TRUE(send_request(1, req, &response));
  13401. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13402. response.substr(0, response.find("\r\n")));
  13403. }
  13404. #ifndef _WIN32
  13405. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13406. static constexpr char reject[] = "Unauthorized";
  13407. static constexpr char accept[] = "Upload accepted";
  13408. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13409. Server svr;
  13410. svr.set_expect_100_continue_handler(
  13411. [](const Request & /*req*/, Response &res) {
  13412. res.status = StatusCode::Unauthorized_401;
  13413. res.set_content(reject, "text/plain");
  13414. return res.status;
  13415. });
  13416. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13417. res.set_content(accept, "text/plain");
  13418. });
  13419. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13420. auto se = detail::scope_exit([&] {
  13421. svr.stop();
  13422. thread.join();
  13423. ASSERT_FALSE(svr.is_running());
  13424. });
  13425. svr.wait_until_ready();
  13426. {
  13427. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13428. curl_easy_init(), &curl_easy_cleanup};
  13429. ASSERT_NE(curl, nullptr);
  13430. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13431. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13432. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13433. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13434. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13435. &curl_slist_free_all};
  13436. ASSERT_NE(list, nullptr);
  13437. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13438. struct read_data {
  13439. size_t read_size;
  13440. size_t total_size;
  13441. } data = {0, total_size};
  13442. using read_callback_t =
  13443. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13444. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13445. void *userdata) -> size_t {
  13446. read_data *d = (read_data *)userdata;
  13447. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13448. std::fill_n(ptr, size * nmemb, 'A');
  13449. d->read_size += size * nmemb;
  13450. return size * nmemb;
  13451. };
  13452. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13453. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13454. std::vector<char> buffer;
  13455. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13456. using write_callback_t =
  13457. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13458. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13459. void *userdata) -> size_t {
  13460. std::vector<char> *buf = (std::vector<char> *)userdata;
  13461. buf->reserve(buf->size() + size * nmemb + 1);
  13462. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13463. return size * nmemb;
  13464. };
  13465. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13466. {
  13467. const auto res = curl_easy_perform(curl.get());
  13468. ASSERT_EQ(res, CURLE_OK);
  13469. }
  13470. {
  13471. auto response_code = long{};
  13472. const auto res =
  13473. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13474. ASSERT_EQ(res, CURLE_OK);
  13475. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13476. }
  13477. {
  13478. auto dl = curl_off_t{};
  13479. const auto res =
  13480. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13481. ASSERT_EQ(res, CURLE_OK);
  13482. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13483. }
  13484. {
  13485. buffer.push_back('\0');
  13486. ASSERT_STRCASEEQ(buffer.data(), reject);
  13487. }
  13488. }
  13489. }
  13490. #endif
  13491. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13492. // Regression test for #2458.
  13493. //
  13494. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13495. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13496. // ticket can make the client socket spuriously readable during the
  13497. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13498. // the client withholds the body and then blocks reading a response that never
  13499. // comes, failing with `Failed to read connection`.
  13500. //
  13501. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13502. // within the timeout. This raw OpenSSL server deliberately never sends
  13503. // `100 Continue`; the client must still deliver the body and receive 200.
  13504. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13505. signal(SIGPIPE, SIG_IGN);
  13506. const auto port = PORT + 4;
  13507. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13508. ASSERT_NE(srv, INVALID_SOCKET);
  13509. int opt = 1;
  13510. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13511. sockaddr_in addr{};
  13512. addr.sin_family = AF_INET;
  13513. addr.sin_port = htons(static_cast<uint16_t>(port));
  13514. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13515. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13516. ASSERT_EQ(0, ::listen(srv, 1));
  13517. std::atomic<size_t> server_body_bytes{0};
  13518. auto server_thread = std::thread([&] {
  13519. sockaddr_in cli_addr{};
  13520. socklen_t cli_len = sizeof(cli_addr);
  13521. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13522. if (cli == INVALID_SOCKET) { return; }
  13523. // Bound the lifetime of the server side so a buggy client (which never
  13524. // sends the body) cannot make this thread block forever on join.
  13525. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13526. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13527. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13528. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13529. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13530. SSL *ssl = SSL_new(ctx);
  13531. SSL_set_fd(ssl, static_cast<int>(cli));
  13532. if (SSL_accept(ssl) > 0) {
  13533. // Read the request headers. Reading here also flushes the TLS 1.3
  13534. // session tickets to the client. Deliberately do NOT send
  13535. // `100 Continue`.
  13536. std::string buf;
  13537. char tmp[1024];
  13538. while (buf.find("\r\n\r\n") == std::string::npos) {
  13539. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13540. if (n <= 0) { break; }
  13541. buf.append(tmp, static_cast<size_t>(n));
  13542. }
  13543. // A correct client sends the body now; count what arrives.
  13544. auto pos = buf.find("\r\n\r\n");
  13545. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13546. while (body < 4096) {
  13547. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13548. if (n <= 0) { break; }
  13549. body += static_cast<size_t>(n);
  13550. }
  13551. server_body_bytes = body;
  13552. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13553. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13554. SSL_shutdown(ssl);
  13555. }
  13556. SSL_free(ssl);
  13557. detail::close_socket(cli);
  13558. SSL_CTX_free(ctx);
  13559. });
  13560. auto se = detail::scope_exit([&] {
  13561. server_thread.join();
  13562. detail::close_socket(srv);
  13563. });
  13564. SSLClient cli("127.0.0.1", port);
  13565. cli.enable_server_certificate_verification(false);
  13566. cli.set_connection_timeout(5, 0);
  13567. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13568. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13569. std::string body(4096, 'A');
  13570. auto res = cli.Put("/api/test", body, "application/json");
  13571. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13572. EXPECT_EQ(StatusCode::OK_200, res->status);
  13573. EXPECT_EQ(body.size(), server_body_bytes.load());
  13574. }
  13575. #endif
  13576. template <typename S, typename C>
  13577. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13578. svr.Get("/stream", [&](const Request &, Response &res) {
  13579. auto data = new std::string("01234567890123456789");
  13580. res.set_content_provider(
  13581. data->size(), "text/plain",
  13582. [&, data](size_t offset, size_t length, DataSink &sink) {
  13583. const size_t DATA_CHUNK_SIZE = 4;
  13584. const auto &d = *data;
  13585. std::this_thread::sleep_for(std::chrono::seconds(1));
  13586. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13587. return true;
  13588. },
  13589. [data](bool success) {
  13590. EXPECT_FALSE(success);
  13591. delete data;
  13592. });
  13593. });
  13594. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13595. auto i = new size_t(0);
  13596. res.set_content_provider(
  13597. "text/plain",
  13598. [i](size_t, DataSink &sink) {
  13599. if (*i < 5) {
  13600. std::this_thread::sleep_for(std::chrono::seconds(1));
  13601. sink.write("abcd", 4);
  13602. (*i)++;
  13603. } else {
  13604. sink.done();
  13605. }
  13606. return true;
  13607. },
  13608. [i](bool success) {
  13609. EXPECT_FALSE(success);
  13610. delete i;
  13611. });
  13612. });
  13613. svr.Get("/chunked", [&](const Request &, Response &res) {
  13614. auto i = new size_t(0);
  13615. res.set_chunked_content_provider(
  13616. "text/plain",
  13617. [i](size_t, DataSink &sink) {
  13618. if (*i < 5) {
  13619. std::this_thread::sleep_for(std::chrono::seconds(1));
  13620. sink.os << "abcd";
  13621. (*i)++;
  13622. } else {
  13623. sink.done();
  13624. }
  13625. return true;
  13626. },
  13627. [i](bool success) {
  13628. EXPECT_FALSE(success);
  13629. delete i;
  13630. });
  13631. });
  13632. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13633. auto se = detail::scope_exit([&] {
  13634. svr.stop();
  13635. listen_thread.join();
  13636. ASSERT_FALSE(svr.is_running());
  13637. });
  13638. svr.wait_until_ready();
  13639. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13640. {
  13641. auto start = std::chrono::steady_clock::now();
  13642. auto res = cli.Get("/stream");
  13643. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13644. std::chrono::steady_clock::now() - start)
  13645. .count();
  13646. ASSERT_FALSE(res);
  13647. EXPECT_EQ(Error::Read, res.error());
  13648. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13649. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13650. }
  13651. {
  13652. auto start = std::chrono::steady_clock::now();
  13653. auto res = cli.Get("/stream_without_length");
  13654. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13655. std::chrono::steady_clock::now() - start)
  13656. .count();
  13657. ASSERT_FALSE(res);
  13658. EXPECT_EQ(Error::Read, res.error());
  13659. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13660. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13661. }
  13662. {
  13663. auto start = std::chrono::steady_clock::now();
  13664. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13665. EXPECT_EQ("abcd", string(data, data_length));
  13666. return true;
  13667. });
  13668. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13669. std::chrono::steady_clock::now() - start)
  13670. .count();
  13671. ASSERT_FALSE(res);
  13672. EXPECT_EQ(Error::Read, res.error());
  13673. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13674. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13675. }
  13676. }
  13677. TEST(MaxTimeoutTest, ContentStream) {
  13678. time_t timeout = 2000;
  13679. time_t threshold = 200;
  13680. Server svr;
  13681. Client cli("localhost", PORT);
  13682. max_timeout_test(svr, cli, timeout, threshold);
  13683. }
  13684. #ifdef CPPHTTPLIB_SSL_ENABLED
  13685. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13686. time_t timeout = 2000;
  13687. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13688. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13689. SSLClient cli("localhost", PORT);
  13690. cli.enable_server_certificate_verification(false);
  13691. max_timeout_test(svr, cli, timeout, threshold);
  13692. }
  13693. #endif
  13694. class EventDispatcher {
  13695. public:
  13696. EventDispatcher() {}
  13697. bool wait_event(DataSink *sink) {
  13698. unique_lock<mutex> lk(m_);
  13699. int id = id_;
  13700. // Wait with timeout to prevent hanging if client disconnects
  13701. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13702. [&] { return cid_ == id; })) {
  13703. return false; // Timeout occurred
  13704. }
  13705. sink->write(message_.data(), message_.size());
  13706. return true;
  13707. }
  13708. void send_event(const string &message) {
  13709. lock_guard<mutex> lk(m_);
  13710. cid_ = id_++;
  13711. message_ = message;
  13712. cv_.notify_all();
  13713. }
  13714. private:
  13715. mutex m_;
  13716. condition_variable cv_;
  13717. atomic_int id_{0};
  13718. atomic_int cid_{-1};
  13719. string message_;
  13720. };
  13721. TEST(ClientInThreadTest, Issue2068) {
  13722. EventDispatcher ed;
  13723. Server svr;
  13724. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13725. res.set_chunked_content_provider("text/event-stream",
  13726. [&](size_t /*offset*/, DataSink &sink) {
  13727. return ed.wait_event(&sink);
  13728. });
  13729. });
  13730. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13731. svr.wait_until_ready();
  13732. thread event_thread([&] {
  13733. int id = 0;
  13734. while (svr.is_running()) {
  13735. this_thread::sleep_for(chrono::milliseconds(500));
  13736. std::stringstream ss;
  13737. ss << "data: " << id << "\n\n";
  13738. ed.send_event(ss.str());
  13739. id++;
  13740. }
  13741. });
  13742. auto se = detail::scope_exit([&] {
  13743. svr.stop();
  13744. listen_thread.join();
  13745. event_thread.join();
  13746. ASSERT_FALSE(svr.is_running());
  13747. });
  13748. {
  13749. auto client = detail::make_unique<Client>(HOST, PORT);
  13750. client->set_read_timeout(std::chrono::minutes(10));
  13751. std::atomic<bool> stop{false};
  13752. std::thread t([&] {
  13753. client->Get("/event1",
  13754. [&](const char *, size_t) -> bool { return !stop; });
  13755. });
  13756. std::this_thread::sleep_for(std::chrono::seconds(2));
  13757. stop = true;
  13758. client->stop();
  13759. t.join();
  13760. // Reset client after thread has finished
  13761. client.reset();
  13762. }
  13763. }
  13764. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13765. auto handled = false;
  13766. Server svr;
  13767. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13768. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13769. auto se = detail::scope_exit([&] {
  13770. svr.stop();
  13771. t.join();
  13772. ASSERT_FALSE(svr.is_running());
  13773. ASSERT_FALSE(handled);
  13774. });
  13775. svr.wait_until_ready();
  13776. // Two Content-Length headers with different values — must be rejected
  13777. auto req = "POST /test HTTP/1.1\r\n"
  13778. "Content-Length: 5\r\n"
  13779. "Content-Length: 10\r\n"
  13780. "\r\n"
  13781. "hello";
  13782. std::string response;
  13783. ASSERT_TRUE(send_request(1, req, &response));
  13784. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13785. response.substr(0, response.find("\r\n")));
  13786. }
  13787. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13788. auto handled = false;
  13789. Server svr;
  13790. svr.Post("/test", [&](const Request &, Response &res) {
  13791. handled = true;
  13792. res.set_content("ok", "text/plain");
  13793. });
  13794. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13795. auto se = detail::scope_exit([&] {
  13796. svr.stop();
  13797. t.join();
  13798. ASSERT_FALSE(svr.is_running());
  13799. ASSERT_TRUE(handled);
  13800. });
  13801. svr.wait_until_ready();
  13802. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13803. auto req = "POST /test HTTP/1.1\r\n"
  13804. "Content-Length: 5\r\n"
  13805. "Content-Length: 5\r\n"
  13806. "\r\n"
  13807. "hello";
  13808. std::string response;
  13809. ASSERT_TRUE(send_request(1, req, &response));
  13810. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13811. }
  13812. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13813. Server svr;
  13814. svr.Get("/", [](const Request &req, Response &res) {
  13815. EXPECT_EQ(2U, req.trailers.size());
  13816. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13817. // Denied
  13818. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13819. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13820. // Accepted
  13821. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13822. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13823. EXPECT_TRUE(req.has_trailer("X-World"));
  13824. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13825. res.set_content("ok", "text/plain");
  13826. });
  13827. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13828. auto se = detail::scope_exit([&] {
  13829. svr.stop();
  13830. t.join();
  13831. ASSERT_FALSE(svr.is_running());
  13832. });
  13833. svr.wait_until_ready();
  13834. const std::string req = "GET / HTTP/1.1\r\n"
  13835. "Transfer-Encoding: chunked\r\n"
  13836. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13837. "\r\n"
  13838. "0\r\n"
  13839. "Content-Length: 10\r\n"
  13840. "Host: internal.local\r\n"
  13841. "Content-Type: malicious/content\r\n"
  13842. "Cookie: any\r\n"
  13843. "Set-Cookie: any\r\n"
  13844. "X-Forwarded-For: attacker.com\r\n"
  13845. "X-Real-Ip: 1.1.1.1\r\n"
  13846. "X-Hello: hello\r\n"
  13847. "X-World: world\r\n"
  13848. "\r\n";
  13849. std::string res;
  13850. ASSERT_TRUE(send_request(1, req, &res));
  13851. }
  13852. // A direct client that is not listed in trusted_proxies must not be able to
  13853. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13854. // the peer address on the actual TCP connection determines whether the
  13855. // header is honored.
  13856. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13857. Server svr;
  13858. // Deliberately does NOT include the loopback address the test client
  13859. // actually connects from, so the direct connection is not a trusted proxy.
  13860. svr.set_trusted_proxies({"203.0.113.66"});
  13861. std::string observed_remote_addr;
  13862. svr.Get("/ip", [&](const Request &req, Response &res) {
  13863. observed_remote_addr = req.remote_addr;
  13864. res.set_content("ok", "text/plain");
  13865. });
  13866. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13867. auto se = detail::scope_exit([&] {
  13868. svr.stop();
  13869. t.join();
  13870. ASSERT_FALSE(svr.is_running());
  13871. });
  13872. svr.wait_until_ready();
  13873. Client cli(HOST, PORT);
  13874. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13876. EXPECT_EQ(StatusCode::OK_200, res->status);
  13877. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13878. // ignored entirely and the real connection-level address retained.
  13879. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13880. observed_remote_addr == "127.0.0.1");
  13881. }
  13882. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13883. Server svr;
  13884. std::string observed_remote_addr;
  13885. std::string observed_xff;
  13886. svr.Get("/ip", [&](const Request &req, Response &res) {
  13887. observed_remote_addr = req.remote_addr;
  13888. observed_xff = req.get_header_value("X-Forwarded-For");
  13889. res.set_content("ok", "text/plain");
  13890. });
  13891. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13892. auto se = detail::scope_exit([&] {
  13893. svr.stop();
  13894. t.join();
  13895. ASSERT_FALSE(svr.is_running());
  13896. });
  13897. svr.wait_until_ready();
  13898. Client cli(HOST, PORT);
  13899. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13901. EXPECT_EQ(StatusCode::OK_200, res->status);
  13902. EXPECT_EQ(observed_xff, "203.0.113.66");
  13903. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13904. observed_remote_addr == "127.0.0.1");
  13905. }
  13906. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13907. Server svr;
  13908. svr.set_trusted_proxies({"203.0.113.66"});
  13909. std::string observed_remote_addr;
  13910. std::string observed_xff;
  13911. svr.Get("/ip", [&](const Request &req, Response &res) {
  13912. observed_remote_addr = req.remote_addr;
  13913. observed_xff = req.get_header_value("X-Forwarded-For");
  13914. res.set_content("ok", "text/plain");
  13915. });
  13916. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13917. auto se = detail::scope_exit([&] {
  13918. svr.stop();
  13919. t.join();
  13920. ASSERT_FALSE(svr.is_running());
  13921. });
  13922. svr.wait_until_ready();
  13923. Client cli(HOST, PORT);
  13924. auto res = cli.Get("/ip");
  13925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13926. EXPECT_EQ(StatusCode::OK_200, res->status);
  13927. EXPECT_EQ(observed_xff, "");
  13928. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13929. observed_remote_addr == "127.0.0.1");
  13930. }
  13931. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13932. Server svr;
  13933. // Include the loopback address the test client actually connects from, so
  13934. // the direct connection itself is recognized as the trusted proxy hop.
  13935. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13936. std::string observed_remote_addr;
  13937. std::string observed_xff;
  13938. svr.Get("/ip", [&](const Request &req, Response &res) {
  13939. observed_remote_addr = req.remote_addr;
  13940. observed_xff = req.get_header_value("X-Forwarded-For");
  13941. res.set_content("ok", "text/plain");
  13942. });
  13943. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13944. auto se = detail::scope_exit([&] {
  13945. svr.stop();
  13946. t.join();
  13947. ASSERT_FALSE(svr.is_running());
  13948. });
  13949. svr.wait_until_ready();
  13950. Client cli(HOST, PORT);
  13951. auto res = cli.Get(
  13952. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13954. EXPECT_EQ(StatusCode::OK_200, res->status);
  13955. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13956. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13957. }
  13958. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13959. Server svr;
  13960. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13961. std::string observed_remote_addr;
  13962. std::string observed_xff;
  13963. svr.Get("/ip", [&](const Request &req, Response &res) {
  13964. observed_remote_addr = req.remote_addr;
  13965. observed_xff = req.get_header_value("X-Forwarded-For");
  13966. res.set_content("ok", "text/plain");
  13967. });
  13968. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13969. auto se = detail::scope_exit([&] {
  13970. svr.stop();
  13971. t.join();
  13972. ASSERT_FALSE(svr.is_running());
  13973. });
  13974. svr.wait_until_ready();
  13975. Client cli(HOST, PORT);
  13976. auto res = cli.Get(
  13977. "/ip",
  13978. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13980. EXPECT_EQ(StatusCode::OK_200, res->status);
  13981. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13982. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13983. }
  13984. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13985. Server svr;
  13986. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13987. std::string observed_remote_addr;
  13988. std::string observed_xff;
  13989. svr.Get("/ip", [&](const Request &req, Response &res) {
  13990. observed_remote_addr = req.remote_addr;
  13991. observed_xff = req.get_header_value("X-Forwarded-For");
  13992. res.set_content("ok", "text/plain");
  13993. });
  13994. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13995. auto se = detail::scope_exit([&] {
  13996. svr.stop();
  13997. t.join();
  13998. ASSERT_FALSE(svr.is_running());
  13999. });
  14000. svr.wait_until_ready();
  14001. Client cli(HOST, PORT);
  14002. auto res = cli.Get(
  14003. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  14004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14005. EXPECT_EQ(StatusCode::OK_200, res->status);
  14006. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  14007. // by the closest hop) is used. The leftmost entry is fully client-controlled
  14008. // and must not be selected.
  14009. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  14010. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  14011. }
  14012. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  14013. Server svr;
  14014. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14015. std::string observed_remote_addr;
  14016. svr.Get("/ip", [&](const Request &req, Response &res) {
  14017. observed_remote_addr = req.remote_addr;
  14018. res.set_content("ok", "text/plain");
  14019. });
  14020. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14021. auto se = detail::scope_exit([&] {
  14022. svr.stop();
  14023. t.join();
  14024. ASSERT_FALSE(svr.is_running());
  14025. });
  14026. svr.wait_until_ready();
  14027. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14028. // a forged address and the trusted proxy's own address; the forged value must
  14029. // not win over the address the trusted proxy actually recorded.
  14030. Client cli(HOST, PORT);
  14031. auto res = cli.Get(
  14032. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14034. EXPECT_EQ(StatusCode::OK_200, res->status);
  14035. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14036. }
  14037. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14038. Server svr;
  14039. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14040. std::string observed_remote_addr;
  14041. std::string observed_xff;
  14042. svr.Get("/ip", [&](const Request &req, Response &res) {
  14043. observed_remote_addr = req.remote_addr;
  14044. observed_xff = req.get_header_value("X-Forwarded-For");
  14045. res.set_content("ok", "text/plain");
  14046. });
  14047. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14048. auto se = detail::scope_exit([&] {
  14049. svr.stop();
  14050. t.join();
  14051. ASSERT_FALSE(svr.is_running());
  14052. });
  14053. svr.wait_until_ready();
  14054. Client cli(HOST, PORT);
  14055. auto res = cli.Get(
  14056. "/ip",
  14057. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14059. EXPECT_EQ(StatusCode::OK_200, res->status);
  14060. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14061. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14062. }
  14063. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14064. Server svr;
  14065. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14066. std::string observed_remote_addr;
  14067. std::string observed_xff;
  14068. svr.Get("/ip", [&](const Request &req, Response &res) {
  14069. observed_remote_addr = req.remote_addr;
  14070. observed_xff = req.get_header_value("X-Forwarded-For");
  14071. res.set_content("ok", "text/plain");
  14072. });
  14073. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14074. auto se = detail::scope_exit([&] {
  14075. svr.stop();
  14076. t.join();
  14077. ASSERT_FALSE(svr.is_running());
  14078. });
  14079. svr.wait_until_ready();
  14080. std::string raw_req =
  14081. "GET /ip HTTP/1.1\r\n"
  14082. "Host: localhost\r\n"
  14083. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14084. "Connection: close\r\n"
  14085. "\r\n";
  14086. std::string out;
  14087. ASSERT_TRUE(send_request(5, raw_req, &out));
  14088. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14089. // Header parser trims surrounding whitespace of the header value
  14090. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14091. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14092. }
  14093. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14094. // crash the server (it used to call front() on an empty vector inside
  14095. // get_client_ip). The connection-level remote address must be retained instead.
  14096. static void run_malformed_xff_test(const std::string &xff_value) {
  14097. Server svr;
  14098. svr.set_trusted_proxies({"192.0.2.45"});
  14099. std::string observed_remote_addr;
  14100. svr.Get("/ip", [&](const Request &req, Response &res) {
  14101. observed_remote_addr = req.remote_addr;
  14102. res.set_content("ok", "text/plain");
  14103. });
  14104. int port = 0;
  14105. thread t = thread([&]() {
  14106. port = svr.bind_to_any_port(HOST);
  14107. svr.listen_after_bind();
  14108. });
  14109. auto se = detail::scope_exit([&] {
  14110. svr.stop();
  14111. t.join();
  14112. ASSERT_FALSE(svr.is_running());
  14113. });
  14114. svr.wait_until_ready();
  14115. Client cli(HOST, port);
  14116. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  14117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14118. EXPECT_EQ(StatusCode::OK_200, res->status);
  14119. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14120. observed_remote_addr == "127.0.0.1");
  14121. }
  14122. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  14123. run_malformed_xff_test("");
  14124. }
  14125. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  14126. run_malformed_xff_test(",");
  14127. }
  14128. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  14129. run_malformed_xff_test(", , ,");
  14130. }
  14131. #ifndef _WIN32
  14132. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  14133. Server svr;
  14134. svr.Post("/post", [&](const Request &req, Response &res) {
  14135. res.set_content(req.body, "text/plain");
  14136. });
  14137. svr.Put("/put", [&](const Request &req, Response &res) {
  14138. res.set_content(req.body, "text/plain");
  14139. });
  14140. svr.Patch("/patch", [&](const Request &req, Response &res) {
  14141. res.set_content(req.body, "text/plain");
  14142. });
  14143. svr.Delete("/delete", [&](const Request &req, Response &res) {
  14144. res.set_content(req.body, "text/plain");
  14145. });
  14146. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14147. auto se = detail::scope_exit([&] {
  14148. svr.stop();
  14149. t.join();
  14150. ASSERT_FALSE(svr.is_running());
  14151. });
  14152. svr.wait_until_ready();
  14153. std::string resp;
  14154. // POST without Content-Length
  14155. ASSERT_TRUE(send_request(5,
  14156. "POST /post HTTP/1.1\r\n"
  14157. "Host: localhost\r\n"
  14158. "Connection: close\r\n"
  14159. "\r\n",
  14160. &resp));
  14161. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14162. // PUT without Content-Length
  14163. resp.clear();
  14164. ASSERT_TRUE(send_request(5,
  14165. "PUT /put HTTP/1.1\r\n"
  14166. "Host: localhost\r\n"
  14167. "Connection: close\r\n"
  14168. "\r\n",
  14169. &resp));
  14170. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14171. // PATCH without Content-Length
  14172. resp.clear();
  14173. ASSERT_TRUE(send_request(5,
  14174. "PATCH /patch HTTP/1.1\r\n"
  14175. "Host: localhost\r\n"
  14176. "Connection: close\r\n"
  14177. "\r\n",
  14178. &resp));
  14179. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14180. // DELETE without Content-Length
  14181. resp.clear();
  14182. ASSERT_TRUE(send_request(5,
  14183. "DELETE /delete HTTP/1.1\r\n"
  14184. "Host: localhost\r\n"
  14185. "Connection: close\r\n"
  14186. "\r\n",
  14187. &resp));
  14188. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14189. }
  14190. #endif
  14191. //==============================================================================
  14192. // open_stream() Tests
  14193. //==============================================================================
  14194. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  14195. std::string result;
  14196. char buf[8192];
  14197. ssize_t n;
  14198. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14199. result.append(buf, static_cast<size_t>(n));
  14200. }
  14201. return result;
  14202. }
  14203. // Mock stream for unit tests
  14204. class MockStream : public Stream {
  14205. public:
  14206. std::string data;
  14207. size_t pos = 0;
  14208. ssize_t error_after = -1; // -1 = no error
  14209. explicit MockStream(const std::string &d, ssize_t err = -1)
  14210. : data(d), error_after(err) {}
  14211. bool is_readable() const override { return true; }
  14212. bool wait_readable() const override { return true; }
  14213. bool wait_writable() const override { return true; }
  14214. ssize_t read(char *ptr, size_t size) override {
  14215. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  14216. if (pos >= data.size()) return 0;
  14217. size_t limit =
  14218. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  14219. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  14220. std::memcpy(ptr, data.data() + pos, to_read);
  14221. pos += to_read;
  14222. return static_cast<ssize_t>(to_read);
  14223. }
  14224. ssize_t write(const char *, size_t) override { return -1; }
  14225. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  14226. ip = "127.0.0.1";
  14227. port = 0;
  14228. }
  14229. void get_local_ip_and_port(std::string &ip, int &port) const override {
  14230. ip = "127.0.0.1";
  14231. port = 0;
  14232. }
  14233. socket_t socket() const override { return INVALID_SOCKET; }
  14234. time_t duration() const override { return 0; }
  14235. };
  14236. TEST(StreamHandleTest, Basic) {
  14237. ClientImpl::StreamHandle handle;
  14238. EXPECT_FALSE(handle.is_valid());
  14239. handle.response = detail::make_unique<Response>();
  14240. handle.error = Error::Connection;
  14241. EXPECT_FALSE(handle.is_valid());
  14242. handle.error = Error::Success;
  14243. EXPECT_TRUE(handle.is_valid());
  14244. }
  14245. TEST(BodyReaderTest, Basic) {
  14246. MockStream stream("Hello, World!");
  14247. detail::BodyReader reader;
  14248. reader.stream = &stream;
  14249. reader.content_length = 13;
  14250. char buf[32];
  14251. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  14252. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  14253. EXPECT_TRUE(reader.eof);
  14254. }
  14255. TEST(BodyReaderTest, NoStream) {
  14256. detail::BodyReader reader;
  14257. char buf[32];
  14258. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14259. EXPECT_EQ(Error::Connection, reader.last_error);
  14260. }
  14261. TEST(BodyReaderTest, Error) {
  14262. MockStream stream("Hello, World!", 5);
  14263. detail::BodyReader reader;
  14264. reader.stream = &stream;
  14265. reader.content_length = 13;
  14266. char buf[32];
  14267. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  14268. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14269. EXPECT_EQ(Error::Read, reader.last_error);
  14270. }
  14271. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  14272. // Mock-based StreamHandle tests relying on private internals are removed.
  14273. class OpenStreamTest : public ::testing::Test {
  14274. protected:
  14275. void SetUp() override {
  14276. svr_.Get("/hello", [](const Request &, Response &res) {
  14277. res.set_content("Hello World!", "text/plain");
  14278. });
  14279. svr_.Get("/large", [](const Request &, Response &res) {
  14280. res.set_content(std::string(10000, 'X'), "text/plain");
  14281. });
  14282. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  14283. res.set_content("Hello World!", "image/jpeg");
  14284. res.set_header("Content-Encoding", "UTF-8");
  14285. });
  14286. svr_.Get("/chunked", [](const Request &, Response &res) {
  14287. res.set_chunked_content_provider("text/plain",
  14288. [](size_t offset, DataSink &sink) {
  14289. if (offset < 15) {
  14290. sink.write("chunk", 5);
  14291. return true;
  14292. }
  14293. sink.done();
  14294. return true;
  14295. });
  14296. });
  14297. svr_.Get("/compressible", [](const Request &, Response &res) {
  14298. res.set_chunked_content_provider("text/plain", [](size_t offset,
  14299. DataSink &sink) {
  14300. if (offset < 100 * 1024) {
  14301. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  14302. sink.write(chunk.data(), chunk.size());
  14303. return true;
  14304. }
  14305. sink.done();
  14306. return true;
  14307. });
  14308. });
  14309. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  14310. [](const Request & /*req*/, Response &res) {
  14311. auto i = new int(0);
  14312. res.set_header("Trailer", "Content-Length, X-Allowed");
  14313. res.set_chunked_content_provider(
  14314. "text/plain",
  14315. [i](size_t /*offset*/, DataSink &sink) {
  14316. switch (*i) {
  14317. case 0: sink.os << "123"; break;
  14318. case 1: sink.os << "456"; break;
  14319. case 2: sink.os << "789"; break;
  14320. case 3: {
  14321. sink.done_with_trailer(
  14322. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  14323. } break;
  14324. }
  14325. (*i)++;
  14326. return true;
  14327. },
  14328. [i](bool success) {
  14329. EXPECT_TRUE(success);
  14330. delete i;
  14331. });
  14332. });
  14333. // Echo headers endpoint for header-related tests
  14334. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  14335. std::string body;
  14336. for (const auto &h : req.headers) {
  14337. body.append(h.first);
  14338. body.push_back(':');
  14339. body.append(h.second);
  14340. body.push_back('\n');
  14341. }
  14342. res.set_content(body, "text/plain");
  14343. });
  14344. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  14345. std::string body;
  14346. for (const auto &h : req.headers) {
  14347. body.append(h.first);
  14348. body.push_back(':');
  14349. body.append(h.second);
  14350. body.push_back('\n');
  14351. }
  14352. res.set_content(body, "text/plain");
  14353. });
  14354. port_ = svr_.bind_to_any_port("127.0.0.1");
  14355. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14356. svr_.wait_until_ready();
  14357. }
  14358. void TearDown() override {
  14359. svr_.stop();
  14360. if (thread_.joinable()) thread_.join();
  14361. }
  14362. Server svr_;
  14363. std::thread thread_;
  14364. int port_ = 0;
  14365. };
  14366. TEST_F(OpenStreamTest, Basic) {
  14367. Client cli("127.0.0.1", port_);
  14368. auto handle = cli.open_stream("GET", "/hello");
  14369. EXPECT_TRUE(handle.is_valid());
  14370. EXPECT_EQ("Hello World!", read_all(handle));
  14371. }
  14372. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  14373. Client cli("127.0.0.1", port_);
  14374. auto handle = cli.open_stream("GET", "/unknown-encoding");
  14375. ASSERT_TRUE(handle.is_valid());
  14376. EXPECT_EQ("Hello World!", read_all(handle));
  14377. }
  14378. TEST_F(OpenStreamTest, SmallBuffer) {
  14379. Client cli("127.0.0.1", port_);
  14380. auto handle = cli.open_stream("GET", "/hello");
  14381. std::string result;
  14382. char buf[4];
  14383. ssize_t n;
  14384. while ((n = handle.read(buf, sizeof(buf))) > 0)
  14385. result.append(buf, static_cast<size_t>(n));
  14386. EXPECT_EQ("Hello World!", result);
  14387. }
  14388. TEST_F(OpenStreamTest, DefaultHeaders) {
  14389. Client cli("127.0.0.1", port_);
  14390. // open_stream GET should include Host, User-Agent and Accept-Encoding
  14391. {
  14392. auto handle = cli.open_stream("GET", "/echo-headers");
  14393. ASSERT_TRUE(handle.is_valid());
  14394. auto body = read_all(handle);
  14395. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  14396. std::string::npos);
  14397. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  14398. std::string::npos);
  14399. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  14400. }
  14401. // open_stream POST with body and no explicit content_type should NOT add
  14402. // text/plain Content-Type (behavior differs from non-streaming path), but
  14403. // should include Content-Length
  14404. {
  14405. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14406. ASSERT_TRUE(handle.is_valid());
  14407. auto body = read_all(handle);
  14408. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14409. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14410. }
  14411. // open_stream POST with explicit Content-Type should preserve it
  14412. {
  14413. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14414. {{"Content-Type", "application/custom"}},
  14415. "{}", "application/custom");
  14416. ASSERT_TRUE(handle.is_valid());
  14417. auto body = read_all(handle);
  14418. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14419. }
  14420. // User-specified User-Agent must not be overwritten for stream API
  14421. {
  14422. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14423. {{"User-Agent", "MyAgent/1.2"}});
  14424. ASSERT_TRUE(handle.is_valid());
  14425. auto body = read_all(handle);
  14426. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14427. }
  14428. }
  14429. TEST_F(OpenStreamTest, Large) {
  14430. Client cli("127.0.0.1", port_);
  14431. auto handle = cli.open_stream("GET", "/large");
  14432. EXPECT_EQ(10000u, read_all(handle).size());
  14433. }
  14434. TEST_F(OpenStreamTest, ConnectionError) {
  14435. Client cli("127.0.0.1", 9999);
  14436. auto handle = cli.open_stream("GET", "/hello");
  14437. EXPECT_FALSE(handle.is_valid());
  14438. }
  14439. TEST_F(OpenStreamTest, Chunked) {
  14440. Client cli("127.0.0.1", port_);
  14441. auto handle = cli.open_stream("GET", "/chunked");
  14442. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14443. "Transfer-Encoding") == "chunked");
  14444. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14445. }
  14446. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14447. Client cli("127.0.0.1", port_);
  14448. auto handle =
  14449. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14450. ASSERT_TRUE(handle.is_valid());
  14451. // Consume body to allow trailers to be received/parsed
  14452. auto body = read_all(handle);
  14453. // Explicitly parse trailers (ensure trailers are available for assertion)
  14454. handle.parse_trailers_if_needed();
  14455. EXPECT_EQ(std::string("123456789"), body);
  14456. // The response should include a Trailer header declaring both names
  14457. ASSERT_TRUE(handle.response);
  14458. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14459. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14460. handle.response->get_header_value("Trailer"));
  14461. // Prohibited trailer must not be present
  14462. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14463. // Allowed trailer should be present
  14464. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14465. EXPECT_EQ(std::string("yes"),
  14466. handle.response->get_trailer_value("X-Allowed"));
  14467. // Verify trailers are NOT present as regular headers
  14468. EXPECT_EQ(std::string(""),
  14469. handle.response->get_header_value("Content-Length"));
  14470. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14471. }
  14472. static std::thread serve_single_response(std::promise<int> &port_promise,
  14473. const std::string &response) {
  14474. return std::thread([&port_promise, response] {
  14475. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14476. default_socket_options(srv);
  14477. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14478. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14479. sockaddr_in addr{};
  14480. addr.sin_family = AF_INET;
  14481. addr.sin_port = htons(0); // Let OS assign a free port
  14482. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14483. int opt = 1;
  14484. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14485. #ifdef _WIN32
  14486. reinterpret_cast<const char *>(&opt),
  14487. #else
  14488. &opt,
  14489. #endif
  14490. sizeof(opt));
  14491. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  14492. ::listen(srv, 1) != 0) {
  14493. port_promise.set_value(-1);
  14494. detail::close_socket(srv);
  14495. return;
  14496. }
  14497. socklen_t addr_len = sizeof(addr);
  14498. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  14499. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  14500. sockaddr_in cli_addr{};
  14501. socklen_t cli_len = sizeof(cli_addr);
  14502. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14503. if (cli != INVALID_SOCKET) {
  14504. // Read the complete HTTP request (until the blank line that terminates
  14505. // headers) before sending the response. If the server closes the socket
  14506. // while the client's request data is still unread in the kernel receive
  14507. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  14508. // connection on both sides: it discards the client's receive buffer
  14509. // (which already holds our response) and causes any in-progress write on
  14510. // the client to fail with ECONNRESET. Reading all request data first
  14511. // ensures close() emits a graceful FIN.
  14512. {
  14513. char rbuf[256];
  14514. std::string req;
  14515. while (req.find("\r\n\r\n") == std::string::npos) {
  14516. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  14517. if (n <= 0) { break; }
  14518. req.append(rbuf, static_cast<size_t>(n));
  14519. }
  14520. }
  14521. ::send(cli,
  14522. #ifdef _WIN32
  14523. static_cast<const char *>(response.c_str()),
  14524. static_cast<int>(response.size()),
  14525. #else
  14526. response.c_str(), response.size(),
  14527. #endif
  14528. 0);
  14529. detail::close_socket(cli);
  14530. }
  14531. detail::close_socket(srv);
  14532. });
  14533. }
  14534. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  14535. #ifndef _WIN32
  14536. signal(SIGPIPE, SIG_IGN);
  14537. #endif
  14538. std::promise<int> port_promise;
  14539. auto port_future = port_promise.get_future();
  14540. auto server_thread =
  14541. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  14542. "Content-Type: text/plain\r\n"
  14543. "Content-Length: not-a-number\r\n"
  14544. "Connection: close\r\n"
  14545. "\r\n"
  14546. "hello");
  14547. auto port = port_future.get();
  14548. ASSERT_GT(port, 0);
  14549. Client cli("127.0.0.1", port);
  14550. auto handle = cli.open_stream("GET", "/");
  14551. EXPECT_FALSE(handle.is_valid());
  14552. server_thread.join();
  14553. }
  14554. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14555. #ifndef _WIN32
  14556. signal(SIGPIPE, SIG_IGN);
  14557. #endif
  14558. std::promise<int> port_promise;
  14559. auto port_future = port_promise.get_future();
  14560. auto server_thread = serve_single_response(
  14561. port_promise, "HTTP/1.1 200 OK\r\n"
  14562. "Content-Type: text/plain\r\n"
  14563. "Content-Length: 99999999999999999999999999\r\n"
  14564. "Connection: close\r\n"
  14565. "\r\n"
  14566. "hello");
  14567. auto port = port_future.get();
  14568. ASSERT_GT(port, 0);
  14569. // Historically std::stoull would throw std::out_of_range here and crash
  14570. // the process, then parsing silently clamped to a bogus framing length and
  14571. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  14572. // so the stream fails to open, matching the not-a-number case above. The
  14573. // process still must NOT terminate.
  14574. Client cli("127.0.0.1", port);
  14575. auto handle = cli.open_stream("GET", "/");
  14576. EXPECT_FALSE(handle.is_valid());
  14577. server_thread.join();
  14578. }
  14579. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14580. TEST_F(OpenStreamTest, Gzip) {
  14581. Client cli("127.0.0.1", port_);
  14582. auto handle = cli.open_stream("GET", "/compressible", {},
  14583. {{"Accept-Encoding", "gzip"}});
  14584. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  14585. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14586. }
  14587. #endif
  14588. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14589. TEST_F(OpenStreamTest, Brotli) {
  14590. Client cli("127.0.0.1", port_);
  14591. auto handle =
  14592. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  14593. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  14594. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14595. }
  14596. #endif
  14597. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14598. TEST_F(OpenStreamTest, Zstd) {
  14599. Client cli("127.0.0.1", port_);
  14600. auto handle = cli.open_stream("GET", "/compressible", {},
  14601. {{"Accept-Encoding", "zstd"}});
  14602. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  14603. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14604. }
  14605. #endif
  14606. #ifdef CPPHTTPLIB_SSL_ENABLED
  14607. class SSLOpenStreamTest : public ::testing::Test {
  14608. protected:
  14609. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  14610. void SetUp() override {
  14611. svr_.Get("/hello", [](const Request &, Response &res) {
  14612. res.set_content("Hello SSL World!", "text/plain");
  14613. });
  14614. svr_.Get("/chunked", [](const Request &, Response &res) {
  14615. res.set_chunked_content_provider("text/plain",
  14616. [](size_t offset, DataSink &sink) {
  14617. if (offset < 15) {
  14618. sink.write("chunk", 5);
  14619. return true;
  14620. }
  14621. sink.done();
  14622. return true;
  14623. });
  14624. });
  14625. svr_.Post("/echo", [](const Request &req, Response &res) {
  14626. res.set_content(req.body, req.get_header_value("Content-Type"));
  14627. });
  14628. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  14629. std::string body = req.body;
  14630. res.set_chunked_content_provider(
  14631. "text/plain", [body](size_t offset, DataSink &sink) {
  14632. if (offset < body.size()) {
  14633. sink.write(body.data() + offset, body.size() - offset);
  14634. }
  14635. sink.done();
  14636. return true;
  14637. });
  14638. });
  14639. port_ = svr_.bind_to_any_port("127.0.0.1");
  14640. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14641. svr_.wait_until_ready();
  14642. }
  14643. void TearDown() override {
  14644. svr_.stop();
  14645. if (thread_.joinable()) thread_.join();
  14646. }
  14647. SSLServer svr_;
  14648. std::thread thread_;
  14649. int port_ = 0;
  14650. };
  14651. TEST_F(SSLOpenStreamTest, Basic) {
  14652. SSLClient cli("127.0.0.1", port_);
  14653. cli.enable_server_certificate_verification(false);
  14654. auto handle = cli.open_stream("GET", "/hello");
  14655. ASSERT_TRUE(handle.is_valid());
  14656. EXPECT_EQ("Hello SSL World!", read_all(handle));
  14657. }
  14658. TEST_F(SSLOpenStreamTest, Chunked) {
  14659. SSLClient cli("127.0.0.1", port_);
  14660. cli.enable_server_certificate_verification(false);
  14661. auto handle = cli.open_stream("GET", "/chunked");
  14662. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14663. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14664. "Transfer-Encoding") == "chunked");
  14665. auto body = read_all(handle);
  14666. EXPECT_EQ("chunkchunkchunk", body);
  14667. }
  14668. TEST_F(SSLOpenStreamTest, Post) {
  14669. SSLClient cli("127.0.0.1", port_);
  14670. cli.enable_server_certificate_verification(false);
  14671. auto handle =
  14672. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  14673. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14674. EXPECT_EQ(200, handle.response->status);
  14675. auto body = read_all(handle);
  14676. EXPECT_EQ("Hello SSL POST", body);
  14677. }
  14678. TEST_F(SSLOpenStreamTest, PostChunked) {
  14679. SSLClient cli("127.0.0.1", port_);
  14680. cli.enable_server_certificate_verification(false);
  14681. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  14682. "Chunked SSL Data", "text/plain");
  14683. ASSERT_TRUE(handle.is_valid());
  14684. EXPECT_EQ(200, handle.response->status);
  14685. auto body = read_all(handle);
  14686. EXPECT_EQ("Chunked SSL Data", body);
  14687. }
  14688. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  14689. // Content-Length is terminated by the server closing the connection. When the
  14690. // SSL peer sends a close_notify after the body, the client must treat it as a
  14691. // clean EOF and return a successful response rather than an error.
  14692. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  14693. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14694. ASSERT_TRUE(svr.is_valid());
  14695. svr.set_keep_alive_max_count(1);
  14696. const std::string expected_body = "Hello from connection-close response!";
  14697. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  14698. res.set_content_provider("text/plain",
  14699. [&](size_t offset, DataSink &sink) -> bool {
  14700. if (offset < expected_body.size()) {
  14701. sink.write(expected_body.data() + offset,
  14702. expected_body.size() - offset);
  14703. }
  14704. sink.done();
  14705. return true;
  14706. });
  14707. });
  14708. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  14709. auto se = detail::scope_exit([&] {
  14710. svr.stop();
  14711. listen_thread.join();
  14712. ASSERT_FALSE(svr.is_running());
  14713. });
  14714. svr.wait_until_ready();
  14715. SSLClient cli(HOST, PORT);
  14716. cli.enable_server_certificate_verification(false);
  14717. auto res = cli.Get("/no-content-length");
  14718. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  14719. EXPECT_EQ(StatusCode::OK_200, res->status);
  14720. EXPECT_EQ(expected_body, res->body);
  14721. }
  14722. #endif // CPPHTTPLIB_SSL_ENABLED
  14723. //==============================================================================
  14724. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  14725. // results for various scenarios.
  14726. //==============================================================================
  14727. TEST(ParityTest, GetVsOpenStream) {
  14728. Server svr;
  14729. const std::string path = "/parity";
  14730. const std::string content = "Parity test content: hello world";
  14731. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14732. res.set_content(content, "text/plain");
  14733. });
  14734. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14735. auto se = detail::scope_exit([&] {
  14736. svr.stop();
  14737. t.join();
  14738. ASSERT_FALSE(svr.is_running());
  14739. });
  14740. svr.wait_until_ready();
  14741. Client cli(HOST, PORT);
  14742. // Non-stream path
  14743. auto r1 = cli.Get(path);
  14744. ASSERT_TRUE(r1);
  14745. EXPECT_EQ(StatusCode::OK_200, r1->status);
  14746. // Stream path
  14747. auto h = cli.open_stream("GET", path);
  14748. ASSERT_TRUE(h.is_valid());
  14749. EXPECT_EQ(r1->body, read_all(h));
  14750. }
  14751. // Helper to compress data with provided compressor type T
  14752. template <typename Compressor>
  14753. static std::string compress_payload_for_parity(const std::string &in) {
  14754. std::string out;
  14755. Compressor compressor;
  14756. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14757. [&](const char *data, size_t n) {
  14758. out.append(data, n);
  14759. return true;
  14760. });
  14761. EXPECT_TRUE(ok);
  14762. return out;
  14763. }
  14764. // Helper function for compression parity tests
  14765. template <typename Compressor>
  14766. static void test_compression_parity(const std::string &original,
  14767. const std::string &path,
  14768. const std::string &encoding) {
  14769. const std::string compressed =
  14770. compress_payload_for_parity<Compressor>(original);
  14771. Server svr;
  14772. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14773. res.set_content(compressed, "application/octet-stream");
  14774. res.set_header("Content-Encoding", encoding);
  14775. });
  14776. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14777. auto se = detail::scope_exit([&] {
  14778. svr.stop();
  14779. t.join();
  14780. ASSERT_FALSE(svr.is_running());
  14781. });
  14782. svr.wait_until_ready();
  14783. Client cli(HOST, PORT);
  14784. // Non-streaming
  14785. {
  14786. auto res = cli.Get(path);
  14787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14788. EXPECT_EQ(StatusCode::OK_200, res->status);
  14789. EXPECT_EQ(original, res->body);
  14790. }
  14791. // Streaming
  14792. {
  14793. auto h = cli.open_stream("GET", path);
  14794. ASSERT_TRUE(h.is_valid());
  14795. EXPECT_EQ(original, read_all(h));
  14796. }
  14797. }
  14798. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14799. TEST(ParityTest, Gzip) {
  14800. test_compression_parity<detail::gzip_compressor>(
  14801. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14802. }
  14803. #endif
  14804. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14805. TEST(ParityTest, Brotli) {
  14806. test_compression_parity<detail::brotli_compressor>(
  14807. "Hello, brotli parity test payload", "/parity-br", "br");
  14808. }
  14809. #endif
  14810. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14811. TEST(ParityTest, Zstd) {
  14812. test_compression_parity<detail::zstd_compressor>(
  14813. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14814. }
  14815. #endif
  14816. //==============================================================================
  14817. // New Stream API Tests
  14818. //==============================================================================
  14819. inline std::string read_body(httplib::stream::Result &result) {
  14820. std::string body;
  14821. while (result.next()) {
  14822. body.append(result.data(), result.size());
  14823. }
  14824. return body;
  14825. }
  14826. TEST(ClientConnectionTest, Basic) {
  14827. httplib::ClientConnection conn;
  14828. EXPECT_FALSE(conn.is_open());
  14829. conn.sock = 1;
  14830. EXPECT_TRUE(conn.is_open());
  14831. httplib::ClientConnection conn2(std::move(conn));
  14832. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14833. conn2.sock = INVALID_SOCKET;
  14834. }
  14835. // Unified test server for all stream::* tests
  14836. class StreamApiTest : public ::testing::Test {
  14837. protected:
  14838. void SetUp() override {
  14839. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14840. res.set_content("Hello World!", "text/plain");
  14841. });
  14842. svr_.Get("/echo-params",
  14843. [](const httplib::Request &req, httplib::Response &res) {
  14844. std::string r;
  14845. for (const auto &p : req.params) {
  14846. if (!r.empty()) r += "&";
  14847. r += p.first + "=" + p.second;
  14848. }
  14849. res.set_content(r, "text/plain");
  14850. });
  14851. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14852. res.set_content(req.body, req.get_header_value("Content-Type"));
  14853. });
  14854. svr_.Post("/echo-headers",
  14855. [](const httplib::Request &req, httplib::Response &res) {
  14856. std::string r;
  14857. for (const auto &h : req.headers)
  14858. r += h.first + ": " + h.second + "\n";
  14859. res.set_content(r, "text/plain");
  14860. });
  14861. svr_.Post("/echo-params",
  14862. [](const httplib::Request &req, httplib::Response &res) {
  14863. std::string r = "params:";
  14864. for (const auto &p : req.params)
  14865. r += p.first + "=" + p.second + ";";
  14866. res.set_content(r + " body:" + req.body, "text/plain");
  14867. });
  14868. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14869. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14870. });
  14871. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14872. res.set_content("PUT:" + req.body, "text/plain");
  14873. });
  14874. svr_.Patch("/echo",
  14875. [](const httplib::Request &req, httplib::Response &res) {
  14876. res.set_content("PATCH:" + req.body, "text/plain");
  14877. });
  14878. svr_.Delete(
  14879. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14880. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14881. "text/plain");
  14882. });
  14883. svr_.Get("/head-test",
  14884. [](const httplib::Request &, httplib::Response &res) {
  14885. res.set_content("body for HEAD", "text/plain");
  14886. });
  14887. svr_.Options("/options",
  14888. [](const httplib::Request &, httplib::Response &res) {
  14889. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14890. });
  14891. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14892. svr_.wait_until_ready();
  14893. }
  14894. void TearDown() override {
  14895. svr_.stop();
  14896. if (thread_.joinable()) thread_.join();
  14897. }
  14898. httplib::Server svr_;
  14899. std::thread thread_;
  14900. };
  14901. // stream::Get tests
  14902. TEST_F(StreamApiTest, GetBasic) {
  14903. httplib::Client cli(HOST, PORT);
  14904. auto result = httplib::stream::Get(cli, "/hello");
  14905. ASSERT_TRUE(result.is_valid());
  14906. EXPECT_EQ(200, result.status());
  14907. EXPECT_EQ("Hello World!", read_body(result));
  14908. }
  14909. TEST_F(StreamApiTest, GetWithParams) {
  14910. httplib::Client cli(HOST, PORT);
  14911. httplib::Params params{{"foo", "bar"}};
  14912. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14913. ASSERT_TRUE(result.is_valid());
  14914. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14915. }
  14916. TEST_F(StreamApiTest, GetConnectionError) {
  14917. httplib::Client cli(HOST, 9999);
  14918. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14919. }
  14920. TEST_F(StreamApiTest, Get404) {
  14921. httplib::Client cli(HOST, PORT);
  14922. auto result = httplib::stream::Get(cli, "/nonexistent");
  14923. EXPECT_TRUE(result.is_valid());
  14924. EXPECT_EQ(404, result.status());
  14925. }
  14926. // stream::Post tests
  14927. TEST_F(StreamApiTest, PostBasic) {
  14928. httplib::Client cli(HOST, PORT);
  14929. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14930. "application/json");
  14931. ASSERT_TRUE(result.is_valid());
  14932. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14933. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14934. }
  14935. TEST_F(StreamApiTest, PostWithHeaders) {
  14936. httplib::Client cli(HOST, PORT);
  14937. httplib::Headers headers{{"X-Custom", "value"}};
  14938. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14939. "text/plain");
  14940. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14941. }
  14942. TEST_F(StreamApiTest, PostWithParams) {
  14943. httplib::Client cli(HOST, PORT);
  14944. httplib::Params params{{"k", "v"}};
  14945. auto result =
  14946. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14947. auto body = read_body(result);
  14948. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14949. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14950. }
  14951. TEST_F(StreamApiTest, PostLarge) {
  14952. httplib::Client cli(HOST, PORT);
  14953. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14954. size_t total = 0;
  14955. while (result.next()) {
  14956. total += result.size();
  14957. }
  14958. EXPECT_EQ(100u * 1024u, total);
  14959. }
  14960. // stream::Put/Patch tests
  14961. TEST_F(StreamApiTest, PutAndPatch) {
  14962. httplib::Client cli(HOST, PORT);
  14963. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14964. EXPECT_EQ("PUT:test", read_body(put));
  14965. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14966. EXPECT_EQ("PATCH:test", read_body(patch));
  14967. }
  14968. // stream::Delete tests
  14969. TEST_F(StreamApiTest, Delete) {
  14970. httplib::Client cli(HOST, PORT);
  14971. auto del1 = httplib::stream::Delete(cli, "/resource");
  14972. EXPECT_EQ("Deleted", read_body(del1));
  14973. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14974. EXPECT_EQ("Deleted:data", read_body(del2));
  14975. }
  14976. // stream::Head/Options tests
  14977. TEST_F(StreamApiTest, HeadAndOptions) {
  14978. httplib::Client cli(HOST, PORT);
  14979. auto head = httplib::stream::Head(cli, "/head-test");
  14980. EXPECT_TRUE(head.is_valid());
  14981. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14982. auto opts = httplib::stream::Options(cli, "/options");
  14983. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14984. }
  14985. // SSL stream::* tests
  14986. #ifdef CPPHTTPLIB_SSL_ENABLED
  14987. class SSLStreamApiTest : public ::testing::Test {
  14988. protected:
  14989. void SetUp() override {
  14990. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14991. res.set_content("Hello SSL!", "text/plain");
  14992. });
  14993. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14994. res.set_content(req.body, "text/plain");
  14995. });
  14996. port_ = svr_.bind_to_any_port("127.0.0.1");
  14997. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14998. svr_.wait_until_ready();
  14999. }
  15000. void TearDown() override {
  15001. svr_.stop();
  15002. if (thread_.joinable()) thread_.join();
  15003. }
  15004. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  15005. std::thread thread_;
  15006. int port_ = 0;
  15007. };
  15008. TEST_F(SSLStreamApiTest, GetAndPost) {
  15009. httplib::SSLClient cli("127.0.0.1", port_);
  15010. cli.enable_server_certificate_verification(false);
  15011. auto get = httplib::stream::Get(cli, "/hello");
  15012. EXPECT_EQ("Hello SSL!", read_body(get));
  15013. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  15014. EXPECT_EQ("test", read_body(post));
  15015. }
  15016. #endif
  15017. // Tests for Error::Timeout and Error::ConnectionClosed error types
  15018. // These errors are set in SocketStream/SSLSocketStream and propagated through
  15019. // BodyReader
  15020. TEST(ErrorHandlingTest, StreamReadTimeout) {
  15021. // Test that read timeout during streaming is detected
  15022. // Use a large content-length response where server delays mid-stream
  15023. Server svr;
  15024. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15025. // Send a large response with delay in the middle
  15026. res.set_content_provider(
  15027. 1000, // content_length
  15028. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  15029. if (offset < 100) {
  15030. // Send first 100 bytes immediately
  15031. std::string data(100, 'A');
  15032. sink.write(data.c_str(), data.size());
  15033. return true;
  15034. }
  15035. // Then delay longer than client timeout
  15036. std::this_thread::sleep_for(std::chrono::seconds(3));
  15037. std::string data(900, 'B');
  15038. sink.write(data.c_str(), data.size());
  15039. return true;
  15040. });
  15041. });
  15042. auto port = 8091;
  15043. std::thread t([&]() { svr.listen("localhost", port); });
  15044. svr.wait_until_ready();
  15045. Client cli("localhost", port);
  15046. cli.set_read_timeout(1, 0); // 1 second timeout
  15047. auto handle = cli.open_stream("GET", "/slow-stream");
  15048. ASSERT_TRUE(handle.is_valid());
  15049. char buf[256];
  15050. ssize_t total = 0;
  15051. ssize_t n;
  15052. bool got_error = false;
  15053. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15054. total += n;
  15055. }
  15056. if (n < 0) {
  15057. got_error = true;
  15058. // Should be timeout or read error
  15059. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15060. handle.get_read_error() == Error::Read)
  15061. << "Actual error: " << to_string(handle.get_read_error());
  15062. }
  15063. // Either we got an error, or we got less data than expected
  15064. EXPECT_TRUE(got_error || total < 1000)
  15065. << "Expected timeout but got all " << total << " bytes";
  15066. svr.stop();
  15067. t.join();
  15068. }
  15069. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  15070. // Test connection closed detection via BodyReader
  15071. Server svr;
  15072. std::atomic<bool> close_now{false};
  15073. svr.Get("/will-close", [&](const Request &, Response &res) {
  15074. res.set_content_provider(
  15075. 10000, // Large content_length that we won't fully send
  15076. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15077. if (offset < 100) {
  15078. std::string data(100, 'X');
  15079. sink.write(data.c_str(), data.size());
  15080. return true;
  15081. }
  15082. // Wait for signal then abort
  15083. while (!close_now) {
  15084. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15085. }
  15086. return false; // Abort - server will close connection
  15087. });
  15088. });
  15089. auto port = 8092;
  15090. std::thread t([&]() { svr.listen("localhost", port); });
  15091. svr.wait_until_ready();
  15092. Client cli("localhost", port);
  15093. auto handle = cli.open_stream("GET", "/will-close");
  15094. ASSERT_TRUE(handle.is_valid());
  15095. char buf[256];
  15096. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15097. EXPECT_GT(n, 0) << "First read should succeed";
  15098. // Signal server to close
  15099. close_now = true;
  15100. // Keep reading until error or EOF
  15101. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15102. // Keep reading
  15103. }
  15104. // Should get an error since content_length wasn't satisfied
  15105. if (n < 0) {
  15106. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15107. handle.get_read_error() == Error::Read)
  15108. << "Actual error: " << to_string(handle.get_read_error());
  15109. }
  15110. svr.stop();
  15111. t.join();
  15112. }
  15113. #ifdef CPPHTTPLIB_SSL_ENABLED
  15114. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  15115. // Test that read timeout during SSL streaming is detected
  15116. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15117. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15118. res.set_content_provider(
  15119. 1000, "text/plain",
  15120. [](size_t offset, size_t /*length*/, DataSink &sink) {
  15121. if (offset < 100) {
  15122. std::string data(100, 'A');
  15123. sink.write(data.c_str(), data.size());
  15124. return true;
  15125. }
  15126. std::this_thread::sleep_for(std::chrono::seconds(3));
  15127. std::string data(900, 'B');
  15128. sink.write(data.c_str(), data.size());
  15129. return true;
  15130. });
  15131. });
  15132. auto port = 8093;
  15133. std::thread t([&]() { svr.listen("localhost", port); });
  15134. svr.wait_until_ready();
  15135. SSLClient cli("localhost", port);
  15136. cli.enable_server_certificate_verification(false);
  15137. cli.set_read_timeout(1, 0); // 1 second timeout
  15138. auto handle = cli.open_stream("GET", "/slow-stream");
  15139. ASSERT_TRUE(handle.is_valid());
  15140. char buf[256];
  15141. ssize_t total = 0;
  15142. ssize_t n;
  15143. bool got_error = false;
  15144. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15145. total += n;
  15146. }
  15147. if (n < 0) {
  15148. got_error = true;
  15149. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15150. handle.get_read_error() == Error::Read)
  15151. << "Actual error: " << to_string(handle.get_read_error());
  15152. }
  15153. EXPECT_TRUE(got_error || total < 1000)
  15154. << "Expected timeout but got all " << total << " bytes";
  15155. svr.stop();
  15156. t.join();
  15157. }
  15158. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  15159. // Test SSL connection closed detection
  15160. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15161. std::atomic<bool> close_now{false};
  15162. svr.Get("/will-close", [&](const Request &, Response &res) {
  15163. res.set_content_provider(
  15164. 10000, "text/plain",
  15165. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15166. if (offset < 100) {
  15167. std::string data(100, 'X');
  15168. sink.write(data.c_str(), data.size());
  15169. return true;
  15170. }
  15171. while (!close_now) {
  15172. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15173. }
  15174. return false;
  15175. });
  15176. });
  15177. auto port = 8094;
  15178. std::thread t([&]() { svr.listen("localhost", port); });
  15179. svr.wait_until_ready();
  15180. SSLClient cli("localhost", port);
  15181. cli.enable_server_certificate_verification(false);
  15182. auto handle = cli.open_stream("GET", "/will-close");
  15183. ASSERT_TRUE(handle.is_valid());
  15184. char buf[256];
  15185. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15186. EXPECT_GT(n, 0);
  15187. // Signal server to close
  15188. close_now = true;
  15189. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15190. // Keep reading
  15191. }
  15192. if (n < 0) {
  15193. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15194. handle.get_read_error() == Error::Read)
  15195. << "Actual error: " << to_string(handle.get_read_error());
  15196. }
  15197. svr.stop();
  15198. t.join();
  15199. }
  15200. #endif
  15201. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  15202. using namespace httplib;
  15203. // Create a test file
  15204. const char *fname = "etag_testfile.txt";
  15205. const char *content = "etag-content";
  15206. {
  15207. std::ofstream ofs(fname);
  15208. ofs << content;
  15209. ASSERT_TRUE(ofs.good());
  15210. }
  15211. Server svr;
  15212. svr.set_mount_point("/static", ".");
  15213. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15214. svr.wait_until_ready();
  15215. Client cli(HOST, PORT);
  15216. // First request: should get 200 with ETag header
  15217. auto res1 = cli.Get("/static/etag_testfile.txt");
  15218. ASSERT_TRUE(res1);
  15219. ASSERT_EQ(200, res1->status);
  15220. ASSERT_TRUE(res1->has_header("ETag"));
  15221. std::string etag = res1->get_header_value("ETag");
  15222. EXPECT_FALSE(etag.empty());
  15223. // Verify ETag format: W/"hex-hex"
  15224. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  15225. EXPECT_EQ('W', etag[0]);
  15226. EXPECT_EQ('/', etag[1]);
  15227. EXPECT_EQ('"', etag[2]);
  15228. EXPECT_EQ('"', etag.back());
  15229. // Exact match: expect 304 Not Modified
  15230. Headers h2 = {{"If-None-Match", etag}};
  15231. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  15232. ASSERT_TRUE(res2);
  15233. EXPECT_EQ(304, res2->status);
  15234. // Wildcard match: expect 304 Not Modified
  15235. Headers h3 = {{"If-None-Match", "*"}};
  15236. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  15237. ASSERT_TRUE(res3);
  15238. EXPECT_EQ(304, res3->status);
  15239. // Non-matching ETag: expect 200
  15240. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  15241. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  15242. ASSERT_TRUE(res4);
  15243. EXPECT_EQ(200, res4->status);
  15244. // Multiple ETags with one matching: expect 304
  15245. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  15246. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  15247. ASSERT_TRUE(res5);
  15248. EXPECT_EQ(304, res5->status);
  15249. svr.stop();
  15250. t.join();
  15251. std::remove(fname);
  15252. }
  15253. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  15254. using namespace httplib;
  15255. Server svr;
  15256. svr.set_mount_point("/static", ".");
  15257. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15258. svr.wait_until_ready();
  15259. Client cli(HOST, PORT);
  15260. // Send If-None-Match: * to a non-existent file
  15261. Headers h = {{"If-None-Match", "*"}};
  15262. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  15263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15264. EXPECT_EQ(404, res->status);
  15265. svr.stop();
  15266. t.join();
  15267. }
  15268. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  15269. using namespace httplib;
  15270. // Create a test file
  15271. const char *fname = "etag_boundary_testfile.txt";
  15272. const char *content = "boundary-test";
  15273. {
  15274. std::ofstream ofs(fname);
  15275. ofs << content;
  15276. ASSERT_TRUE(ofs.good());
  15277. }
  15278. Server svr;
  15279. svr.set_mount_point("/static", ".");
  15280. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15281. svr.wait_until_ready();
  15282. Client cli(HOST, PORT);
  15283. // Get the actual ETag
  15284. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  15285. ASSERT_TRUE(res1);
  15286. ASSERT_EQ(200, res1->status);
  15287. ASSERT_TRUE(res1->has_header("ETag"));
  15288. std::string etag = res1->get_header_value("ETag");
  15289. // Test 1: Very long ETag value (longer than actual ETag)
  15290. // Should NOT match and return 200 (not trigger out-of-bounds read)
  15291. Headers h1 = {{"If-None-Match", "W/"
  15292. "\"very-long-etag-value-that-is-much-longer-"
  15293. "than-the-actual-etag-value\""}};
  15294. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  15295. ASSERT_TRUE(res2);
  15296. EXPECT_EQ(200, res2->status); // Should not match
  15297. // Test 2: Long string followed by wildcard
  15298. // Should match on "*" and return 304 (without out-of-bounds read on the long
  15299. // string)
  15300. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  15301. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  15302. ASSERT_TRUE(res3);
  15303. EXPECT_EQ(304, res3->status); // Should match on "*"
  15304. // Test 3: Wildcard followed by long string
  15305. // Should match on "*" immediately and return 304
  15306. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  15307. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  15308. ASSERT_TRUE(res4);
  15309. EXPECT_EQ(304, res4->status); // Should match on "*"
  15310. // Test 4: Multiple long non-matching values
  15311. // Should NOT match and return 200 (test that all comparisons are safe)
  15312. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  15313. "W/\"second-long-non-matching-value\", "
  15314. "W/\"third-long-non-matching-value\""}};
  15315. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  15316. ASSERT_TRUE(res5);
  15317. EXPECT_EQ(200, res5->status); // Should not match
  15318. // Test 5: Single character that is not "*" (edge case)
  15319. Headers h5 = {{"If-None-Match", "X"}};
  15320. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  15321. ASSERT_TRUE(res6);
  15322. EXPECT_EQ(200, res6->status); // Should not match
  15323. svr.stop();
  15324. t.join();
  15325. std::remove(fname);
  15326. }
  15327. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  15328. using namespace httplib;
  15329. // Create a test file
  15330. const char *fname = "ims_testfile.txt";
  15331. const char *content = "if-modified-since-test";
  15332. {
  15333. std::ofstream ofs(fname);
  15334. ofs << content;
  15335. ASSERT_TRUE(ofs.good());
  15336. }
  15337. Server svr;
  15338. svr.set_mount_point("/static", ".");
  15339. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15340. svr.wait_until_ready();
  15341. Client cli(HOST, PORT);
  15342. // First request: should get 200 with Last-Modified header
  15343. auto res1 = cli.Get("/static/ims_testfile.txt");
  15344. ASSERT_TRUE(res1);
  15345. ASSERT_EQ(200, res1->status);
  15346. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15347. std::string last_modified = res1->get_header_value("Last-Modified");
  15348. EXPECT_FALSE(last_modified.empty());
  15349. // If-Modified-Since with same time: expect 304
  15350. Headers h2 = {{"If-Modified-Since", last_modified}};
  15351. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  15352. ASSERT_TRUE(res2);
  15353. EXPECT_EQ(304, res2->status);
  15354. // If-Modified-Since with future time: expect 304
  15355. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15356. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  15357. ASSERT_TRUE(res3);
  15358. EXPECT_EQ(304, res3->status);
  15359. // If-Modified-Since with past time: expect 200
  15360. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15361. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  15362. ASSERT_TRUE(res4);
  15363. EXPECT_EQ(200, res4->status);
  15364. // If-None-Match takes precedence over If-Modified-Since
  15365. // (send matching ETag with old If-Modified-Since -> should still be 304)
  15366. ASSERT_TRUE(res1->has_header("ETag"));
  15367. std::string etag = res1->get_header_value("ETag");
  15368. Headers h5 = {{"If-None-Match", etag},
  15369. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15370. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  15371. ASSERT_TRUE(res5);
  15372. EXPECT_EQ(304, res5->status);
  15373. svr.stop();
  15374. t.join();
  15375. std::remove(fname);
  15376. }
  15377. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  15378. using namespace httplib;
  15379. Server svr;
  15380. // Endpoint that returns compressible content
  15381. svr.Get("/compressible", [](const Request &, Response &res) {
  15382. // Return a large enough body to trigger compression
  15383. std::string body(1000, 'a');
  15384. res.set_content(body, "text/plain");
  15385. });
  15386. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15387. svr.wait_until_ready();
  15388. Client cli(HOST, PORT);
  15389. // Request with gzip support: should get Vary header when compressed
  15390. cli.set_compress(true);
  15391. auto res1 = cli.Get("/compressible");
  15392. ASSERT_TRUE(res1);
  15393. EXPECT_EQ(200, res1->status);
  15394. // If Content-Encoding is set, Vary should also be set
  15395. if (res1->has_header("Content-Encoding")) {
  15396. EXPECT_TRUE(res1->has_header("Vary"));
  15397. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  15398. }
  15399. // Request without Accept-Encoding header: should not have compression
  15400. Headers h_no_compress;
  15401. auto res2 = cli.Get("/compressible", h_no_compress);
  15402. ASSERT_TRUE(res2);
  15403. EXPECT_EQ(200, res2->status);
  15404. // Verify Vary header is present when compression is applied
  15405. // (the exact behavior depends on server configuration)
  15406. svr.stop();
  15407. t.join();
  15408. }
  15409. TEST(ETagTest, IfRangeWithETag) {
  15410. using namespace httplib;
  15411. // Create a test file with known content
  15412. const char *fname = "if_range_testfile.txt";
  15413. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15414. {
  15415. std::ofstream ofs(fname);
  15416. ofs << content;
  15417. ASSERT_TRUE(ofs.good());
  15418. }
  15419. Server svr;
  15420. svr.set_mount_point("/static", ".");
  15421. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15422. svr.wait_until_ready();
  15423. Client cli(HOST, PORT);
  15424. // First request: get ETag
  15425. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15426. ASSERT_TRUE(res1);
  15427. ASSERT_EQ(200, res1->status);
  15428. ASSERT_TRUE(res1->has_header("ETag"));
  15429. std::string etag = res1->get_header_value("ETag");
  15430. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15431. // Since our server generates weak ETags (W/"..."), If-Range with our
  15432. // ETag should NOT result in partial content - it should return full content.
  15433. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15434. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15435. ASSERT_TRUE(res2);
  15436. // Weak ETag in If-Range -> full content (200), not partial (206)
  15437. EXPECT_EQ(200, res2->status);
  15438. EXPECT_EQ(content, res2->body);
  15439. EXPECT_FALSE(res2->has_header("Content-Range"));
  15440. // Range request with non-matching If-Range (ETag): should get 200 (full
  15441. // content)
  15442. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15443. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15444. ASSERT_TRUE(res3);
  15445. EXPECT_EQ(200, res3->status);
  15446. EXPECT_EQ(content, res3->body);
  15447. EXPECT_FALSE(res3->has_header("Content-Range"));
  15448. // Range request with strong ETag (hypothetical - our server doesn't generate
  15449. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15450. // should return full content)
  15451. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15452. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15453. ASSERT_TRUE(res4);
  15454. EXPECT_EQ(200, res4->status);
  15455. EXPECT_EQ(content, res4->body);
  15456. EXPECT_FALSE(res4->has_header("Content-Range"));
  15457. svr.stop();
  15458. t.join();
  15459. std::remove(fname);
  15460. }
  15461. TEST(ETagTest, IfRangeWithDate) {
  15462. using namespace httplib;
  15463. // Create a test file
  15464. const char *fname = "if_range_date_testfile.txt";
  15465. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15466. {
  15467. std::ofstream ofs(fname);
  15468. ofs << content;
  15469. ASSERT_TRUE(ofs.good());
  15470. }
  15471. Server svr;
  15472. svr.set_mount_point("/static", ".");
  15473. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15474. svr.wait_until_ready();
  15475. Client cli(HOST, PORT);
  15476. // First request: get Last-Modified
  15477. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  15478. ASSERT_TRUE(res1);
  15479. ASSERT_EQ(200, res1->status);
  15480. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15481. std::string last_modified = res1->get_header_value("Last-Modified");
  15482. // Range request with matching If-Range (date): should get 206
  15483. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  15484. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  15485. ASSERT_TRUE(res2);
  15486. EXPECT_EQ(206, res2->status);
  15487. EXPECT_EQ("FGHIJ", res2->body);
  15488. // Range request with old If-Range date: should get 200 (full content)
  15489. Headers h3 = {{"Range", "bytes=5-9"},
  15490. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15491. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  15492. ASSERT_TRUE(res3);
  15493. EXPECT_EQ(200, res3->status);
  15494. EXPECT_EQ(content, res3->body);
  15495. // Range request with future If-Range date: should get 206
  15496. Headers h4 = {{"Range", "bytes=0-4"},
  15497. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15498. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  15499. ASSERT_TRUE(res4);
  15500. EXPECT_EQ(206, res4->status);
  15501. EXPECT_EQ("ABCDE", res4->body);
  15502. svr.stop();
  15503. t.join();
  15504. std::remove(fname);
  15505. }
  15506. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  15507. using namespace httplib;
  15508. const char *fname = "etag_malformed.txt";
  15509. const char *content = "malformed-etag";
  15510. {
  15511. std::ofstream ofs(fname);
  15512. ofs << content;
  15513. ASSERT_TRUE(ofs.good());
  15514. }
  15515. Server svr;
  15516. svr.set_mount_point("/static", ".");
  15517. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15518. svr.wait_until_ready();
  15519. Client cli(HOST, PORT);
  15520. // baseline: should get 200 and an ETag
  15521. auto res1 = cli.Get("/static/etag_malformed.txt");
  15522. ASSERT_TRUE(res1);
  15523. ASSERT_EQ(200, res1->status);
  15524. ASSERT_TRUE(res1->has_header("ETag"));
  15525. // Malformed ETag value (missing quotes) should be treated as non-matching
  15526. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  15527. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  15528. ASSERT_TRUE(res_bad);
  15529. EXPECT_EQ(200, res_bad->status);
  15530. // Whitespace-only header value should be considered invalid / non-matching
  15531. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  15532. "Host: localhost\r\n"
  15533. "If-None-Match: \r\n"
  15534. "Connection: close\r\n"
  15535. "\r\n";
  15536. std::string out;
  15537. ASSERT_TRUE(send_request(5, raw_req, &out));
  15538. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15539. svr.stop();
  15540. t.join();
  15541. std::remove(fname);
  15542. }
  15543. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  15544. using namespace httplib;
  15545. const char *fname = "ims_invalid_format.txt";
  15546. const char *content = "ims-bad-format";
  15547. {
  15548. std::ofstream ofs(fname);
  15549. ofs << content;
  15550. ASSERT_TRUE(ofs.good());
  15551. }
  15552. Server svr;
  15553. svr.set_mount_point("/static", ".");
  15554. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15555. svr.wait_until_ready();
  15556. Client cli(HOST, PORT);
  15557. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  15558. ASSERT_TRUE(res1);
  15559. ASSERT_EQ(200, res1->status);
  15560. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15561. // If-Modified-Since with invalid format should not result in 304
  15562. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  15563. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  15564. ASSERT_TRUE(res_bad);
  15565. EXPECT_EQ(200, res_bad->status);
  15566. // If-Range with invalid date format should be treated as mismatch -> full
  15567. // content (200)
  15568. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  15569. {"If-Range", "invalid-date"}};
  15570. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  15571. ASSERT_TRUE(res_ifrange);
  15572. EXPECT_EQ(200, res_ifrange->status);
  15573. svr.stop();
  15574. t.join();
  15575. std::remove(fname);
  15576. }
  15577. TEST(ETagTest, IfRangeWithMalformedETag) {
  15578. using namespace httplib;
  15579. const char *fname = "ifrange_malformed.txt";
  15580. const std::string content = "0123456789";
  15581. {
  15582. std::ofstream ofs(fname);
  15583. ofs << content;
  15584. ASSERT_TRUE(ofs.good());
  15585. }
  15586. Server svr;
  15587. svr.set_mount_point("/static", ".");
  15588. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15589. svr.wait_until_ready();
  15590. Client cli(HOST, PORT);
  15591. // First request: get ETag
  15592. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  15593. ASSERT_TRUE(res1);
  15594. ASSERT_EQ(200, res1->status);
  15595. ASSERT_TRUE(res1->has_header("ETag"));
  15596. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  15597. // full content (200)
  15598. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  15599. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  15600. ASSERT_TRUE(res2);
  15601. EXPECT_EQ(200, res2->status);
  15602. EXPECT_EQ(content, res2->body);
  15603. svr.stop();
  15604. t.join();
  15605. std::remove(fname);
  15606. }
  15607. TEST(ETagTest, ExtremeLargeDateValues) {
  15608. using namespace httplib;
  15609. const char *fname = "ims_extreme_date.txt";
  15610. const char *content = "ims-extreme-date";
  15611. {
  15612. std::ofstream ofs(fname);
  15613. ofs << content;
  15614. ASSERT_TRUE(ofs.good());
  15615. }
  15616. Server svr;
  15617. svr.set_mount_point("/static", ".");
  15618. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15619. svr.wait_until_ready();
  15620. Client cli(HOST, PORT);
  15621. auto res1 = cli.Get(std::string("/static/") + fname);
  15622. ASSERT_TRUE(res1);
  15623. ASSERT_EQ(200, res1->status);
  15624. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15625. // Extremely large year that may overflow date parsing routines.
  15626. Headers h_large_date = {
  15627. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15628. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  15629. ASSERT_TRUE(res_bad);
  15630. // Expect server to treat this as invalid/mismatch and return full content
  15631. EXPECT_EQ(200, res_bad->status);
  15632. // If-Range with extremely large date should be treated as mismatch -> full
  15633. // content (200)
  15634. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  15635. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15636. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  15637. ASSERT_TRUE(res_ifrange);
  15638. EXPECT_EQ(200, res_ifrange->status);
  15639. svr.stop();
  15640. t.join();
  15641. std::remove(fname);
  15642. }
  15643. TEST(ETagTest, NegativeFileModificationTime) {
  15644. using namespace httplib;
  15645. const char *fname = "ims_negative_mtime.txt";
  15646. const std::string content = "negative-mtime";
  15647. {
  15648. std::ofstream ofs(fname);
  15649. ofs << content;
  15650. ASSERT_TRUE(ofs.good());
  15651. }
  15652. // Try to set file mtime to a negative value. This may fail on some
  15653. // platforms/filesystems; if it fails, the test will still verify server
  15654. // behaves safely by performing a regular conditional request.
  15655. #if defined(__APPLE__) || defined(__linux__)
  15656. bool set_negative = false;
  15657. do {
  15658. struct timeval times[2];
  15659. // access time: now
  15660. times[0].tv_sec = time(nullptr);
  15661. times[0].tv_usec = 0;
  15662. // modification time: negative (e.g., -1)
  15663. times[1].tv_sec = -1;
  15664. times[1].tv_usec = 0;
  15665. if (utimes(fname, times) == 0) { set_negative = true; }
  15666. } while (0);
  15667. #else
  15668. bool set_negative = false;
  15669. #endif
  15670. Server svr;
  15671. svr.set_mount_point("/static", ".");
  15672. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15673. svr.wait_until_ready();
  15674. Client cli(HOST, PORT);
  15675. auto res1 = cli.Get(std::string("/static/") + fname);
  15676. ASSERT_TRUE(res1);
  15677. ASSERT_EQ(200, res1->status);
  15678. bool has_last_modified = res1->has_header("Last-Modified");
  15679. std::string last_modified;
  15680. if (has_last_modified) {
  15681. last_modified = res1->get_header_value("Last-Modified");
  15682. }
  15683. if (set_negative) {
  15684. // If we successfully set a negative mtime, ensure server returns a
  15685. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  15686. // with an old date and ensure server handles it without crash.
  15687. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  15688. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  15689. ASSERT_TRUE(res2);
  15690. // Behavior may vary; at minimum ensure server responds (200 or 304).
  15691. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  15692. } else {
  15693. // Could not set negative mtime on this platform; fall back to verifying
  15694. // that normal invalid/malformed dates are treated safely (non-304).
  15695. Headers h_bad_date = {
  15696. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15697. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  15698. ASSERT_TRUE(res_bad);
  15699. EXPECT_EQ(200, res_bad->status);
  15700. }
  15701. svr.stop();
  15702. t.join();
  15703. std::remove(fname);
  15704. }
  15705. //==============================================================================
  15706. // SSE Parsing Tests
  15707. //==============================================================================
  15708. class SSEParsingTest : public ::testing::Test {
  15709. protected:
  15710. // Test helper that mimics SSE parsing behavior
  15711. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  15712. int &retry_ms) {
  15713. // Blank line signals end of event
  15714. if (line.empty() || line == "\r") { return true; }
  15715. // Lines starting with ':' are comments (ignored)
  15716. if (!line.empty() && line[0] == ':') { return false; }
  15717. // Find the colon separator
  15718. auto colon_pos = line.find(':');
  15719. if (colon_pos == std::string::npos) {
  15720. // Line with no colon is treated as field name with empty value
  15721. return false;
  15722. }
  15723. std::string field = line.substr(0, colon_pos);
  15724. std::string value;
  15725. // Value starts after colon, skip optional single space
  15726. if (colon_pos + 1 < line.size()) {
  15727. size_t value_start = colon_pos + 1;
  15728. if (line[value_start] == ' ') { value_start++; }
  15729. value = line.substr(value_start);
  15730. // Remove trailing \r if present
  15731. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  15732. }
  15733. // Handle known fields
  15734. if (field == "event") {
  15735. msg.event = value;
  15736. } else if (field == "data") {
  15737. // Multiple data lines are concatenated with newlines
  15738. if (!msg.data.empty()) { msg.data += "\n"; }
  15739. msg.data += value;
  15740. } else if (field == "id") {
  15741. // Empty id is valid (clears the last event ID)
  15742. msg.id = value;
  15743. } else if (field == "retry") {
  15744. // Parse retry interval in milliseconds
  15745. {
  15746. int v = 0;
  15747. auto res =
  15748. detail::from_chars(value.data(), value.data() + value.size(), v);
  15749. if (res.ec == std::errc{}) { retry_ms = v; }
  15750. }
  15751. }
  15752. // Unknown fields are ignored per SSE spec
  15753. return false;
  15754. }
  15755. };
  15756. // Test: Single-line data
  15757. TEST_F(SSEParsingTest, SingleLineData) {
  15758. sse::SSEMessage msg;
  15759. int retry_ms = 3000;
  15760. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15761. EXPECT_EQ(msg.data, "hello");
  15762. EXPECT_EQ(msg.event, "message");
  15763. // Blank line ends event
  15764. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15765. }
  15766. // Test: Multi-line data
  15767. TEST_F(SSEParsingTest, MultiLineData) {
  15768. sse::SSEMessage msg;
  15769. int retry_ms = 3000;
  15770. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15771. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15772. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15773. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15774. }
  15775. // Test: Custom event types
  15776. TEST_F(SSEParsingTest, CustomEventType) {
  15777. sse::SSEMessage msg;
  15778. int retry_ms = 3000;
  15779. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15780. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15781. EXPECT_EQ(msg.event, "update");
  15782. EXPECT_EQ(msg.data, "payload");
  15783. }
  15784. // Test: Event ID handling
  15785. TEST_F(SSEParsingTest, EventIdHandling) {
  15786. sse::SSEMessage msg;
  15787. int retry_ms = 3000;
  15788. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15789. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15790. EXPECT_EQ(msg.id, "12345");
  15791. }
  15792. // Test: Empty event ID (clears last event ID)
  15793. TEST_F(SSEParsingTest, EmptyEventId) {
  15794. sse::SSEMessage msg;
  15795. msg.id = "previous";
  15796. int retry_ms = 3000;
  15797. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15798. EXPECT_EQ(msg.id, "");
  15799. }
  15800. // Test: Retry field parsing
  15801. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15802. sse::SSEMessage msg;
  15803. int retry_ms = 3000;
  15804. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15805. EXPECT_EQ(retry_ms, 5000);
  15806. }
  15807. // Test: Invalid retry value
  15808. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15809. sse::SSEMessage msg;
  15810. int retry_ms = 3000;
  15811. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15812. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15813. }
  15814. // Test: Comments (lines starting with :)
  15815. TEST_F(SSEParsingTest, CommentsIgnored) {
  15816. sse::SSEMessage msg;
  15817. int retry_ms = 3000;
  15818. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15819. EXPECT_EQ(msg.data, "");
  15820. EXPECT_EQ(msg.event, "message");
  15821. }
  15822. // Test: Colon in value
  15823. TEST_F(SSEParsingTest, ColonInValue) {
  15824. sse::SSEMessage msg;
  15825. int retry_ms = 3000;
  15826. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15827. EXPECT_EQ(msg.data, "hello:world:test");
  15828. }
  15829. // Test: Line with no colon (field name only)
  15830. TEST_F(SSEParsingTest, FieldNameOnly) {
  15831. sse::SSEMessage msg;
  15832. int retry_ms = 3000;
  15833. // According to SSE spec, this is treated as field name with empty value
  15834. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15835. // Since we don't recognize "data" without colon, data should be empty
  15836. EXPECT_EQ(msg.data, "");
  15837. }
  15838. // Test: Trailing \r handling
  15839. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15840. sse::SSEMessage msg;
  15841. int retry_ms = 3000;
  15842. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15843. EXPECT_EQ(msg.data, "hello");
  15844. }
  15845. // Test: Unknown fields ignored
  15846. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15847. sse::SSEMessage msg;
  15848. int retry_ms = 3000;
  15849. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15850. EXPECT_EQ(msg.data, "");
  15851. EXPECT_EQ(msg.event, "message");
  15852. }
  15853. // Test: Space after colon is optional
  15854. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15855. sse::SSEMessage msg1, msg2;
  15856. int retry_ms = 3000;
  15857. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15858. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15859. EXPECT_EQ(msg1.data, "hello");
  15860. EXPECT_EQ(msg2.data, "hello");
  15861. }
  15862. // Test: SSEMessage clear
  15863. TEST_F(SSEParsingTest, MessageClear) {
  15864. sse::SSEMessage msg;
  15865. msg.event = "custom";
  15866. msg.data = "some data";
  15867. msg.id = "123";
  15868. msg.clear();
  15869. EXPECT_EQ(msg.event, "message");
  15870. EXPECT_EQ(msg.data, "");
  15871. EXPECT_EQ(msg.id, "");
  15872. }
  15873. // Test: Complete event parsing
  15874. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15875. sse::SSEMessage msg;
  15876. int retry_ms = 3000;
  15877. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15878. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15879. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15880. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15881. // Blank line ends event
  15882. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15883. EXPECT_EQ(msg.event, "notification");
  15884. EXPECT_EQ(msg.id, "evt-42");
  15885. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15886. EXPECT_EQ(retry_ms, 1000);
  15887. }
  15888. //==============================================================================
  15889. // Integration Tests with Server
  15890. //==============================================================================
  15891. class SSEIntegrationTest : public ::testing::Test {
  15892. protected:
  15893. void SetUp() override {
  15894. stop_server_.store(false);
  15895. events_.clear();
  15896. server_ = httplib::detail::make_unique<Server>();
  15897. setup_server();
  15898. start_server();
  15899. }
  15900. void TearDown() override {
  15901. stop_server_.store(true);
  15902. event_cv_.notify_all();
  15903. server_->stop();
  15904. if (server_thread_.joinable()) { server_thread_.join(); }
  15905. }
  15906. void setup_server() {
  15907. // Simple SSE endpoint
  15908. server_->Get("/events", [this](const Request &req, Response &res) {
  15909. auto last_id = req.get_header_value("Last-Event-ID");
  15910. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15911. res.set_chunked_content_provider(
  15912. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15913. std::unique_lock<std::mutex> lock(event_mutex_);
  15914. if (event_cv_.wait_for(
  15915. lock, std::chrono::milliseconds(200), [this] {
  15916. return !events_.empty() || stop_server_.load();
  15917. })) {
  15918. if (stop_server_.load()) { return false; }
  15919. if (!events_.empty()) {
  15920. std::string event = events_.front();
  15921. events_.erase(events_.begin());
  15922. sink.write(event.data(), event.size());
  15923. return true;
  15924. }
  15925. }
  15926. return !stop_server_.load();
  15927. });
  15928. });
  15929. // Endpoint that returns error
  15930. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15931. res.status = 500;
  15932. res.set_content("Internal Server Error", "text/plain");
  15933. });
  15934. // Endpoint for custom event types
  15935. server_->Get("/custom-events", [](const Request &, Response &res) {
  15936. res.set_chunked_content_provider(
  15937. "text/event-stream", [](size_t offset, DataSink &sink) {
  15938. if (offset == 0) {
  15939. std::string event = "event: update\ndata: updated\n\n"
  15940. "event: delete\ndata: deleted\n\n";
  15941. sink.write(event.data(), event.size());
  15942. }
  15943. return false; // End stream after sending
  15944. });
  15945. });
  15946. }
  15947. void start_server() {
  15948. port_ = server_->bind_to_any_port(HOST);
  15949. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15950. // Wait for server to start
  15951. while (!server_->is_running()) {
  15952. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15953. }
  15954. }
  15955. int get_port() const { return port_; }
  15956. void send_event(const std::string &event) {
  15957. std::lock_guard<std::mutex> lock(event_mutex_);
  15958. events_.push_back(event);
  15959. event_cv_.notify_all();
  15960. }
  15961. std::unique_ptr<Server> server_;
  15962. std::thread server_thread_;
  15963. std::mutex event_mutex_;
  15964. std::condition_variable event_cv_;
  15965. std::vector<std::string> events_;
  15966. std::atomic<bool> stop_server_{false};
  15967. std::string last_received_event_id_;
  15968. int port_ = 0;
  15969. };
  15970. // Test: Successful connection and on_open callback
  15971. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15972. // Add a simple endpoint that sends one event and closes
  15973. server_->Get("/simple-event", [](const Request &, Response &res) {
  15974. res.set_chunked_content_provider(
  15975. "text/event-stream", [](size_t offset, DataSink &sink) {
  15976. if (offset == 0) {
  15977. std::string event = "data: hello\n\n";
  15978. sink.write(event.data(), event.size());
  15979. }
  15980. return false; // Close stream after sending
  15981. });
  15982. });
  15983. Client client("localhost", get_port());
  15984. sse::SSEClient sse(client, "/simple-event");
  15985. std::atomic<bool> open_called{false};
  15986. std::atomic<bool> message_received{false};
  15987. sse.on_open([&open_called]() { open_called.store(true); });
  15988. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15989. if (msg.data == "hello") { message_received.store(true); }
  15990. });
  15991. sse.set_reconnect_interval(100);
  15992. sse.set_max_reconnect_attempts(1);
  15993. // Start async
  15994. sse.start_async();
  15995. // Wait for message to be processed
  15996. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15997. sse.stop();
  15998. EXPECT_TRUE(open_called.load());
  15999. EXPECT_TRUE(message_received.load());
  16000. }
  16001. // Test: on_message callback
  16002. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  16003. // Endpoint that sends multiple events then closes
  16004. server_->Get("/multi-event", [](const Request &, Response &res) {
  16005. res.set_chunked_content_provider(
  16006. "text/event-stream", [](size_t offset, DataSink &sink) {
  16007. if (offset == 0) {
  16008. std::string events = "data: message1\n\ndata: message2\n\n";
  16009. sink.write(events.data(), events.size());
  16010. }
  16011. return false;
  16012. });
  16013. });
  16014. Client client("localhost", get_port());
  16015. sse::SSEClient sse(client, "/multi-event");
  16016. std::vector<std::string> received_messages;
  16017. std::mutex messages_mutex;
  16018. sse.on_message([&](const sse::SSEMessage &msg) {
  16019. std::lock_guard<std::mutex> lock(messages_mutex);
  16020. received_messages.push_back(msg.data);
  16021. });
  16022. sse.set_reconnect_interval(100);
  16023. sse.set_max_reconnect_attempts(1);
  16024. sse.start_async();
  16025. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16026. sse.stop();
  16027. std::lock_guard<std::mutex> lock(messages_mutex);
  16028. EXPECT_GE(received_messages.size(), 2u);
  16029. if (received_messages.size() >= 2) {
  16030. EXPECT_EQ(received_messages[0], "message1");
  16031. EXPECT_EQ(received_messages[1], "message2");
  16032. }
  16033. }
  16034. // Test: on_event for specific types
  16035. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  16036. Client client("localhost", get_port());
  16037. sse::SSEClient sse(client, "/custom-events");
  16038. std::atomic<bool> update_received{false};
  16039. std::atomic<bool> delete_received{false};
  16040. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  16041. if (msg.data == "updated") { update_received.store(true); }
  16042. });
  16043. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  16044. if (msg.data == "deleted") { delete_received.store(true); }
  16045. });
  16046. sse.set_max_reconnect_attempts(1);
  16047. sse.start_async();
  16048. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  16049. sse.stop();
  16050. EXPECT_TRUE(update_received.load());
  16051. EXPECT_TRUE(delete_received.load());
  16052. }
  16053. // Test: on_error callback on connection failure
  16054. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  16055. // Connect to a non-existent port
  16056. Client client("localhost", 59999);
  16057. sse::SSEClient sse(client, "/events");
  16058. std::atomic<bool> error_called{false};
  16059. Error received_error = Error::Success;
  16060. sse.on_error([&](Error err) {
  16061. error_called.store(true);
  16062. received_error = err;
  16063. });
  16064. sse.set_reconnect_interval(50);
  16065. sse.set_max_reconnect_attempts(1);
  16066. sse.start_async();
  16067. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16068. sse.stop();
  16069. EXPECT_TRUE(error_called.load());
  16070. EXPECT_NE(received_error, Error::Success);
  16071. }
  16072. // Test: Last-Event-ID header sent on reconnect
  16073. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  16074. // Endpoint that sends event with ID
  16075. server_->Get("/event-with-id", [](const Request &, Response &res) {
  16076. res.set_chunked_content_provider(
  16077. "text/event-stream", [](size_t offset, DataSink &sink) {
  16078. if (offset == 0) {
  16079. std::string event = "id: evt-123\ndata: test\n\n";
  16080. sink.write(event.data(), event.size());
  16081. }
  16082. return false;
  16083. });
  16084. });
  16085. Client client("localhost", get_port());
  16086. sse::SSEClient sse(client, "/event-with-id");
  16087. std::atomic<bool> id_received{false};
  16088. sse.on_message([&](const sse::SSEMessage &msg) {
  16089. if (!msg.id.empty()) { id_received.store(true); }
  16090. });
  16091. sse.set_reconnect_interval(100);
  16092. sse.set_max_reconnect_attempts(1);
  16093. sse.start_async();
  16094. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16095. sse.stop();
  16096. EXPECT_TRUE(id_received.load());
  16097. EXPECT_EQ(sse.last_event_id(), "evt-123");
  16098. }
  16099. // Test: Manual stop
  16100. TEST_F(SSEIntegrationTest, ManualStop) {
  16101. // Endpoint that sends one event and stays open briefly
  16102. std::atomic<bool> handler_running{true};
  16103. server_->Get("/stay-open", [&handler_running](const Request &,
  16104. Response &res) {
  16105. res.set_chunked_content_provider(
  16106. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  16107. if (offset == 0) {
  16108. std::string event = "data: connected\n\n";
  16109. sink.write(event.data(), event.size());
  16110. }
  16111. // Keep connection open while handler_running is true
  16112. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  16113. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16114. }
  16115. return false;
  16116. });
  16117. });
  16118. Client client("localhost", get_port());
  16119. sse::SSEClient sse(client, "/stay-open");
  16120. std::atomic<bool> connected{false};
  16121. sse.on_open([&connected]() { connected.store(true); });
  16122. sse.set_reconnect_interval(100);
  16123. sse.set_max_reconnect_attempts(1);
  16124. sse.start_async();
  16125. // Wait for connection to establish
  16126. for (int i = 0; i < 20 && !connected.load(); ++i) {
  16127. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16128. }
  16129. EXPECT_TRUE(connected.load());
  16130. EXPECT_TRUE(sse.is_connected());
  16131. // Signal handler to stop
  16132. handler_running.store(false);
  16133. // Stop SSE client
  16134. sse.stop();
  16135. EXPECT_FALSE(sse.is_connected());
  16136. }
  16137. // Test: SSEClient with custom headers
  16138. TEST_F(SSEIntegrationTest, CustomHeaders) {
  16139. // Setup a server endpoint that checks for custom header
  16140. std::atomic<bool> header_received{false};
  16141. server_->Get("/header-check", [&](const Request &req, Response &res) {
  16142. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  16143. header_received.store(true);
  16144. }
  16145. res.set_chunked_content_provider("text/event-stream",
  16146. [](size_t, DataSink &) { return false; });
  16147. });
  16148. Client client("localhost", get_port());
  16149. Headers headers = {{"X-Custom-Header", "custom-value"}};
  16150. sse::SSEClient sse(client, "/header-check", headers);
  16151. sse.set_max_reconnect_attempts(1);
  16152. sse.start_async();
  16153. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16154. sse.stop();
  16155. EXPECT_TRUE(header_received.load());
  16156. }
  16157. // Test: Reconnect interval configuration
  16158. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  16159. Client client("localhost", get_port());
  16160. sse::SSEClient sse(client, "/events");
  16161. auto &result = sse.set_reconnect_interval(500);
  16162. // Builder pattern should return reference to self
  16163. EXPECT_EQ(&result, &sse);
  16164. }
  16165. // Test: Max reconnect attempts
  16166. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  16167. // Connect to non-existent port to force reconnects
  16168. Client client("localhost", 59998);
  16169. sse::SSEClient sse(client, "/events");
  16170. std::atomic<int> error_count{0};
  16171. sse.on_error([&](Error) { error_count.fetch_add(1); });
  16172. sse.set_reconnect_interval(50);
  16173. sse.set_max_reconnect_attempts(2);
  16174. auto start = std::chrono::steady_clock::now();
  16175. sse.start(); // Blocking call
  16176. auto end = std::chrono::steady_clock::now();
  16177. // Should have stopped after 2 failed attempts
  16178. EXPECT_GE(error_count.load(), 2);
  16179. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  16180. auto duration =
  16181. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  16182. #ifdef _WIN32
  16183. // Windows is much slower for socket connection failures
  16184. EXPECT_LT(duration.count(), 7000);
  16185. #else
  16186. EXPECT_LT(duration.count(), 1000);
  16187. #endif
  16188. }
  16189. // Test: Multi-line data in integration
  16190. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  16191. // Endpoint with multi-line data
  16192. server_->Get("/multiline-data", [](const Request &, Response &res) {
  16193. res.set_chunked_content_provider(
  16194. "text/event-stream", [](size_t offset, DataSink &sink) {
  16195. if (offset == 0) {
  16196. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  16197. sink.write(event.data(), event.size());
  16198. }
  16199. return false;
  16200. });
  16201. });
  16202. Client client("localhost", get_port());
  16203. sse::SSEClient sse(client, "/multiline-data");
  16204. std::string received_data;
  16205. std::mutex data_mutex;
  16206. sse.on_message([&](const sse::SSEMessage &msg) {
  16207. std::lock_guard<std::mutex> lock(data_mutex);
  16208. received_data = msg.data;
  16209. });
  16210. sse.set_reconnect_interval(100);
  16211. sse.set_max_reconnect_attempts(1);
  16212. sse.start_async();
  16213. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16214. sse.stop();
  16215. std::lock_guard<std::mutex> lock(data_mutex);
  16216. EXPECT_EQ(received_data, "line1\nline2\nline3");
  16217. }
  16218. // Test: Auto-reconnect after server disconnection
  16219. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  16220. std::atomic<int> connection_count{0};
  16221. std::atomic<int> message_count{0};
  16222. // Endpoint that sends one event and closes, forcing reconnect
  16223. server_->Get("/reconnect-test",
  16224. [&connection_count](const Request &, Response &res) {
  16225. connection_count.fetch_add(1);
  16226. res.set_chunked_content_provider(
  16227. "text/event-stream", [](size_t offset, DataSink &sink) {
  16228. if (offset == 0) {
  16229. std::string event = "data: hello\n\n";
  16230. sink.write(event.data(), event.size());
  16231. }
  16232. return false; // Close connection after sending
  16233. });
  16234. });
  16235. Client client("localhost", get_port());
  16236. sse::SSEClient sse(client, "/reconnect-test");
  16237. sse.on_message([&message_count](const sse::SSEMessage &) {
  16238. message_count.fetch_add(1);
  16239. });
  16240. sse.set_reconnect_interval(100);
  16241. sse.set_max_reconnect_attempts(3);
  16242. sse.start_async();
  16243. // Wait long enough for multiple reconnects
  16244. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16245. sse.stop();
  16246. // Should have connected multiple times (initial + reconnects)
  16247. EXPECT_GE(connection_count.load(), 2);
  16248. // Should have received messages from multiple connections
  16249. EXPECT_GE(message_count.load(), 2);
  16250. }
  16251. // Test: Last-Event-ID sent on reconnect
  16252. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  16253. std::atomic<int> connection_count{0};
  16254. std::vector<std::string> received_last_event_ids;
  16255. std::mutex id_mutex;
  16256. // Endpoint that checks Last-Event-ID header and sends event with ID
  16257. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  16258. int conn = connection_count.fetch_add(1);
  16259. // Capture the Last-Event-ID header from each connection
  16260. {
  16261. std::lock_guard<std::mutex> lock(id_mutex);
  16262. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  16263. }
  16264. res.set_chunked_content_provider(
  16265. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  16266. if (offset == 0) {
  16267. std::string event =
  16268. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  16269. sink.write(event.data(), event.size());
  16270. }
  16271. return false;
  16272. });
  16273. });
  16274. Client client("localhost", get_port());
  16275. sse::SSEClient sse(client, "/reconnect-with-id");
  16276. sse.set_reconnect_interval(100);
  16277. sse.set_max_reconnect_attempts(3);
  16278. sse.start_async();
  16279. // Wait for at least 2 connections
  16280. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16281. sse.stop();
  16282. // Verify behavior
  16283. std::lock_guard<std::mutex> lock(id_mutex);
  16284. EXPECT_GE(received_last_event_ids.size(), 2u);
  16285. // First connection should have no Last-Event-ID
  16286. if (!received_last_event_ids.empty()) {
  16287. EXPECT_EQ(received_last_event_ids[0], "");
  16288. }
  16289. // Second connection should have Last-Event-ID from first connection
  16290. if (received_last_event_ids.size() >= 2) {
  16291. EXPECT_EQ(received_last_event_ids[1], "event-0");
  16292. }
  16293. }
  16294. // Test: set_headers updates headers used on reconnect
  16295. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  16296. std::vector<std::string> received_tokens;
  16297. std::mutex token_mutex;
  16298. // Endpoint that captures Authorization header
  16299. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  16300. {
  16301. std::lock_guard<std::mutex> lock(token_mutex);
  16302. received_tokens.push_back(req.get_header_value("Authorization"));
  16303. }
  16304. res.set_chunked_content_provider(
  16305. "text/event-stream", [](size_t offset, DataSink &sink) {
  16306. if (offset == 0) {
  16307. std::string event = "data: hello\n\n";
  16308. sink.write(event.data(), event.size());
  16309. }
  16310. return false; // Close connection to trigger reconnect
  16311. });
  16312. });
  16313. Client client("localhost", get_port());
  16314. Headers headers = {{"Authorization", "Bearer old-token"}};
  16315. sse::SSEClient sse(client, "/auth-check", headers);
  16316. // Update headers on each successful connection
  16317. sse.on_open(
  16318. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  16319. sse.set_reconnect_interval(100);
  16320. sse.set_max_reconnect_attempts(3);
  16321. sse.start_async();
  16322. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16323. sse.stop();
  16324. std::lock_guard<std::mutex> lock(token_mutex);
  16325. ASSERT_GE(received_tokens.size(), 2u);
  16326. // First connection uses original header
  16327. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  16328. // Second connection uses updated header from set_headers
  16329. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  16330. }
  16331. // Test: 401 allows reconnection (so on_error can refresh headers)
  16332. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  16333. std::atomic<int> connection_count{0};
  16334. // Endpoint: returns 401 on first attempt, 200 on second
  16335. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  16336. int conn = connection_count.fetch_add(1);
  16337. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  16338. res.status = StatusCode::Unauthorized_401;
  16339. res.set_content("Unauthorized", "text/plain");
  16340. return;
  16341. }
  16342. res.set_chunked_content_provider(
  16343. "text/event-stream", [](size_t offset, DataSink &sink) {
  16344. if (offset == 0) {
  16345. std::string event = "data: authenticated\n\n";
  16346. sink.write(event.data(), event.size());
  16347. }
  16348. return false;
  16349. });
  16350. });
  16351. Client client("localhost", get_port());
  16352. Headers headers = {{"Authorization", "Bearer expired"}};
  16353. sse::SSEClient sse(client, "/auth-retry", headers);
  16354. std::atomic<bool> message_received{false};
  16355. // Refresh token on error
  16356. sse.on_error(
  16357. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  16358. sse.on_message([&](const sse::SSEMessage &msg) {
  16359. if (msg.data == "authenticated") { message_received.store(true); }
  16360. });
  16361. sse.set_reconnect_interval(100);
  16362. sse.set_max_reconnect_attempts(3);
  16363. sse.start_async();
  16364. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16365. sse.stop();
  16366. // Should have reconnected after 401 and succeeded with new token
  16367. EXPECT_GE(connection_count.load(), 2);
  16368. EXPECT_TRUE(message_received.load());
  16369. }
  16370. TEST(Issue2318Test, EmptyHostString) {
  16371. {
  16372. httplib::Client cli_empty("", PORT);
  16373. auto res = cli_empty.Get("/");
  16374. ASSERT_FALSE(res);
  16375. EXPECT_EQ(httplib::Error::Connection, res.error());
  16376. }
  16377. {
  16378. httplib::Client cli(" ", PORT);
  16379. auto res = cli.Get("/");
  16380. ASSERT_FALSE(res);
  16381. EXPECT_EQ(httplib::Error::Connection, res.error());
  16382. }
  16383. }
  16384. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16385. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  16386. Server svr;
  16387. // Set a small payload limit (1KB)
  16388. svr.set_payload_max_length(1024);
  16389. svr.Post("/test", [&](const Request &req, Response &res) {
  16390. res.set_content("Body size: " + std::to_string(req.body.size()),
  16391. "text/plain");
  16392. });
  16393. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16394. auto se = detail::scope_exit([&] {
  16395. svr.stop();
  16396. listen_thread.join();
  16397. });
  16398. svr.wait_until_ready();
  16399. // Create data that compresses well but exceeds limit when decompressed
  16400. // 8KB of repeated null bytes compresses to a very small size
  16401. std::string original_data(8 * 1024, '\0');
  16402. // Compress the data using gzip
  16403. std::string compressed_data;
  16404. detail::gzip_compressor compressor;
  16405. compressor.compress(original_data.data(), original_data.size(), true,
  16406. [&](const char *data, size_t size) {
  16407. compressed_data.append(data, size);
  16408. return true;
  16409. });
  16410. // Verify compression worked (compressed should be much smaller)
  16411. ASSERT_LT(compressed_data.size(), original_data.size());
  16412. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16413. // Send compressed data with Content-Encoding: gzip
  16414. Client cli(HOST, PORT);
  16415. Headers headers = {{"Content-Encoding", "gzip"}};
  16416. auto res =
  16417. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16418. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16420. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16421. }
  16422. #endif
  16423. // ============================================================================
  16424. // OpenSSL-Specific Tests
  16425. // ============================================================================
  16426. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16427. X509 *readCertificate(const std::string &strFileName) {
  16428. std::ifstream inStream(strFileName);
  16429. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16430. std::istreambuf_iterator<char>());
  16431. if (strCertPEM.empty()) return (nullptr);
  16432. BIO *pbCert = BIO_new(BIO_s_mem());
  16433. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16434. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16435. BIO_free(pbCert);
  16436. return (pCert);
  16437. }
  16438. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16439. std::ifstream inStream(strFileName);
  16440. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16441. std::istreambuf_iterator<char>());
  16442. if (strPrivateKeyPEM.empty()) return (nullptr);
  16443. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16444. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16445. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16446. BIO_free(pbPrivKey);
  16447. return (pPrivateKey);
  16448. }
  16449. TEST(BindServerTest, UpdateCerts) {
  16450. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16451. int port = svr.bind_to_any_port("0.0.0.0");
  16452. ASSERT_TRUE(svr.is_valid());
  16453. ASSERT_TRUE(port > 0);
  16454. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16455. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16456. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16457. ASSERT_TRUE(cert != nullptr);
  16458. ASSERT_TRUE(ca_cert != nullptr);
  16459. ASSERT_TRUE(key != nullptr);
  16460. X509_STORE *cert_store = X509_STORE_new();
  16461. X509_STORE_add_cert(cert_store, ca_cert);
  16462. // svr.update_certs(cert, key, cert_store); // deprecated
  16463. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16464. CLIENT_CA_CERT_FILE);
  16465. ASSERT_TRUE(svr.is_valid());
  16466. svr.stop();
  16467. X509_STORE_free(cert_store);
  16468. X509_free(cert);
  16469. X509_free(ca_cert);
  16470. EVP_PKEY_free(key);
  16471. }
  16472. // Test that update_certs() updates client CA list correctly
  16473. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  16474. // Start with file-based constructor
  16475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16476. ASSERT_TRUE(svr.is_valid());
  16477. // Initially no client CA list should be set
  16478. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16479. ASSERT_TRUE(ssl_ctx != nullptr);
  16480. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  16481. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  16482. EXPECT_EQ(0, count_before);
  16483. // Now update with client CA (PEM string)
  16484. std::string cert_pem, key_pem, ca_pem;
  16485. read_file(SERVER_CERT_FILE, cert_pem);
  16486. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  16487. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  16488. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  16489. ASSERT_TRUE(svr.is_valid());
  16490. // Now client CA list should be set
  16491. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  16492. ASSERT_TRUE(ca_list_after != nullptr);
  16493. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  16494. }
  16495. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  16496. // Test that the file-path SSLServer constructor properly sets the client CA
  16497. // list that is sent to clients during the TLS handshake (CertificateRequest)
  16498. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16499. ASSERT_TRUE(svr.is_valid());
  16500. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16501. ASSERT_TRUE(ssl_ctx != nullptr);
  16502. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  16503. ASSERT_TRUE(ca_list != nullptr);
  16504. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  16505. }
  16506. #endif
  16507. // ============================================================================
  16508. // MbedTLS-Specific Tests
  16509. // ============================================================================
  16510. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16511. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  16512. using namespace httplib::tls;
  16513. // Track if callback was invoked
  16514. bool callback_invoked = false;
  16515. // The callback receives void* ctx which is actually MbedTlsContext*
  16516. // We can access the mbedtls_ssl_config via the context
  16517. auto setup_callback = [&callback_invoked](void *ctx) {
  16518. callback_invoked = true;
  16519. // Cast to MbedTlsContext* to access the ssl config
  16520. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  16521. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  16522. // Use static variables to hold certificate data (simplified for test)
  16523. static mbedtls_x509_crt own_cert;
  16524. static mbedtls_pk_context own_key;
  16525. static mbedtls_x509_crt ca_chain;
  16526. static bool initialized = false;
  16527. if (!initialized) {
  16528. mbedtls_x509_crt_init(&own_cert);
  16529. mbedtls_pk_init(&own_key);
  16530. mbedtls_x509_crt_init(&ca_chain);
  16531. // Load server certificate
  16532. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  16533. return false;
  16534. }
  16535. // Load server private key.
  16536. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  16537. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  16538. #if MBEDTLS_VERSION_MAJOR == 3
  16539. ,
  16540. mbedtls_ctr_drbg_random, nullptr
  16541. #endif
  16542. ) != 0) {
  16543. return false;
  16544. }
  16545. // Load CA chain for client verification
  16546. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  16547. return false;
  16548. }
  16549. initialized = true;
  16550. }
  16551. // Configure the SSL config
  16552. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  16553. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  16554. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16555. // Set minimum TLS version using mbedTLS native API
  16556. #if MBEDTLS_VERSION_MAJOR >= 3
  16557. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16558. #else
  16559. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16560. MBEDTLS_SSL_MINOR_VERSION_3);
  16561. #endif
  16562. return true;
  16563. };
  16564. SSLServer svr(setup_callback);
  16565. ASSERT_TRUE(svr.is_valid());
  16566. ASSERT_TRUE(callback_invoked);
  16567. svr.Get("/test", [&](const Request &req, Response &res) {
  16568. res.set_content("test", "text/plain");
  16569. auto cert = req.peer_cert();
  16570. ASSERT_TRUE(static_cast<bool>(cert));
  16571. auto common_name = cert.subject_cn();
  16572. EXPECT_EQ("Common Name", common_name);
  16573. });
  16574. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16575. auto se = detail::scope_exit([&] {
  16576. svr.stop();
  16577. t.join();
  16578. ASSERT_FALSE(svr.is_running());
  16579. });
  16580. svr.wait_until_ready();
  16581. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16582. cli.enable_server_certificate_verification(false);
  16583. cli.set_connection_timeout(30);
  16584. auto res = cli.Get("/test");
  16585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16586. ASSERT_EQ(StatusCode::OK_200, res->status);
  16587. }
  16588. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  16589. // context (owning mbedtls_ssl_config) before shutting down a still-open
  16590. // keep-alive SSL session, which reads through that config in
  16591. // mbedtls_ssl_close_notify.
  16592. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  16593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16594. ASSERT_TRUE(svr.is_valid());
  16595. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16596. res.set_content("test", "text/plain");
  16597. });
  16598. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16599. auto se = detail::scope_exit([&] {
  16600. svr.stop();
  16601. t.join();
  16602. ASSERT_FALSE(svr.is_running());
  16603. });
  16604. svr.wait_until_ready();
  16605. {
  16606. SSLClient cli(HOST, PORT);
  16607. cli.enable_server_certificate_verification(false);
  16608. cli.set_keep_alive(true);
  16609. auto res = cli.Get("/test");
  16610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16611. ASSERT_EQ(StatusCode::OK_200, res->status);
  16612. // cli is destructed here with the keep-alive SSL session still open.
  16613. }
  16614. }
  16615. #endif
  16616. // WebSocket Tests
  16617. TEST(WebSocketTest, RSVBitsMustBeZero) {
  16618. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  16619. // defining the meaning of these bits has been negotiated.
  16620. auto make_frame = [](uint8_t first_byte) {
  16621. std::string frame;
  16622. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  16623. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  16624. frame += "Hello";
  16625. return frame;
  16626. };
  16627. // RSV1 set (0x40)
  16628. {
  16629. detail::BufferStream strm;
  16630. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  16631. ws::Opcode opcode;
  16632. std::string payload;
  16633. bool fin;
  16634. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16635. false, 1024));
  16636. }
  16637. // RSV2 set (0x20)
  16638. {
  16639. detail::BufferStream strm;
  16640. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  16641. ws::Opcode opcode;
  16642. std::string payload;
  16643. bool fin;
  16644. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16645. false, 1024));
  16646. }
  16647. // RSV3 set (0x10)
  16648. {
  16649. detail::BufferStream strm;
  16650. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  16651. ws::Opcode opcode;
  16652. std::string payload;
  16653. bool fin;
  16654. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16655. false, 1024));
  16656. }
  16657. // No RSV bits set - should succeed
  16658. {
  16659. detail::BufferStream strm;
  16660. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  16661. ws::Opcode opcode;
  16662. std::string payload;
  16663. bool fin;
  16664. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16665. false, 1024));
  16666. EXPECT_EQ(ws::Opcode::Text, opcode);
  16667. EXPECT_EQ("Hello", payload);
  16668. EXPECT_TRUE(fin);
  16669. }
  16670. }
  16671. TEST(WebSocketTest, ControlFrameValidation) {
  16672. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  16673. // payload length <= 125.
  16674. // Ping with FIN=0 - must be rejected
  16675. {
  16676. detail::BufferStream strm;
  16677. std::string frame;
  16678. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  16679. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16680. strm.write(frame.data(), frame.size());
  16681. ws::Opcode opcode;
  16682. std::string payload;
  16683. bool fin;
  16684. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16685. false, 1024));
  16686. }
  16687. // Close with FIN=0 - must be rejected
  16688. {
  16689. detail::BufferStream strm;
  16690. std::string frame;
  16691. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  16692. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16693. strm.write(frame.data(), frame.size());
  16694. ws::Opcode opcode;
  16695. std::string payload;
  16696. bool fin;
  16697. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16698. false, 1024));
  16699. }
  16700. // Ping with payload_len=126 (extended length) - must be rejected
  16701. {
  16702. detail::BufferStream strm;
  16703. std::string frame;
  16704. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16705. frame += static_cast<char>(126); // payload_len=126 (>125)
  16706. frame += static_cast<char>(0x00); // extended length high byte
  16707. frame += static_cast<char>(126); // extended length low byte
  16708. frame += std::string(126, 'x');
  16709. strm.write(frame.data(), frame.size());
  16710. ws::Opcode opcode;
  16711. std::string payload;
  16712. bool fin;
  16713. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16714. false, 1024));
  16715. }
  16716. // Ping with FIN=1 and payload_len=125 - should succeed
  16717. {
  16718. detail::BufferStream strm;
  16719. std::string frame;
  16720. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16721. frame += static_cast<char>(125); // payload_len=125
  16722. frame += std::string(125, 'x');
  16723. strm.write(frame.data(), frame.size());
  16724. ws::Opcode opcode;
  16725. std::string payload;
  16726. bool fin;
  16727. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16728. false, 1024));
  16729. EXPECT_EQ(ws::Opcode::Ping, opcode);
  16730. EXPECT_EQ(125u, payload.size());
  16731. EXPECT_TRUE(fin);
  16732. }
  16733. }
  16734. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  16735. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  16736. // length MUST be 0.
  16737. // MSB set - must be rejected
  16738. {
  16739. detail::BufferStream strm;
  16740. std::string frame;
  16741. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16742. frame += static_cast<char>(127); // 64-bit extended length
  16743. frame += static_cast<char>(0x80); // MSB set (invalid)
  16744. frame += std::string(7, '\0'); // remaining 7 bytes of length
  16745. strm.write(frame.data(), frame.size());
  16746. ws::Opcode opcode;
  16747. std::string payload;
  16748. bool fin;
  16749. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16750. false, 1024));
  16751. }
  16752. // MSB clear - should pass length parsing (will be rejected by max_len,
  16753. // but that's a different check; use a small length to verify)
  16754. {
  16755. detail::BufferStream strm;
  16756. std::string frame;
  16757. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16758. frame += static_cast<char>(127); // 64-bit extended length
  16759. frame += std::string(7, '\0'); // high bytes = 0
  16760. frame += static_cast<char>(0x03); // length = 3
  16761. frame += "abc";
  16762. strm.write(frame.data(), frame.size());
  16763. ws::Opcode opcode;
  16764. std::string payload;
  16765. bool fin;
  16766. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16767. false, 1024));
  16768. EXPECT_EQ(ws::Opcode::Text, opcode);
  16769. EXPECT_EQ("abc", payload);
  16770. }
  16771. }
  16772. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16773. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16774. // Valid UTF-8
  16775. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16776. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16777. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16778. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16779. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16780. // Invalid UTF-8
  16781. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16782. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16783. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16784. EXPECT_FALSE(
  16785. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16786. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16787. }
  16788. TEST(WebSocketTest, ConnectAndDisconnect) {
  16789. Server svr;
  16790. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16791. std::string msg;
  16792. while (ws.read(msg)) {}
  16793. });
  16794. auto port = svr.bind_to_any_port(HOST);
  16795. std::thread t([&]() { svr.listen_after_bind(); });
  16796. svr.wait_until_ready();
  16797. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16798. auto res = client.connect();
  16799. ASSERT_TRUE(res);
  16800. EXPECT_EQ(Error::Success, res.error());
  16801. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  16802. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  16803. EXPECT_TRUE(client.is_open());
  16804. client.close();
  16805. EXPECT_FALSE(client.is_open());
  16806. svr.stop();
  16807. t.join();
  16808. }
  16809. TEST(WebSocketTest, ValidURL) {
  16810. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16811. EXPECT_TRUE(ws1.is_valid());
  16812. ws::WebSocketClient ws2("ws://example.com/path");
  16813. EXPECT_TRUE(ws2.is_valid());
  16814. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16815. EXPECT_TRUE(ws3.is_valid());
  16816. #ifdef CPPHTTPLIB_SSL_ENABLED
  16817. ws::WebSocketClient wss1("wss://example.com/path");
  16818. EXPECT_TRUE(wss1.is_valid());
  16819. ws::WebSocketClient wss2("wss://example.com:443/path");
  16820. EXPECT_TRUE(wss2.is_valid());
  16821. #endif
  16822. }
  16823. TEST(WebSocketTest, InvalidURL) {
  16824. // No scheme
  16825. ws::WebSocketClient ws1("localhost:8080/path");
  16826. EXPECT_FALSE(ws1.is_valid());
  16827. // No path
  16828. ws::WebSocketClient ws2("ws://localhost:8080");
  16829. EXPECT_FALSE(ws2.is_valid());
  16830. // Empty string
  16831. ws::WebSocketClient ws3("");
  16832. EXPECT_FALSE(ws3.is_valid());
  16833. // Missing host
  16834. ws::WebSocketClient ws4("ws://:8080/path");
  16835. EXPECT_FALSE(ws4.is_valid());
  16836. // Port number overflow — should not crash
  16837. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16838. EXPECT_FALSE(ws5.is_valid());
  16839. // Port out of range
  16840. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16841. EXPECT_FALSE(ws6.is_valid());
  16842. }
  16843. TEST(WebSocketTest, UnsupportedScheme) {
  16844. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16845. ws::WebSocketClient ws1("http://localhost:8080/path");
  16846. EXPECT_FALSE(ws1.is_valid());
  16847. ws::WebSocketClient ws2("https://localhost:8080/path");
  16848. EXPECT_FALSE(ws2.is_valid());
  16849. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16850. EXPECT_FALSE(ws3.is_valid());
  16851. #else
  16852. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16853. std::invalid_argument);
  16854. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16855. std::invalid_argument);
  16856. #endif
  16857. }
  16858. TEST(WebSocketTest, ConnectWhenInvalid) {
  16859. ws::WebSocketClient ws("not a valid url");
  16860. EXPECT_FALSE(ws.is_valid());
  16861. auto res = ws.connect();
  16862. EXPECT_FALSE(res);
  16863. EXPECT_EQ(Error::Connection, res.error());
  16864. EXPECT_EQ(-1, res.status());
  16865. }
  16866. TEST(WebSocketTest, ConnectRefusedReportsError) {
  16867. // Grab a port that is free, then close it again so nothing listens there
  16868. Server svr;
  16869. auto port = svr.bind_to_any_port(HOST);
  16870. svr.stop();
  16871. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16872. auto res = client.connect();
  16873. ASSERT_FALSE(res);
  16874. EXPECT_EQ(Error::Connection, res.error());
  16875. EXPECT_EQ(-1, res.status());
  16876. }
  16877. TEST(WebSocketTest, DefaultPort) {
  16878. ws::WebSocketClient ws1("ws://example.com/path");
  16879. EXPECT_TRUE(ws1.is_valid());
  16880. // ws:// defaults to port 80 (verified by successful parse)
  16881. #ifdef CPPHTTPLIB_SSL_ENABLED
  16882. ws::WebSocketClient ws2("wss://example.com/path");
  16883. EXPECT_TRUE(ws2.is_valid());
  16884. // wss:// defaults to port 443 (verified by successful parse)
  16885. #endif
  16886. }
  16887. TEST(WebSocketTest, IPv6LiteralAddress) {
  16888. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16889. EXPECT_TRUE(ws1.is_valid());
  16890. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16891. EXPECT_TRUE(ws2.is_valid());
  16892. }
  16893. TEST(WebSocketTest, ComplexPath) {
  16894. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16895. EXPECT_TRUE(ws1.is_valid());
  16896. ws::WebSocketClient ws2("ws://localhost:8080/");
  16897. EXPECT_TRUE(ws2.is_valid());
  16898. }
  16899. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16900. Server svr;
  16901. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16902. std::string msg;
  16903. while (ws.read(msg)) {}
  16904. });
  16905. auto port = svr.bind_to_any_port(HOST);
  16906. std::thread t([&]() { svr.listen_after_bind(); });
  16907. svr.wait_until_ready();
  16908. auto another_host = "example.com";
  16909. auto wrong_ip = "192.0.2.1";
  16910. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16911. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16912. ASSERT_TRUE(client.connect());
  16913. EXPECT_TRUE(client.is_open());
  16914. client.close();
  16915. svr.stop();
  16916. t.join();
  16917. }
  16918. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16919. Server svr;
  16920. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16921. std::string msg;
  16922. while (ws.read(msg)) {}
  16923. });
  16924. auto port = svr.bind_to_any_port(HOST);
  16925. std::thread t([&]() { svr.listen_after_bind(); });
  16926. svr.wait_until_ready();
  16927. auto wrong_ip = "192.0.2.1";
  16928. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16929. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16930. client.set_connection_timeout(1);
  16931. client.set_read_timeout(1);
  16932. client.set_write_timeout(1);
  16933. EXPECT_FALSE(client.connect());
  16934. EXPECT_FALSE(client.is_open());
  16935. svr.stop();
  16936. t.join();
  16937. }
  16938. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16939. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16940. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16941. // (RFC 6761) is only a map key and the Host header value.
  16942. auto host = "target.invalid";
  16943. Server svr;
  16944. std::string received_host;
  16945. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16946. received_host = req.get_header_value("Host");
  16947. std::string msg;
  16948. while (ws.read(msg)) {}
  16949. });
  16950. auto port = svr.bind_to_any_port(HOST);
  16951. std::thread t([&]() { svr.listen_after_bind(); });
  16952. // ASSERT_* below returns from the test body, which would leave t joinable
  16953. // and make ~thread call std::terminate.
  16954. auto se = detail::scope_exit([&] {
  16955. svr.stop();
  16956. if (t.joinable()) { t.join(); }
  16957. });
  16958. svr.wait_until_ready();
  16959. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16960. std::to_string(port) + "/ws");
  16961. client.set_hostname_addr_map({{host, HOST}});
  16962. ASSERT_TRUE(client.connect());
  16963. EXPECT_TRUE(client.is_open());
  16964. client.close();
  16965. svr.stop();
  16966. t.join();
  16967. // The mapping only redirects the connection; the identity stays host_.
  16968. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16969. }
  16970. class WebSocketIntegrationTest : public ::testing::Test {
  16971. protected:
  16972. void SetUp() override {
  16973. server_ = httplib::detail::make_unique<Server>();
  16974. setup_server();
  16975. start_server();
  16976. }
  16977. void TearDown() override {
  16978. server_->stop();
  16979. if (server_thread_.joinable()) { server_thread_.join(); }
  16980. }
  16981. void setup_server() {
  16982. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16983. std::string msg;
  16984. ws::ReadResult ret;
  16985. while ((ret = ws.read(msg))) {
  16986. if (ret == ws::Binary) {
  16987. ws.send(msg.data(), msg.size());
  16988. } else {
  16989. ws.send(msg);
  16990. }
  16991. }
  16992. });
  16993. server_->WebSocket("/ws-echo-string",
  16994. [](const Request &, ws::WebSocket &ws) {
  16995. std::string msg;
  16996. while (ws.read(msg)) {
  16997. ws.send("echo: " + msg);
  16998. }
  16999. });
  17000. server_->WebSocket(
  17001. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  17002. // Echo back request metadata
  17003. ws.send("path:" + req.path);
  17004. ws.send("header:" + req.get_header_value("X-Test-Header"));
  17005. std::string msg;
  17006. while (ws.read(msg)) {}
  17007. });
  17008. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  17009. std::string msg;
  17010. ws.read(msg); // wait for a message
  17011. ws.close();
  17012. });
  17013. server_->WebSocket("/ws-close-status",
  17014. [](const Request &, ws::WebSocket &ws) {
  17015. std::string msg;
  17016. ws.read(msg); // wait for a message
  17017. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  17018. });
  17019. server_->WebSocket(
  17020. "/ws-subprotocol",
  17021. [](const Request &, ws::WebSocket &ws) {
  17022. std::string msg;
  17023. while (ws.read(msg)) {
  17024. ws.send(msg);
  17025. }
  17026. },
  17027. [](const std::vector<std::string> &protocols) -> std::string {
  17028. for (const auto &p : protocols) {
  17029. if (p == "graphql-ws") { return p; }
  17030. }
  17031. return "";
  17032. });
  17033. }
  17034. void start_server() {
  17035. port_ = server_->bind_to_any_port(HOST);
  17036. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17037. server_->wait_until_ready();
  17038. }
  17039. std::unique_ptr<Server> server_;
  17040. std::thread server_thread_;
  17041. int port_ = 0;
  17042. };
  17043. TEST_F(WebSocketIntegrationTest, TextEcho) {
  17044. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17045. "/ws-echo");
  17046. ASSERT_TRUE(client.connect());
  17047. ASSERT_TRUE(client.is_open());
  17048. ASSERT_TRUE(client.send("Hello WebSocket"));
  17049. std::string msg;
  17050. EXPECT_EQ(ws::Text, client.read(msg));
  17051. EXPECT_EQ("Hello WebSocket", msg);
  17052. client.close();
  17053. }
  17054. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  17055. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17056. "/ws-echo");
  17057. ASSERT_TRUE(client.connect());
  17058. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  17059. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  17060. std::string msg;
  17061. EXPECT_EQ(ws::Binary, client.read(msg));
  17062. EXPECT_EQ(binary_data, msg);
  17063. client.close();
  17064. }
  17065. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  17066. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17067. "/ws-echo");
  17068. ASSERT_TRUE(client.connect());
  17069. for (int i = 0; i < 10; i++) {
  17070. auto text = "message " + std::to_string(i);
  17071. ASSERT_TRUE(client.send(text));
  17072. std::string msg;
  17073. ASSERT_TRUE(client.read(msg));
  17074. EXPECT_EQ(text, msg);
  17075. }
  17076. client.close();
  17077. }
  17078. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  17079. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17080. "/ws-close");
  17081. ASSERT_TRUE(client.connect());
  17082. // Send a message to trigger the server to close
  17083. ASSERT_TRUE(client.send("trigger close"));
  17084. // The server will close, so read should return false
  17085. std::string msg;
  17086. EXPECT_FALSE(client.read(msg));
  17087. EXPECT_FALSE(client.is_open());
  17088. }
  17089. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  17090. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17091. "/ws-echo");
  17092. ASSERT_TRUE(client.connect());
  17093. // 128KB message
  17094. std::string large_data(128 * 1024, 'X');
  17095. ASSERT_TRUE(client.send(large_data));
  17096. std::string msg;
  17097. ASSERT_TRUE(client.read(msg));
  17098. EXPECT_EQ(large_data, msg);
  17099. client.close();
  17100. }
  17101. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  17102. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17103. "/ws-echo");
  17104. ASSERT_TRUE(client.connect());
  17105. const int num_threads = 4;
  17106. std::vector<std::thread> threads;
  17107. std::atomic<int> send_count{0};
  17108. for (int t = 0; t < num_threads; t++) {
  17109. threads.emplace_back([&client, &send_count, t]() {
  17110. for (int i = 0; i < 5; i++) {
  17111. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  17112. if (client.send(text)) { send_count++; }
  17113. }
  17114. });
  17115. }
  17116. for (auto &th : threads) {
  17117. th.join();
  17118. }
  17119. int received = 0;
  17120. std::string msg;
  17121. while (received < send_count.load()) {
  17122. if (!client.read(msg)) { break; }
  17123. received++;
  17124. }
  17125. EXPECT_EQ(send_count.load(), received);
  17126. client.close();
  17127. }
  17128. TEST_F(WebSocketIntegrationTest, ReadString) {
  17129. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17130. "/ws-echo-string");
  17131. ASSERT_TRUE(client.connect());
  17132. ASSERT_TRUE(client.send("hello"));
  17133. std::string msg;
  17134. ASSERT_TRUE(client.read(msg));
  17135. EXPECT_EQ("echo: hello", msg);
  17136. ASSERT_TRUE(client.send("world"));
  17137. ASSERT_TRUE(client.read(msg));
  17138. EXPECT_EQ("echo: world", msg);
  17139. client.close();
  17140. }
  17141. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  17142. Headers headers = {{"X-Test-Header", "test-value"}};
  17143. ws::WebSocketClient client(
  17144. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  17145. ASSERT_TRUE(client.connect());
  17146. std::string msg;
  17147. ASSERT_TRUE(client.read(msg));
  17148. EXPECT_EQ("path:/ws-request-info", msg);
  17149. ASSERT_TRUE(client.read(msg));
  17150. EXPECT_EQ("header:test-value", msg);
  17151. client.close();
  17152. }
  17153. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  17154. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17155. "/ws-echo");
  17156. client.set_read_timeout(1, 0); // 1 second
  17157. ASSERT_TRUE(client.connect());
  17158. // Don't send anything — server echo handler waits for a message,
  17159. // so read() should time out and return false.
  17160. std::string msg;
  17161. EXPECT_FALSE(client.read(msg));
  17162. }
  17163. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  17164. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17165. "/ws-echo");
  17166. client.set_read_timeout(5, 0);
  17167. ASSERT_TRUE(client.connect());
  17168. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17169. // The server should reject it and close the connection.
  17170. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  17171. client.send(oversized);
  17172. // The server's read() should have failed due to payload limit,
  17173. // so our read() should return false (connection closed).
  17174. std::string msg;
  17175. EXPECT_FALSE(client.read(msg));
  17176. }
  17177. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  17178. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17179. "/ws-echo");
  17180. client.set_read_timeout(10, 0);
  17181. ASSERT_TRUE(client.connect());
  17182. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17183. // This should succeed.
  17184. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  17185. ASSERT_TRUE(client.send(at_limit));
  17186. std::string msg;
  17187. ASSERT_TRUE(client.read(msg));
  17188. EXPECT_EQ(at_limit.size(), msg.size());
  17189. client.close();
  17190. }
  17191. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  17192. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17193. "/nonexistent");
  17194. auto res = client.connect();
  17195. EXPECT_FALSE(res);
  17196. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  17197. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  17198. EXPECT_FALSE(client.is_open());
  17199. }
  17200. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  17201. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17202. "/ws-echo");
  17203. ASSERT_TRUE(client.connect());
  17204. ASSERT_TRUE(client.send(""));
  17205. std::string msg;
  17206. EXPECT_EQ(ws::Text, client.read(msg));
  17207. EXPECT_EQ("", msg);
  17208. client.close();
  17209. }
  17210. TEST_F(WebSocketIntegrationTest, Reconnect) {
  17211. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17212. "/ws-echo");
  17213. // First connection
  17214. ASSERT_TRUE(client.connect());
  17215. ASSERT_TRUE(client.send("first"));
  17216. std::string msg;
  17217. ASSERT_TRUE(client.read(msg));
  17218. EXPECT_EQ("first", msg);
  17219. client.close();
  17220. EXPECT_FALSE(client.is_open());
  17221. // Reconnect using the same client object
  17222. ASSERT_TRUE(client.connect());
  17223. ASSERT_TRUE(client.is_open());
  17224. ASSERT_TRUE(client.send("second"));
  17225. ASSERT_TRUE(client.read(msg));
  17226. EXPECT_EQ("second", msg);
  17227. client.close();
  17228. }
  17229. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  17230. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17231. "/ws-close-status");
  17232. ASSERT_TRUE(client.connect());
  17233. // Trigger the server to close with GoingAway status
  17234. ASSERT_TRUE(client.send("trigger"));
  17235. // read() should return false after receiving the close frame
  17236. std::string msg;
  17237. EXPECT_FALSE(client.read(msg));
  17238. EXPECT_FALSE(client.is_open());
  17239. }
  17240. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  17241. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17242. "/ws-echo");
  17243. ASSERT_TRUE(client.connect());
  17244. client.close(ws::CloseStatus::GoingAway, "client leaving");
  17245. EXPECT_FALSE(client.is_open());
  17246. }
  17247. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  17248. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  17249. ws::WebSocketClient client(
  17250. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17251. ASSERT_TRUE(client.connect());
  17252. // Server should have selected graphql-ws
  17253. EXPECT_EQ("graphql-ws", client.subprotocol());
  17254. client.close();
  17255. }
  17256. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  17257. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  17258. ws::WebSocketClient client(
  17259. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17260. ASSERT_TRUE(client.connect());
  17261. // Server should not have selected any subprotocol
  17262. EXPECT_TRUE(client.subprotocol().empty());
  17263. client.close();
  17264. }
  17265. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  17266. // Connect without requesting any subprotocol
  17267. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17268. "/ws-subprotocol");
  17269. ASSERT_TRUE(client.connect());
  17270. EXPECT_TRUE(client.subprotocol().empty());
  17271. client.close();
  17272. }
  17273. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  17274. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17275. "/ws-echo");
  17276. client.set_tcp_nodelay(true);
  17277. client.set_connection_timeout(3, 0);
  17278. bool socket_options_called = false;
  17279. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  17280. ASSERT_TRUE(client.connect());
  17281. ASSERT_TRUE(client.is_open());
  17282. EXPECT_TRUE(socket_options_called);
  17283. ASSERT_TRUE(client.send("hello"));
  17284. std::string msg;
  17285. auto result = client.read(msg);
  17286. EXPECT_EQ(result, ws::ReadResult::Text);
  17287. EXPECT_EQ(msg, "hello");
  17288. client.close();
  17289. }
  17290. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  17291. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17292. "/ws-echo");
  17293. client.set_connection_timeout(std::chrono::seconds(3));
  17294. client.set_write_timeout(std::chrono::seconds(3));
  17295. // A sub-second remainder exercises the seconds/microseconds split.
  17296. client.set_read_timeout(std::chrono::milliseconds(1500));
  17297. ASSERT_TRUE(client.connect());
  17298. auto start = std::chrono::steady_clock::now();
  17299. std::string msg;
  17300. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  17301. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17302. std::chrono::steady_clock::now() - start)
  17303. .count();
  17304. // Above 1s so that dropping the microseconds half of the split fails here,
  17305. // and well under the 300s default so that ignoring the setter fails too.
  17306. EXPECT_GE(elapsed, 1400);
  17307. EXPECT_LT(elapsed, 30000);
  17308. }
  17309. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  17310. Server svr;
  17311. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  17312. if (!req.has_header("Authorization")) {
  17313. res.status = StatusCode::Unauthorized_401;
  17314. res.set_content("Unauthorized", "text/plain");
  17315. return Server::HandlerResponse::Handled;
  17316. }
  17317. return Server::HandlerResponse::Unhandled;
  17318. });
  17319. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17320. std::string msg;
  17321. while (ws.read(msg)) {
  17322. ws.send(msg);
  17323. }
  17324. });
  17325. auto port = svr.bind_to_any_port("localhost");
  17326. std::thread t([&]() { svr.listen_after_bind(); });
  17327. svr.wait_until_ready();
  17328. // Without Authorization header - should be rejected before upgrade
  17329. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  17330. EXPECT_FALSE(client1.connect());
  17331. // With Authorization header - should succeed
  17332. Headers headers = {{"Authorization", "Bearer token123"}};
  17333. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  17334. headers);
  17335. ASSERT_TRUE(client2.connect());
  17336. ASSERT_TRUE(client2.send("hello"));
  17337. std::string msg;
  17338. ASSERT_TRUE(client2.read(msg));
  17339. EXPECT_EQ("hello", msg);
  17340. client2.close();
  17341. svr.stop();
  17342. t.join();
  17343. }
  17344. TEST(WebSocketTest, QueryStringInHandshake) {
  17345. Server svr;
  17346. std::mutex mtx;
  17347. std::string received_target;
  17348. std::string received_token;
  17349. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17350. {
  17351. std::lock_guard<std::mutex> lock(mtx);
  17352. received_target = req.target;
  17353. if (req.has_param("token")) {
  17354. received_token = req.get_param_value("token");
  17355. }
  17356. }
  17357. std::string msg;
  17358. while (ws.read(msg)) {
  17359. ws.send(msg);
  17360. }
  17361. });
  17362. auto port = svr.bind_to_any_port("localhost");
  17363. std::thread t([&]() { svr.listen_after_bind(); });
  17364. svr.wait_until_ready();
  17365. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  17366. "/ws?token=ABC&session=123");
  17367. ASSERT_TRUE(client.connect());
  17368. // Round-trip ensures the handler has run and captured the request.
  17369. ASSERT_TRUE(client.send("hello"));
  17370. std::string msg;
  17371. ASSERT_TRUE(client.read(msg));
  17372. EXPECT_EQ("hello", msg);
  17373. client.close();
  17374. {
  17375. std::lock_guard<std::mutex> lock(mtx);
  17376. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  17377. EXPECT_EQ("ABC", received_token);
  17378. }
  17379. svr.stop();
  17380. t.join();
  17381. }
  17382. // Run a handshake against a throwaway server and hand the request the server
  17383. // received back to the caller, so tests can assert on the headers the client
  17384. // actually put on the wire.
  17385. static void capture_websocket_handshake_request(
  17386. const Headers &client_headers,
  17387. std::function<void(const Request &, int port)> verify) {
  17388. Server svr;
  17389. std::mutex mtx;
  17390. Request received;
  17391. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17392. {
  17393. std::lock_guard<std::mutex> lock(mtx);
  17394. received = req;
  17395. }
  17396. std::string msg;
  17397. while (ws.read(msg)) {
  17398. ws.send(msg);
  17399. }
  17400. });
  17401. auto port = svr.bind_to_any_port("localhost");
  17402. std::thread t([&]() { svr.listen_after_bind(); });
  17403. auto se = detail::scope_exit([&] {
  17404. svr.stop();
  17405. t.join();
  17406. });
  17407. svr.wait_until_ready();
  17408. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  17409. client_headers);
  17410. ASSERT_TRUE(client.connect());
  17411. ASSERT_TRUE(client.send("hello"));
  17412. std::string msg;
  17413. ASSERT_TRUE(client.read(msg));
  17414. client.close();
  17415. {
  17416. std::lock_guard<std::mutex> lock(mtx);
  17417. verify(received, port);
  17418. }
  17419. }
  17420. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  17421. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  17422. // Non-default port must be present in the Host header. Default ports
  17423. // (80/443) are omitted; that logic is covered by
  17424. // MakeHostAndPortStringTest.
  17425. EXPECT_EQ("localhost:" + std::to_string(port),
  17426. req.get_header_value("Host"));
  17427. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  17428. req.get_header_value("User-Agent"));
  17429. EXPECT_FALSE(req.has_header("Accept"));
  17430. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  17431. EXPECT_FALSE(req.has_header("Content-Length"));
  17432. });
  17433. }
  17434. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  17435. capture_websocket_handshake_request(
  17436. {{"Host", "example.com"},
  17437. {"User-Agent", "custom-agent"},
  17438. {"X-Custom", "value"}},
  17439. [](const Request &req, int) {
  17440. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17441. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17442. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17443. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17444. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17445. });
  17446. }
  17447. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17448. capture_websocket_handshake_request(
  17449. {{"Upgrade", "bogus"},
  17450. {"Connection", "close"},
  17451. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17452. {"Sec-WebSocket-Version", "8"}},
  17453. [](const Request &req, int) {
  17454. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17455. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17456. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17457. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17458. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17459. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17460. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  17461. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  17462. req.get_header_value("Sec-WebSocket-Key"));
  17463. });
  17464. }
  17465. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  17466. // A header the client refuses to send must abort the handshake before any
  17467. // part of it reaches the wire; a lone request line would otherwise sit in
  17468. // the peer's buffer as a truncated request.
  17469. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17470. ASSERT_NE(INVALID_SOCKET, srv);
  17471. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  17472. sockaddr_in addr{};
  17473. addr.sin_family = AF_INET;
  17474. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  17475. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17476. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17477. ASSERT_EQ(0, ::listen(srv, 1));
  17478. sockaddr_in bound{};
  17479. socklen_t bound_len = sizeof(bound);
  17480. ASSERT_EQ(
  17481. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  17482. auto port = ntohs(bound.sin_port);
  17483. ssize_t received = -1;
  17484. std::thread t([&] {
  17485. // Bound every blocking call so a regression fails the test with a bad
  17486. // value instead of hanging the suite.
  17487. fd_set rfds;
  17488. FD_ZERO(&rfds);
  17489. FD_SET(srv, &rfds);
  17490. timeval tv{5, 0};
  17491. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  17492. 0) {
  17493. return;
  17494. }
  17495. sockaddr_in cli_addr{};
  17496. socklen_t cli_len = sizeof(cli_addr);
  17497. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17498. if (cli == INVALID_SOCKET) { return; }
  17499. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  17500. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17501. char buf[4096];
  17502. received = ::recv(cli, buf, sizeof(buf), 0);
  17503. });
  17504. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  17505. // connect() has already shut the socket down by the time it returns false,
  17506. // so the peer sees EOF without waiting for the client to be destroyed.
  17507. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  17508. {{"X-Bad", "a\r\nInjected: 1"}});
  17509. EXPECT_FALSE(client.connect());
  17510. t.join();
  17511. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  17512. EXPECT_EQ(0, received);
  17513. }
  17514. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  17515. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  17516. // contains "upgrade" as a substring is a different token and must not
  17517. // start a WebSocket handshake.
  17518. auto make_request = [](const std::vector<std::string> &connection_values) {
  17519. Request req;
  17520. req.method = "GET";
  17521. req.headers.emplace("Upgrade", "websocket");
  17522. for (const auto &value : connection_values) {
  17523. req.headers.emplace("Connection", value);
  17524. }
  17525. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  17526. req.headers.emplace("Sec-WebSocket-Version", "13");
  17527. return req;
  17528. };
  17529. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  17530. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  17531. EXPECT_TRUE(
  17532. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  17533. EXPECT_TRUE(
  17534. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  17535. EXPECT_TRUE(
  17536. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  17537. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  17538. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  17539. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  17540. EXPECT_FALSE(
  17541. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  17542. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  17543. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  17544. }
  17545. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  17546. Server svr;
  17547. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  17548. auto port = svr.bind_to_any_port("localhost");
  17549. std::thread t([&]() { svr.listen_after_bind(); });
  17550. auto se = detail::scope_exit([&] {
  17551. svr.stop();
  17552. t.join();
  17553. });
  17554. svr.wait_until_ready();
  17555. Headers headers = {{"Upgrade", "websocket"},
  17556. {"Connection", "notupgrade"},
  17557. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  17558. {"Sec-WebSocket-Version", "13"}};
  17559. Client cli("localhost", port);
  17560. auto res = cli.Get("/ws", headers);
  17561. // The route exists only as a WebSocket route, so a request that fails the
  17562. // handshake check falls through to ordinary routing.
  17563. ASSERT_TRUE(res);
  17564. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  17565. }
  17566. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  17567. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  17568. // Connection value is the only thing left for the client to reject.
  17569. Server svr;
  17570. svr.Get("/ws", [](const Request &req, Response &res) {
  17571. res.status = StatusCode::SwitchingProtocol_101;
  17572. res.set_header("Upgrade", "websocket");
  17573. res.set_header("Connection", "notupgrade");
  17574. res.set_header("Sec-WebSocket-Accept",
  17575. detail::websocket_accept_key(
  17576. req.get_header_value("Sec-WebSocket-Key")));
  17577. });
  17578. auto port = svr.bind_to_any_port("localhost");
  17579. std::thread t([&]() { svr.listen_after_bind(); });
  17580. auto se = detail::scope_exit([&] {
  17581. svr.stop();
  17582. t.join();
  17583. });
  17584. svr.wait_until_ready();
  17585. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  17586. auto res = client.connect();
  17587. EXPECT_FALSE(res);
  17588. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  17589. EXPECT_FALSE(client.is_open());
  17590. }
  17591. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  17592. // The socket path doubles as the URL host, so it must not contain '/'.
  17593. const char *shard = getenv("GTEST_SHARD_INDEX");
  17594. const std::string sock_path =
  17595. shard ? std::string("httplib-ws-") + shard + ".sock"
  17596. : std::string("httplib-ws.sock");
  17597. std::remove(sock_path.c_str());
  17598. Server svr;
  17599. std::mutex mtx;
  17600. std::string received_host;
  17601. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17602. {
  17603. std::lock_guard<std::mutex> lock(mtx);
  17604. received_host = req.get_header_value("Host");
  17605. }
  17606. std::string msg;
  17607. while (ws.read(msg)) {
  17608. ws.send(msg);
  17609. }
  17610. });
  17611. svr.set_address_family(AF_UNIX);
  17612. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  17613. auto se = detail::scope_exit([&] {
  17614. svr.stop();
  17615. t.join();
  17616. std::remove(sock_path.c_str());
  17617. });
  17618. svr.wait_until_ready();
  17619. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  17620. client.set_address_family(AF_UNIX);
  17621. ASSERT_TRUE(client.connect());
  17622. ASSERT_TRUE(client.send("hello"));
  17623. std::string msg;
  17624. ASSERT_TRUE(client.read(msg));
  17625. client.close();
  17626. {
  17627. std::lock_guard<std::mutex> lock(mtx);
  17628. // There is no host:port for a Unix socket, so the same "localhost"
  17629. // placeholder the HTTP client uses is expected.
  17630. EXPECT_EQ("localhost", received_host);
  17631. }
  17632. }
  17633. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17634. class WebSocketSSLIntegrationTest : public ::testing::Test {
  17635. protected:
  17636. void SetUp() override {
  17637. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  17638. SERVER_PRIVATE_KEY_FILE);
  17639. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17640. std::string msg;
  17641. ws::ReadResult ret;
  17642. while ((ret = ws.read(msg))) {
  17643. if (ret == ws::Binary) {
  17644. ws.send(msg.data(), msg.size());
  17645. } else {
  17646. ws.send(msg);
  17647. }
  17648. }
  17649. });
  17650. port_ = server_->bind_to_any_port(HOST);
  17651. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17652. server_->wait_until_ready();
  17653. }
  17654. void TearDown() override {
  17655. server_->stop();
  17656. if (server_thread_.joinable()) { server_thread_.join(); }
  17657. }
  17658. std::unique_ptr<SSLServer> server_;
  17659. std::thread server_thread_;
  17660. int port_ = 0;
  17661. };
  17662. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  17663. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17664. "/ws-echo");
  17665. client.enable_server_certificate_verification(false);
  17666. ASSERT_TRUE(client.connect());
  17667. ASSERT_TRUE(client.is_open());
  17668. ASSERT_TRUE(client.send("Hello WSS"));
  17669. std::string msg;
  17670. EXPECT_EQ(ws::Text, client.read(msg));
  17671. EXPECT_EQ("Hello WSS", msg);
  17672. client.close();
  17673. }
  17674. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  17675. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  17676. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  17677. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  17678. // client (without calling close() first) is the only path that runs
  17679. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  17680. // bug exactly.
  17681. //
  17682. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  17683. // when linked against an instrumented libssl; run under Valgrind to catch it
  17684. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  17685. // suite (the freed session otherwise stalls on the close handshake) — this test
  17686. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  17687. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  17688. {
  17689. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17690. "/ws-echo");
  17691. client.enable_server_certificate_verification(false);
  17692. client.set_read_timeout(2, 0);
  17693. client.set_write_timeout(2, 0);
  17694. ASSERT_TRUE(client.connect());
  17695. ASSERT_TRUE(client.is_open());
  17696. ASSERT_TRUE(client.send("still open"));
  17697. // Intentionally do NOT call client.close(): leaving scope runs
  17698. // shutdown_and_close() with the WebSocket still open, which must send the
  17699. // close frame while the TLS session is still alive.
  17700. }
  17701. }
  17702. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  17703. // shutdown_and_close() at the start of connect(), reproducing the same
  17704. // use-after-free within the test body rather than at scope exit. The second
  17705. // connect must succeed and echo, proving the close handshake ran over a live
  17706. // session. See the note above about memory-tool requirements.
  17707. TEST_F(WebSocketSSLIntegrationTest,
  17708. ReconnectWhileOpenSendsCloseOverLiveSession) {
  17709. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17710. "/ws-echo");
  17711. client.enable_server_certificate_verification(false);
  17712. client.set_read_timeout(2, 0);
  17713. client.set_write_timeout(2, 0);
  17714. ASSERT_TRUE(client.connect());
  17715. ASSERT_TRUE(client.is_open());
  17716. ASSERT_TRUE(client.send("still open"));
  17717. // Reconnect without closing first: connect() calls shutdown_and_close() on
  17718. // the still-open connection, which must not touch a freed TLS session.
  17719. ASSERT_TRUE(client.connect());
  17720. ASSERT_TRUE(client.is_open());
  17721. ASSERT_TRUE(client.send("after reconnect"));
  17722. std::string msg;
  17723. EXPECT_EQ(ws::Text, client.read(msg));
  17724. EXPECT_EQ("after reconnect", msg);
  17725. client.close();
  17726. }
  17727. #endif
  17728. #ifdef CPPHTTPLIB_SSL_ENABLED
  17729. class WebSocketSSLCATest : public ::testing::Test {
  17730. protected:
  17731. void SetUp() override {
  17732. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  17733. SERVER_PRIVATE_KEY_FILE);
  17734. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17735. std::string msg;
  17736. while (ws.read(msg)) {
  17737. ws.send(msg);
  17738. }
  17739. });
  17740. port_ = server_->bind_to_any_port("127.0.0.1");
  17741. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17742. server_->wait_until_ready();
  17743. }
  17744. void TearDown() override {
  17745. server_->stop();
  17746. if (server_thread_.joinable()) { server_thread_.join(); }
  17747. }
  17748. std::string url() const {
  17749. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  17750. }
  17751. std::unique_ptr<SSLServer> server_;
  17752. std::thread server_thread_;
  17753. int port_ = 0;
  17754. };
  17755. // A custom CA loaded as PEM verifies the server with full certificate
  17756. // verification enabled
  17757. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  17758. ws::WebSocketClient client(url());
  17759. std::string cert;
  17760. read_file(SERVER_CERT2_FILE, cert);
  17761. client.load_ca_cert_store(cert.c_str(), cert.size());
  17762. ASSERT_TRUE(client.connect());
  17763. ASSERT_TRUE(client.send("hello"));
  17764. std::string msg;
  17765. EXPECT_EQ(ws::Text, client.read(msg));
  17766. EXPECT_EQ("hello", msg);
  17767. client.close();
  17768. }
  17769. // A custom CA that does not cover the server must fail verification (the
  17770. // custom CA is exclusive; system certs are not loaded alongside it)
  17771. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  17772. ws::WebSocketClient client(url());
  17773. std::string cert;
  17774. read_file(CLIENT_CA_CERT_FILE, cert);
  17775. client.load_ca_cert_store(cert.c_str(), cert.size());
  17776. auto res = client.connect();
  17777. ASSERT_FALSE(res);
  17778. EXPECT_EQ(Error::SSLServerVerification, res.error());
  17779. EXPECT_EQ(-1, res.status());
  17780. EXPECT_NE(0u, res.ssl_backend_error());
  17781. }
  17782. // The same CA as a file path rather than PEM in memory
  17783. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  17784. ws::WebSocketClient client(url());
  17785. client.set_ca_cert_path(SERVER_CERT2_FILE);
  17786. ASSERT_TRUE(client.connect());
  17787. ASSERT_TRUE(client.send("hello"));
  17788. std::string msg;
  17789. EXPECT_EQ(ws::Text, client.read(msg));
  17790. EXPECT_EQ("hello", msg);
  17791. client.close();
  17792. }
  17793. // ...and a CA file that does not cover the server still fails, so it is the
  17794. // path above that decides the outcome
  17795. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  17796. ws::WebSocketClient client(url());
  17797. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  17798. ASSERT_FALSE(client.connect());
  17799. }
  17800. // Regression test: reconnecting with a native custom CA store used to reuse
  17801. // a store handle the previous TLS context had already freed (use-after-free
  17802. // under the OpenSSL backend). The context now lives as long as the client.
  17803. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  17804. ws::WebSocketClient client(url());
  17805. std::string cert;
  17806. read_file(SERVER_CERT2_FILE, cert);
  17807. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  17808. ASSERT_TRUE(client.connect());
  17809. client.close();
  17810. ASSERT_TRUE(client.connect());
  17811. ASSERT_TRUE(client.send("again"));
  17812. std::string msg;
  17813. EXPECT_EQ(ws::Text, client.read(msg));
  17814. EXPECT_EQ("again", msg);
  17815. client.close();
  17816. }
  17817. // Regression test: a certificate with a trusted chain but no identity match
  17818. // for the server IP must be rejected. The Mbed TLS backend used to skip
  17819. // verification entirely for IP hosts, so this connection succeeded there.
  17820. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  17821. // chain verification while the identity check must still fail.
  17822. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  17823. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17824. ASSERT_TRUE(svr.is_valid());
  17825. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17826. std::string msg;
  17827. while (ws.read(msg)) {
  17828. ws.send(msg);
  17829. }
  17830. });
  17831. auto port = svr.bind_to_any_port("127.0.0.1");
  17832. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17833. auto se = detail::scope_exit([&] {
  17834. svr.stop();
  17835. t.join();
  17836. });
  17837. svr.wait_until_ready();
  17838. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  17839. "/echo");
  17840. std::string cert;
  17841. read_file(SERVER_CERT_FILE, cert);
  17842. client.load_ca_cert_store(cert.c_str(), cert.size());
  17843. ASSERT_FALSE(client.connect());
  17844. }
  17845. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  17846. // SNI, so nothing binds the host name to the TLS session. These bind the
  17847. // server to "localhost" instead, the only shape that exercises the SNI and
  17848. // hostname-verification path with certificate verification left enabled.
  17849. class WebSocketSSLDnsHostTest : public ::testing::Test {
  17850. protected:
  17851. void Start(const char *cert_file) {
  17852. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  17853. SERVER_PRIVATE_KEY_FILE);
  17854. ASSERT_TRUE(server_->is_valid());
  17855. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17856. std::string msg;
  17857. while (ws.read(msg)) {
  17858. ws.send(msg);
  17859. }
  17860. });
  17861. port_ = server_->bind_to_any_port("localhost");
  17862. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17863. server_->wait_until_ready();
  17864. }
  17865. void TearDown() override {
  17866. if (server_) { server_->stop(); }
  17867. if (server_thread_.joinable()) { server_thread_.join(); }
  17868. }
  17869. std::string url() const {
  17870. return "wss://localhost:" + std::to_string(port_) + "/echo";
  17871. }
  17872. std::unique_ptr<SSLServer> server_;
  17873. std::thread server_thread_;
  17874. int port_ = 0;
  17875. };
  17876. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  17877. // out and the connection is usable
  17878. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  17879. Start(SERVER_CERT2_FILE);
  17880. ws::WebSocketClient client(url());
  17881. client.set_ca_cert_path(SERVER_CERT2_FILE);
  17882. ASSERT_TRUE(client.connect());
  17883. ASSERT_TRUE(client.send("hello"));
  17884. std::string msg;
  17885. EXPECT_EQ(ws::Text, client.read(msg));
  17886. EXPECT_EQ("hello", msg);
  17887. client.close();
  17888. }
  17889. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  17890. // while the identity check must still reject "localhost"
  17891. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  17892. Start(SERVER_CERT_FILE);
  17893. ws::WebSocketClient client(url());
  17894. client.set_ca_cert_path(SERVER_CERT_FILE);
  17895. auto res = client.connect();
  17896. ASSERT_FALSE(res);
  17897. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  17898. EXPECT_EQ(-1, res.status());
  17899. }
  17900. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  17901. // disabled: the chain is still checked, only the identity check is skipped
  17902. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  17903. Start(SERVER_CERT_FILE);
  17904. ws::WebSocketClient client(url());
  17905. client.set_ca_cert_path(SERVER_CERT_FILE);
  17906. client.enable_server_hostname_verification(false);
  17907. ASSERT_TRUE(client.connect());
  17908. ASSERT_TRUE(client.send("hello"));
  17909. std::string msg;
  17910. EXPECT_EQ(ws::Text, client.read(msg));
  17911. EXPECT_EQ("hello", msg);
  17912. client.close();
  17913. }
  17914. // A CA that did not sign the server certificate fails the chain, even though
  17915. // the name would match
  17916. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  17917. Start(SERVER_CERT2_FILE);
  17918. ws::WebSocketClient client(url());
  17919. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  17920. ASSERT_FALSE(client.connect());
  17921. }
  17922. // With verification disabled, neither the chain nor the name is checked
  17923. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  17924. Start(SERVER_CERT_FILE);
  17925. ws::WebSocketClient client(url());
  17926. client.enable_server_certificate_verification(false);
  17927. ASSERT_TRUE(client.connect());
  17928. ASSERT_TRUE(client.send("hello"));
  17929. std::string msg;
  17930. EXPECT_EQ(ws::Text, client.read(msg));
  17931. EXPECT_EQ("hello", msg);
  17932. client.close();
  17933. }
  17934. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  17935. protected:
  17936. void SetUp() override {
  17937. server_ = httplib::detail::make_unique<SSLServer>(
  17938. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17939. ASSERT_TRUE(server_->is_valid());
  17940. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17941. std::string msg;
  17942. while (ws.read(msg)) {
  17943. ws.send(msg);
  17944. }
  17945. });
  17946. port_ = server_->bind_to_any_port("localhost");
  17947. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17948. server_->wait_until_ready();
  17949. }
  17950. void TearDown() override {
  17951. server_->stop();
  17952. if (server_thread_.joinable()) { server_thread_.join(); }
  17953. }
  17954. std::string url() const {
  17955. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  17956. }
  17957. void ConnectWithClientCert(const std::string &client_cert_file,
  17958. const std::string &client_private_key_file,
  17959. const char *private_key_password) {
  17960. std::string cert_pem, key_pem;
  17961. read_file(client_cert_file, cert_pem);
  17962. read_file(client_private_key_file, key_pem);
  17963. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  17964. key_pem.c_str(), key_pem.size(),
  17965. private_key_password};
  17966. ws::WebSocketClient client(url(), pem);
  17967. ASSERT_TRUE(client.is_valid());
  17968. client.enable_server_certificate_verification(false);
  17969. ASSERT_TRUE(client.connect());
  17970. ASSERT_TRUE(client.send("hello"));
  17971. std::string msg;
  17972. EXPECT_EQ(ws::Text, client.read(msg));
  17973. EXPECT_EQ("hello", msg);
  17974. client.close();
  17975. }
  17976. std::unique_ptr<SSLServer> server_;
  17977. std::thread server_thread_;
  17978. int port_ = 0;
  17979. };
  17980. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  17981. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  17982. }
  17983. // Control for the tests above: the fixture's server really does require a
  17984. // client certificate, so it is the PEM the constructor installed that decides
  17985. // the outcome.
  17986. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  17987. ws::WebSocketClient client(url());
  17988. ASSERT_TRUE(client.is_valid());
  17989. client.enable_server_certificate_verification(false);
  17990. EXPECT_FALSE(client.connect());
  17991. }
  17992. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  17993. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  17994. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  17995. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  17996. }
  17997. #endif
  17998. #if !defined(_WIN32)
  17999. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  18000. auto secret_dir = std::string("./symlink_test_secret");
  18001. auto served_dir = std::string("./symlink_test_served");
  18002. auto secret_file = secret_dir + "/secret.txt";
  18003. auto symlink_path = served_dir + "/escape";
  18004. // Setup: create directories and files
  18005. mkdir(secret_dir.c_str(), 0755);
  18006. mkdir(served_dir.c_str(), 0755);
  18007. {
  18008. std::ofstream ofs(secret_file);
  18009. ofs << "SECRET_DATA";
  18010. }
  18011. // Create symlink using absolute path so it resolves correctly
  18012. #ifdef PATH_MAX
  18013. char abs_secret[PATH_MAX];
  18014. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  18015. #else
  18016. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  18017. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  18018. ASSERT_NE(nullptr, abs_secret);
  18019. #endif
  18020. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  18021. auto se = detail::scope_exit([&] {
  18022. unlink(symlink_path.c_str());
  18023. unlink(secret_file.c_str());
  18024. rmdir(served_dir.c_str());
  18025. rmdir(secret_dir.c_str());
  18026. });
  18027. Server svr;
  18028. svr.set_mount_point("/", served_dir);
  18029. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18030. auto se2 = detail::scope_exit([&] {
  18031. svr.stop();
  18032. listen_thread.join();
  18033. });
  18034. svr.wait_until_ready();
  18035. Client cli("localhost", PORT);
  18036. // Symlink pointing outside base dir should be blocked
  18037. auto res = cli.Get("/escape/secret.txt");
  18038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18039. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18040. }
  18041. #endif
  18042. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  18043. // A GET request with Content-Length to a static file handler must have its
  18044. // body drained before the keep-alive connection is reused. Otherwise the
  18045. // unread body bytes are interpreted as the next HTTP request.
  18046. //
  18047. // The body is sent AFTER receiving the first response (as in the original
  18048. // PoC) so that the stream_line_reader cannot buffer it together with the
  18049. // headers of the first request.
  18050. Server svr;
  18051. svr.set_mount_point("/", "./www");
  18052. std::atomic<int> smuggled_count(0);
  18053. svr.Get("/smuggled", [&](const Request &, Response &res) {
  18054. smuggled_count++;
  18055. res.set_content("oops", "text/plain");
  18056. });
  18057. auto port = svr.bind_to_any_port("localhost");
  18058. thread t = thread([&] { svr.listen_after_bind(); });
  18059. auto se = detail::scope_exit([&] {
  18060. svr.stop();
  18061. t.join();
  18062. });
  18063. svr.wait_until_ready();
  18064. auto error = Error::Success;
  18065. auto sock = detail::create_client_socket(
  18066. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  18067. /*connection_timeout_sec=*/2, 0,
  18068. /*read_timeout_sec=*/2, 0,
  18069. /*write_timeout_sec=*/2, 0, std::string(), error);
  18070. ASSERT_NE(INVALID_SOCKET, sock);
  18071. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18072. // The "smuggled" request will be sent as the body of the outer GET
  18073. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  18074. "Host: localhost\r\n"
  18075. "Connection: close\r\n"
  18076. "\r\n";
  18077. // Step 1: Send only the outer request headers (no body yet)
  18078. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  18079. "Host: localhost\r\n"
  18080. "Content-Length: " +
  18081. std::to_string(smuggled.size()) +
  18082. "\r\n"
  18083. "\r\n";
  18084. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  18085. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  18086. // Step 2: Read the first response (server serves file without reading body)
  18087. std::string first_response;
  18088. char buf[4096];
  18089. for (;;) {
  18090. auto n = recv(sock, buf, sizeof(buf), 0);
  18091. if (n <= 0) break;
  18092. first_response.append(buf, static_cast<size_t>(n));
  18093. // Stop once we have a complete response (headers + body)
  18094. auto hdr_end = first_response.find("\r\n\r\n");
  18095. if (hdr_end != std::string::npos) {
  18096. // Check for Content-Length to know when the body is complete
  18097. auto cl_pos = first_response.find("Content-Length:");
  18098. if (cl_pos != std::string::npos) {
  18099. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  18100. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  18101. auto cl = std::stoul(
  18102. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  18103. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  18104. } else {
  18105. break; // No Content-Length, assume headers-only response
  18106. }
  18107. }
  18108. }
  18109. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  18110. // Step 3: Now send the body, which looks like a new HTTP request.
  18111. // On a vulnerable server the keep-alive loop reads this as a second request.
  18112. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  18113. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  18114. // Step 4: Try to read a second response (should NOT exist after fix)
  18115. std::string second_response;
  18116. for (;;) {
  18117. auto n = recv(sock, buf, sizeof(buf), 0);
  18118. if (n <= 0) break;
  18119. second_response.append(buf, static_cast<size_t>(n));
  18120. }
  18121. // The smuggled request must NOT have been processed
  18122. EXPECT_EQ(0, smuggled_count.load());
  18123. }
  18124. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18125. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  18126. // must be rejected with 400 Bad Request.
  18127. Server svr;
  18128. svr.Post("/test", [&](const Request &, Response &res) {
  18129. res.set_content("ok", "text/plain");
  18130. });
  18131. thread t = thread([&] { svr.listen(HOST, PORT); });
  18132. auto se = detail::scope_exit([&] {
  18133. svr.stop();
  18134. t.join();
  18135. ASSERT_FALSE(svr.is_running());
  18136. });
  18137. svr.wait_until_ready();
  18138. // Exact "chunked"
  18139. {
  18140. auto req = "POST /test HTTP/1.1\r\n"
  18141. "Host: localhost\r\n"
  18142. "Content-Length: 5\r\n"
  18143. "Transfer-Encoding: chunked\r\n"
  18144. "Connection: close\r\n"
  18145. "\r\n"
  18146. "hello";
  18147. std::string response;
  18148. ASSERT_TRUE(send_request(1, req, &response));
  18149. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18150. response.substr(0, response.find("\r\n")));
  18151. }
  18152. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  18153. {
  18154. auto req = "POST /test HTTP/1.1\r\n"
  18155. "Host: localhost\r\n"
  18156. "Content-Length: 5\r\n"
  18157. "Transfer-Encoding: gzip, chunked\r\n"
  18158. "Connection: close\r\n"
  18159. "\r\n"
  18160. "hello";
  18161. std::string response;
  18162. ASSERT_TRUE(send_request(1, req, &response));
  18163. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18164. response.substr(0, response.find("\r\n")));
  18165. }
  18166. }
  18167. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  18168. Server svr;
  18169. svr.Post("/test", [&](const Request &, Response &res) {
  18170. res.set_content("ok", "text/plain");
  18171. });
  18172. thread t = thread([&] { svr.listen(HOST, PORT); });
  18173. auto se = detail::scope_exit([&] {
  18174. svr.stop();
  18175. t.join();
  18176. ASSERT_FALSE(svr.is_running());
  18177. });
  18178. svr.wait_until_ready();
  18179. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  18180. // length cannot be determined, so the server must answer 400 and close
  18181. // rather than treat the request as bodyless and leave the body in the
  18182. // socket for the next request to pick up.
  18183. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  18184. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  18185. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  18186. std::string response;
  18187. ASSERT_TRUE(send_request(1, req, &response));
  18188. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18189. response.substr(0, response.find("\r\n")))
  18190. << transfer_encoding;
  18191. }
  18192. // RFC 9110 5.3: the codings may also be split across several
  18193. // Transfer-Encoding lines, which combine in the order they were received.
  18194. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  18195. // just like the single-line "chunked, gzip" above.
  18196. {
  18197. auto req = "POST /test HTTP/1.1\r\n"
  18198. "Host: localhost\r\n"
  18199. "Transfer-Encoding: chunked\r\n"
  18200. "Transfer-Encoding: gzip\r\n"
  18201. "\r\n"
  18202. "0\r\n\r\n";
  18203. std::string response;
  18204. ASSERT_TRUE(send_request(1, req, &response));
  18205. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18206. response.substr(0, response.find("\r\n")));
  18207. }
  18208. // A sequence ending in chunked stays valid.
  18209. auto req = "POST /test HTTP/1.1\r\n"
  18210. "Host: localhost\r\n"
  18211. "Transfer-Encoding: gzip, chunked\r\n"
  18212. "Connection: close\r\n"
  18213. "\r\n"
  18214. "0\r\n\r\n";
  18215. std::string response;
  18216. ASSERT_TRUE(send_request(1, req, &response));
  18217. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18218. // ...including when it is spread over several lines.
  18219. auto split_req = "POST /test HTTP/1.1\r\n"
  18220. "Host: localhost\r\n"
  18221. "Transfer-Encoding: gzip\r\n"
  18222. "Transfer-Encoding: chunked\r\n"
  18223. "Connection: close\r\n"
  18224. "\r\n"
  18225. "0\r\n\r\n";
  18226. std::string split_response;
  18227. ASSERT_TRUE(send_request(1, split_req, &split_response));
  18228. EXPECT_EQ("HTTP/1.1 200 OK",
  18229. split_response.substr(0, split_response.find("\r\n")));
  18230. }
  18231. // Regression for issue #2450: a DELETE without Content-Length on a
  18232. // keep-alive connection must not let the post-response drain consume the
  18233. // next request's bytes.
  18234. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  18235. Server svr;
  18236. std::atomic<int> delete_count(0);
  18237. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  18238. delete_count++;
  18239. res.status = StatusCode::NoContent_204;
  18240. });
  18241. auto port = svr.bind_to_any_port(HOST);
  18242. thread t = thread([&] { svr.listen_after_bind(); });
  18243. auto se = detail::scope_exit([&] {
  18244. svr.stop();
  18245. t.join();
  18246. });
  18247. svr.wait_until_ready();
  18248. auto error = Error::Success;
  18249. auto sock = detail::create_client_socket(
  18250. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18251. /*connection_timeout_sec=*/2, 0,
  18252. /*read_timeout_sec=*/2, 0,
  18253. /*write_timeout_sec=*/2, 0, std::string(), error);
  18254. ASSERT_NE(INVALID_SOCKET, sock);
  18255. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18256. auto send_request_and_read_response = [&](const std::string &req,
  18257. std::string &out) -> bool {
  18258. auto sent = send(sock, req.data(), req.size(), 0);
  18259. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  18260. char buf[4096];
  18261. for (;;) {
  18262. auto n = recv(sock, buf, sizeof(buf), 0);
  18263. if (n <= 0) { return !out.empty(); }
  18264. out.append(buf, static_cast<size_t>(n));
  18265. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  18266. }
  18267. };
  18268. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  18269. "Host: localhost\r\n"
  18270. "\r\n";
  18271. std::string resp1;
  18272. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  18273. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  18274. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  18275. "Host: localhost\r\n"
  18276. "Connection: close\r\n"
  18277. "\r\n";
  18278. std::string resp2;
  18279. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  18280. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  18281. EXPECT_EQ(2, delete_count.load());
  18282. }
  18283. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  18284. Server svr;
  18285. svr.Post("/ingest", [&](const Request &, Response &res,
  18286. const ContentReader &content_reader) {
  18287. auto consumed = content_reader([](const char *, size_t) { return false; });
  18288. EXPECT_FALSE(consumed);
  18289. res.status = StatusCode::Conflict_409;
  18290. res.set_header("Connection", "close");
  18291. });
  18292. auto port = svr.bind_to_any_port(HOST);
  18293. thread t = thread([&] { svr.listen_after_bind(); });
  18294. auto se = detail::scope_exit([&] {
  18295. svr.stop();
  18296. t.join();
  18297. });
  18298. svr.wait_until_ready();
  18299. auto error = Error::Success;
  18300. auto sock = detail::create_client_socket(
  18301. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18302. /*connection_timeout_sec=*/2, 0,
  18303. /*read_timeout_sec=*/1, 0,
  18304. /*write_timeout_sec=*/2, 0, std::string(), error);
  18305. ASSERT_NE(INVALID_SOCKET, sock);
  18306. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18307. std::string request = "POST /ingest HTTP/1.1\r\n"
  18308. "Host: localhost\r\n"
  18309. "Transfer-Encoding: chunked\r\n"
  18310. "\r\n"
  18311. "4\r\n"
  18312. "data\r\n";
  18313. auto sent = send(sock, request.data(), request.size(), 0);
  18314. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  18315. std::string response;
  18316. ssize_t received = 0;
  18317. do {
  18318. char buf[4096];
  18319. received = recv(sock, buf, sizeof(buf), 0);
  18320. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  18321. } while (received > 0);
  18322. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  18323. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  18324. EXPECT_EQ(0, received);
  18325. }
  18326. namespace no_proxy_test {
  18327. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  18328. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  18329. // calling listen().
  18330. class ScopedServer {
  18331. public:
  18332. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  18333. ~ScopedServer() {
  18334. svr_.stop();
  18335. if (th_.joinable()) { th_.join(); }
  18336. }
  18337. Server &svr() { return svr_; }
  18338. int port() const { return port_; }
  18339. void listen() {
  18340. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18341. svr_.wait_until_ready();
  18342. }
  18343. private:
  18344. Server svr_;
  18345. std::thread th_;
  18346. int port_ = 0;
  18347. };
  18348. class ProxyAndTargetServers {
  18349. public:
  18350. ProxyAndTargetServers() {
  18351. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  18352. proxy_hits_++;
  18353. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18354. res.set_content("via-proxy", "text/plain");
  18355. });
  18356. target_.Get(".*", [this](const Request &req, Response &res) {
  18357. target_hits_++;
  18358. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18359. res.set_content("direct", "text/plain");
  18360. });
  18361. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  18362. target_port_ = target_.bind_to_any_port("127.0.0.1");
  18363. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  18364. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  18365. proxy_mock_.wait_until_ready();
  18366. target_.wait_until_ready();
  18367. }
  18368. ~ProxyAndTargetServers() {
  18369. proxy_mock_.stop();
  18370. target_.stop();
  18371. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  18372. if (target_thread_.joinable()) { target_thread_.join(); }
  18373. }
  18374. Server &proxy_mock() { return proxy_mock_; }
  18375. Server &target() { return target_; }
  18376. int proxy_port() const { return proxy_port_; }
  18377. int target_port() const { return target_port_; }
  18378. int proxy_hits() const { return proxy_hits_.load(); }
  18379. int target_hits() const { return target_hits_.load(); }
  18380. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  18381. void reset_counters() {
  18382. proxy_hits_ = 0;
  18383. target_hits_ = 0;
  18384. last_had_proxy_authz_ = false;
  18385. }
  18386. private:
  18387. Server proxy_mock_;
  18388. Server target_;
  18389. std::thread proxy_thread_;
  18390. std::thread target_thread_;
  18391. int proxy_port_ = 0;
  18392. int target_port_ = 0;
  18393. std::atomic<int> proxy_hits_{0};
  18394. std::atomic<int> target_hits_{0};
  18395. std::atomic<bool> last_had_proxy_authz_{false};
  18396. };
  18397. inline std::unique_ptr<Client> make_client(const std::string &host,
  18398. ProxyAndTargetServers &s) {
  18399. auto cli = detail::make_unique<Client>(host, s.target_port());
  18400. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  18401. cli->set_proxy("127.0.0.1", s.proxy_port());
  18402. return cli;
  18403. }
  18404. } // namespace no_proxy_test
  18405. using no_proxy_test::make_client;
  18406. using no_proxy_test::ProxyAndTargetServers;
  18407. TEST(NoProxyTest, ExactHostnameBypasses) {
  18408. ProxyAndTargetServers s;
  18409. auto cli = make_client("example.com", s);
  18410. cli->set_no_proxy({"example.com"});
  18411. auto res = cli->Get("/");
  18412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18413. EXPECT_EQ(0, s.proxy_hits());
  18414. EXPECT_EQ(1, s.target_hits());
  18415. }
  18416. TEST(NoProxyTest, SubdomainBypasses) {
  18417. ProxyAndTargetServers s;
  18418. auto cli = make_client("foo.example.com", s);
  18419. cli->set_no_proxy({"example.com"});
  18420. auto res = cli->Get("/");
  18421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18422. EXPECT_EQ(0, s.proxy_hits());
  18423. EXPECT_EQ(1, s.target_hits());
  18424. }
  18425. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  18426. // Regression guard: "evilexample.com" must not be considered a subdomain
  18427. // of "example.com". Without the dot-boundary rule, a naive endsWith
  18428. // check would let traffic bypass the proxy and leak credentials direct
  18429. // to the attacker host.
  18430. ProxyAndTargetServers s;
  18431. auto cli = make_client("evilexample.com", s);
  18432. cli->set_no_proxy({"example.com"});
  18433. auto res = cli->Get("/");
  18434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18435. EXPECT_GE(s.proxy_hits(), 1);
  18436. EXPECT_EQ(0, s.target_hits());
  18437. }
  18438. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  18439. ProxyAndTargetServers s;
  18440. auto cli = make_client("example.com.evil.com", s);
  18441. cli->set_no_proxy({"example.com"});
  18442. auto res = cli->Get("/");
  18443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18444. EXPECT_GE(s.proxy_hits(), 1);
  18445. EXPECT_EQ(0, s.target_hits());
  18446. }
  18447. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  18448. ProxyAndTargetServers s;
  18449. auto cli = make_client("example.com", s);
  18450. cli->set_no_proxy({".example.com"});
  18451. auto res = cli->Get("/");
  18452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18453. EXPECT_EQ(0, s.proxy_hits());
  18454. EXPECT_EQ(1, s.target_hits());
  18455. }
  18456. TEST(NoProxyTest, CaseInsensitiveHostname) {
  18457. ProxyAndTargetServers s;
  18458. auto cli = make_client("Example.COM", s);
  18459. cli->set_no_proxy({"EXAMPLE.com"});
  18460. auto res = cli->Get("/");
  18461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18462. EXPECT_EQ(0, s.proxy_hits());
  18463. EXPECT_EQ(1, s.target_hits());
  18464. }
  18465. TEST(NoProxyTest, TrailingDotIsNormalized) {
  18466. ProxyAndTargetServers s;
  18467. auto cli = make_client("example.com.", s);
  18468. cli->set_no_proxy({"example.com"});
  18469. auto res = cli->Get("/");
  18470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18471. EXPECT_EQ(0, s.proxy_hits());
  18472. EXPECT_EQ(1, s.target_hits());
  18473. }
  18474. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  18475. // Trailing dots must be normalized on BOTH sides — host and entry.
  18476. // An implementation that only strips the host-side trailing dot would
  18477. // fail to match host "example.com" against entry "example.com." because
  18478. // a literal substring search would compare 11 chars against 12.
  18479. ProxyAndTargetServers s;
  18480. auto cli = make_client("example.com", s);
  18481. cli->set_no_proxy({"example.com."});
  18482. auto res = cli->Get("/");
  18483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18484. EXPECT_EQ(0, s.proxy_hits());
  18485. EXPECT_EQ(1, s.target_hits());
  18486. }
  18487. TEST(NoProxyTest, WildcardBypassesEverything) {
  18488. ProxyAndTargetServers s;
  18489. auto cli = make_client("anything.invalid.test", s);
  18490. cli->set_no_proxy({"*"});
  18491. auto res = cli->Get("/");
  18492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18493. EXPECT_EQ(0, s.proxy_hits());
  18494. EXPECT_EQ(1, s.target_hits());
  18495. }
  18496. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  18497. ProxyAndTargetServers s;
  18498. Client cli("127.0.0.1", s.target_port());
  18499. cli.set_proxy("127.0.0.1", s.proxy_port());
  18500. cli.set_no_proxy({"127.0.0.1"});
  18501. auto res = cli.Get("/");
  18502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18503. EXPECT_EQ(0, s.proxy_hits());
  18504. EXPECT_EQ(1, s.target_hits());
  18505. }
  18506. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  18507. ProxyAndTargetServers s;
  18508. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  18509. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  18510. cli.set_proxy("127.0.0.1", s.proxy_port());
  18511. cli.set_no_proxy({"::1"});
  18512. auto res = cli.Get("/");
  18513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18514. EXPECT_EQ(0, s.proxy_hits());
  18515. EXPECT_EQ(1, s.target_hits());
  18516. }
  18517. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  18518. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  18519. // must still be recognized as IPv6 for CIDR matching. Implementations
  18520. // that detect IPv6 only when the host begins with '[' would parse the
  18521. // host as a hostname and miss the match.
  18522. ProxyAndTargetServers s;
  18523. Client cli("fe80::1", s.target_port());
  18524. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18525. cli.set_proxy("127.0.0.1", s.proxy_port());
  18526. cli.set_no_proxy({"fe80::/10"});
  18527. auto res = cli.Get("/");
  18528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18529. EXPECT_EQ(0, s.proxy_hits());
  18530. EXPECT_EQ(1, s.target_hits());
  18531. }
  18532. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  18533. ProxyAndTargetServers s;
  18534. Client cli("::1", s.target_port());
  18535. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  18536. cli.set_proxy("127.0.0.1", s.proxy_port());
  18537. cli.set_no_proxy({"[::1]"});
  18538. auto res = cli.Get("/");
  18539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18540. EXPECT_EQ(0, s.proxy_hits());
  18541. EXPECT_EQ(1, s.target_hits());
  18542. }
  18543. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  18544. ProxyAndTargetServers s;
  18545. Client cli("fe80::1", s.target_port());
  18546. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18547. cli.set_proxy("127.0.0.1", s.proxy_port());
  18548. cli.set_no_proxy({"[fe80::]/10"});
  18549. auto res = cli.Get("/");
  18550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18551. EXPECT_EQ(0, s.proxy_hits());
  18552. EXPECT_EQ(1, s.target_hits());
  18553. }
  18554. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  18555. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  18556. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  18557. // tricks via address-family conversion.
  18558. ProxyAndTargetServers s;
  18559. Client cli("::ffff:127.0.0.1", s.target_port());
  18560. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  18561. cli.set_proxy("127.0.0.1", s.proxy_port());
  18562. cli.set_no_proxy({"127.0.0.1"});
  18563. auto res = cli.Get("/");
  18564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18565. EXPECT_GE(s.proxy_hits(), 1);
  18566. EXPECT_EQ(0, s.target_hits());
  18567. }
  18568. TEST(NoProxyTest, IPv4CidrMatch) {
  18569. ProxyAndTargetServers s;
  18570. Client cli("127.0.0.1", s.target_port());
  18571. cli.set_proxy("127.0.0.1", s.proxy_port());
  18572. cli.set_no_proxy({"127.0.0.0/8"});
  18573. auto res = cli.Get("/");
  18574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18575. EXPECT_EQ(0, s.proxy_hits());
  18576. EXPECT_EQ(1, s.target_hits());
  18577. }
  18578. TEST(NoProxyTest, IPv4CidrNonMatch) {
  18579. ProxyAndTargetServers s;
  18580. Client cli("127.0.0.1", s.target_port());
  18581. cli.set_proxy("127.0.0.1", s.proxy_port());
  18582. cli.set_no_proxy({"10.0.0.0/8"});
  18583. auto res = cli.Get("/");
  18584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18585. EXPECT_GE(s.proxy_hits(), 1);
  18586. EXPECT_EQ(0, s.target_hits());
  18587. }
  18588. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  18589. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  18590. // IPv4 target matches.
  18591. ProxyAndTargetServers s;
  18592. Client cli("127.0.0.1", s.target_port());
  18593. cli.set_proxy("127.0.0.1", s.proxy_port());
  18594. cli.set_no_proxy({"0.0.0.0/0"});
  18595. auto res = cli.Get("/");
  18596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18597. EXPECT_EQ(0, s.proxy_hits());
  18598. EXPECT_EQ(1, s.target_hits());
  18599. }
  18600. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  18601. ProxyAndTargetServers s;
  18602. Client cli("127.0.0.1", s.target_port());
  18603. cli.set_proxy("127.0.0.1", s.proxy_port());
  18604. cli.set_no_proxy({"127.0.0.1"});
  18605. auto res = cli.Get("/");
  18606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18607. EXPECT_EQ(0, s.proxy_hits());
  18608. EXPECT_EQ(1, s.target_hits());
  18609. }
  18610. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  18611. ProxyAndTargetServers s;
  18612. Client cli("127.0.0.1", s.target_port());
  18613. cli.set_proxy("127.0.0.1", s.proxy_port());
  18614. cli.set_no_proxy({"127.0.0.0/33"});
  18615. auto res = cli.Get("/");
  18616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18617. EXPECT_GE(s.proxy_hits(), 1);
  18618. EXPECT_EQ(0, s.target_hits());
  18619. }
  18620. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  18621. // Empty prefix after the slash must be rejected, not silently treated as /32.
  18622. ProxyAndTargetServers s;
  18623. Client cli("127.0.0.1", s.target_port());
  18624. cli.set_proxy("127.0.0.1", s.proxy_port());
  18625. cli.set_no_proxy({"127.0.0.1/"});
  18626. auto res = cli.Get("/");
  18627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18628. EXPECT_GE(s.proxy_hits(), 1);
  18629. EXPECT_EQ(0, s.target_hits());
  18630. }
  18631. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  18632. ProxyAndTargetServers s;
  18633. auto cli = make_client("internal.corp", s);
  18634. cli->set_proxy_basic_auth("u", "p");
  18635. cli->set_no_proxy({"internal.corp"});
  18636. auto res = cli->Get("/");
  18637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18638. EXPECT_EQ(1, s.target_hits());
  18639. EXPECT_EQ(0, s.proxy_hits());
  18640. EXPECT_FALSE(s.last_had_proxy_authz())
  18641. << "Proxy-Authorization must not be sent direct to the target";
  18642. }
  18643. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  18644. ProxyAndTargetServers s;
  18645. auto cli = make_client("public.example", s);
  18646. cli->set_proxy_basic_auth("u", "p");
  18647. cli->set_no_proxy({"internal.corp"}); // does not match
  18648. auto res = cli->Get("/");
  18649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18650. EXPECT_GE(s.proxy_hits(), 1);
  18651. EXPECT_TRUE(s.last_had_proxy_authz());
  18652. }
  18653. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  18654. ProxyAndTargetServers s;
  18655. auto cli = make_client("anything.test", s);
  18656. auto res = cli->Get("/");
  18657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18658. EXPECT_GE(s.proxy_hits(), 1);
  18659. EXPECT_EQ(0, s.target_hits());
  18660. }
  18661. TEST(NoProxyTest, PortSpecificEntryRejected) {
  18662. ProxyAndTargetServers s;
  18663. auto cli = make_client("example.com", s);
  18664. cli->set_no_proxy({"example.com:8080"});
  18665. auto res = cli->Get("/");
  18666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18667. EXPECT_GE(s.proxy_hits(), 1);
  18668. EXPECT_EQ(0, s.target_hits());
  18669. }
  18670. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  18671. ProxyAndTargetServers s;
  18672. auto cli = make_client("anything.test", s);
  18673. cli->set_no_proxy({"", " ", "\t"});
  18674. auto res = cli->Get("/");
  18675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18676. EXPECT_GE(s.proxy_hits(), 1);
  18677. EXPECT_EQ(0, s.target_hits());
  18678. }
  18679. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  18680. // An entry with leading/trailing whitespace must still match — env-style
  18681. // values are commonly pasted with stray spaces and an implementation
  18682. // that feeds the raw token directly to inet_pton would fail to match
  18683. // valid CIDRs because of the spaces.
  18684. ProxyAndTargetServers s;
  18685. Client cli("127.0.0.1", s.target_port());
  18686. cli.set_proxy("127.0.0.1", s.proxy_port());
  18687. cli.set_no_proxy({" 127.0.0.0/8 "});
  18688. auto res = cli.Get("/");
  18689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18690. EXPECT_EQ(0, s.proxy_hits());
  18691. EXPECT_EQ(1, s.target_hits());
  18692. }
  18693. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  18694. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  18695. // go direct and must NOT carry Proxy-Authorization.
  18696. std::atomic<int> proxy_hits{0};
  18697. std::atomic<int> target_hits{0};
  18698. std::atomic<bool> target_saw_authz{false};
  18699. no_proxy_test::ScopedServer proxy_mock, target;
  18700. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18701. proxy_hits++;
  18702. res.status = 302;
  18703. res.set_header("Location", "http://127.0.0.1:" +
  18704. std::to_string(target.port()) + "/landed");
  18705. });
  18706. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18707. target_hits++;
  18708. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  18709. res.set_content("direct", "text/plain");
  18710. });
  18711. proxy_mock.listen();
  18712. target.listen();
  18713. Client cli("public.example", target.port());
  18714. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18715. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18716. cli.set_proxy_basic_auth("u", "p");
  18717. cli.set_no_proxy({"127.0.0.1"});
  18718. cli.set_follow_location(true);
  18719. auto res = cli.Get("/redir");
  18720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18721. EXPECT_GE(proxy_hits.load(), 1);
  18722. EXPECT_GE(target_hits.load(), 1);
  18723. EXPECT_FALSE(target_saw_authz.load());
  18724. }
  18725. #ifdef CPPHTTPLIB_SSL_ENABLED
  18726. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  18727. // Direct origin replying 407 must not trigger the digest retry; otherwise
  18728. // proxy creds would be sent to the (possibly hostile) origin.
  18729. std::atomic<int> target_hits{0};
  18730. std::atomic<bool> target_saw_proxy_authz{false};
  18731. no_proxy_test::ScopedServer target;
  18732. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18733. target_hits++;
  18734. if (req.has_header("Proxy-Authorization")) {
  18735. target_saw_proxy_authz = true;
  18736. }
  18737. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18738. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  18739. "nonce=\"abc\", algorithm=MD5");
  18740. });
  18741. target.listen();
  18742. // The proxy address is set to the target's port: the bypass MUST kick in;
  18743. // if it doesn't, the test still routes "via proxy" to the same server and
  18744. // the Proxy-Authorization assertion below catches the leak.
  18745. Client cli("evil.example", target.port());
  18746. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  18747. cli.set_proxy("127.0.0.1", target.port());
  18748. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18749. cli.set_no_proxy({"evil.example"});
  18750. auto res = cli.Get("/x");
  18751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18752. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18753. EXPECT_EQ(1, target_hits.load());
  18754. EXPECT_FALSE(target_saw_proxy_authz.load());
  18755. }
  18756. #endif
  18757. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  18758. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  18759. std::atomic<int> proxy_hits{0};
  18760. std::atomic<int> bypass_hits{0};
  18761. std::atomic<bool> proxy_saw_c_url{false};
  18762. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  18763. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  18764. proxy_hits++;
  18765. if (req.path.find("/start") != std::string::npos) {
  18766. res.status = 302;
  18767. res.set_header("Location", "http://127.0.0.1:" +
  18768. std::to_string(bypass_server.port()) +
  18769. "/middle");
  18770. return;
  18771. }
  18772. if (req.path.find("/end") != std::string::npos) {
  18773. proxy_saw_c_url = true;
  18774. res.set_content("c-via-proxy", "text/plain");
  18775. return;
  18776. }
  18777. res.set_content("unexpected", "text/plain");
  18778. });
  18779. // public.example's "advertised" port is arbitrary (the request never lands
  18780. // there — it goes through the proxy), but use a dynamic value to stay
  18781. // friendly with sharded parallel runs.
  18782. int public_port = bypass_server.port();
  18783. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  18784. bypass_hits++;
  18785. res.status = 302;
  18786. res.set_header("Location", "http://public.example:" +
  18787. std::to_string(public_port) + "/end");
  18788. });
  18789. proxy_mock.listen();
  18790. bypass_server.listen();
  18791. Client cli("public.example", public_port);
  18792. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18793. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18794. cli.set_no_proxy({"127.0.0.1"});
  18795. cli.set_follow_location(true);
  18796. auto res = cli.Get("/start");
  18797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18798. EXPECT_EQ(StatusCode::OK_200, res->status);
  18799. EXPECT_EQ("c-via-proxy", res->body);
  18800. EXPECT_GE(proxy_hits.load(), 2);
  18801. EXPECT_GE(bypass_hits.load(), 1);
  18802. EXPECT_TRUE(proxy_saw_c_url.load());
  18803. }
  18804. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  18805. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  18806. // request reconnects to the correct endpoint.
  18807. std::atomic<int> proxy_hits{0};
  18808. std::atomic<int> target_hits{0};
  18809. no_proxy_test::ScopedServer proxy_mock, target;
  18810. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18811. proxy_hits++;
  18812. res.set_content("via-proxy", "text/plain");
  18813. });
  18814. target.svr().Get(".*", [&](const Request &, Response &res) {
  18815. target_hits++;
  18816. res.set_content("direct", "text/plain");
  18817. });
  18818. proxy_mock.listen();
  18819. target.listen();
  18820. Client cli("public.example", target.port());
  18821. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18822. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18823. cli.set_keep_alive(true);
  18824. auto res1 = cli.Get("/a");
  18825. ASSERT_TRUE(res1);
  18826. EXPECT_EQ("via-proxy", res1->body);
  18827. EXPECT_EQ(1, proxy_hits.load());
  18828. EXPECT_EQ(0, target_hits.load());
  18829. cli.set_no_proxy({"public.example"});
  18830. auto res2 = cli.Get("/b");
  18831. ASSERT_TRUE(res2);
  18832. EXPECT_EQ("direct", res2->body);
  18833. EXPECT_EQ(1, proxy_hits.load());
  18834. EXPECT_EQ(1, target_hits.load());
  18835. }
  18836. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  18837. namespace proxy_tunnel_test {
  18838. // SSLServer counterpart to no_proxy_test::ScopedServer.
  18839. class ScopedSSLServer {
  18840. public:
  18841. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  18842. port_ = svr_.bind_to_any_port("127.0.0.1");
  18843. }
  18844. ~ScopedSSLServer() {
  18845. svr_.stop();
  18846. if (th_.joinable()) { th_.join(); }
  18847. }
  18848. SSLServer &svr() { return svr_; }
  18849. int port() const { return port_; }
  18850. void listen() {
  18851. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18852. svr_.wait_until_ready();
  18853. }
  18854. private:
  18855. SSLServer svr_;
  18856. std::thread th_;
  18857. int port_ = 0;
  18858. };
  18859. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  18860. class ScopedConnectProxy {
  18861. public:
  18862. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  18863. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  18864. if (listen_fd_ < 0) { return; }
  18865. int yes = 1;
  18866. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  18867. sockaddr_in a{};
  18868. a.sin_family = AF_INET;
  18869. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18870. a.sin_port = 0;
  18871. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  18872. return;
  18873. }
  18874. socklen_t alen = sizeof(a);
  18875. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  18876. 0) {
  18877. return;
  18878. }
  18879. port_ = ntohs(a.sin_port);
  18880. if (::listen(listen_fd_, 1) != 0) { return; }
  18881. th_ = std::thread([this] { run(); });
  18882. }
  18883. ~ScopedConnectProxy() {
  18884. stop_ = true;
  18885. if (listen_fd_ >= 0) {
  18886. ::shutdown(listen_fd_, SHUT_RDWR);
  18887. ::close(listen_fd_);
  18888. }
  18889. if (th_.joinable()) { th_.join(); }
  18890. }
  18891. int port() const { return port_; }
  18892. int connect_hits() const { return connect_hits_.load(); }
  18893. private:
  18894. void run() {
  18895. while (!stop_.load()) {
  18896. fd_set rfds;
  18897. FD_ZERO(&rfds);
  18898. FD_SET(listen_fd_, &rfds);
  18899. timeval tv{0, 100 * 1000};
  18900. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  18901. if (sel <= 0) { continue; }
  18902. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  18903. if (client_fd < 0) { continue; }
  18904. std::string req;
  18905. char buf[2048];
  18906. while (req.find("\r\n\r\n") == std::string::npos) {
  18907. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  18908. if (n <= 0) { break; }
  18909. req.append(buf, static_cast<size_t>(n));
  18910. }
  18911. if (req.compare(0, 7, "CONNECT") != 0) {
  18912. ::close(client_fd);
  18913. continue;
  18914. }
  18915. connect_hits_++;
  18916. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  18917. ::send(client_fd, ok, std::strlen(ok), 0);
  18918. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  18919. sockaddr_in o{};
  18920. o.sin_family = AF_INET;
  18921. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18922. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  18923. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  18924. 0) {
  18925. ::close(client_fd);
  18926. ::close(origin_fd);
  18927. continue;
  18928. }
  18929. auto forward = [](int from, int to) {
  18930. char b[8192];
  18931. for (;;) {
  18932. ssize_t n = ::recv(from, b, sizeof(b), 0);
  18933. if (n <= 0) { break; }
  18934. ssize_t off = 0;
  18935. while (off < n) {
  18936. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  18937. if (s <= 0) {
  18938. off = n;
  18939. break;
  18940. }
  18941. off += s;
  18942. }
  18943. }
  18944. ::shutdown(to, SHUT_WR);
  18945. };
  18946. std::thread t1([&] { forward(client_fd, origin_fd); });
  18947. std::thread t2([&] { forward(origin_fd, client_fd); });
  18948. t1.join();
  18949. t2.join();
  18950. ::close(client_fd);
  18951. ::close(origin_fd);
  18952. }
  18953. }
  18954. int forward_port_ = -1;
  18955. int listen_fd_ = -1;
  18956. int port_ = 0;
  18957. std::thread th_;
  18958. std::atomic<bool> stop_{false};
  18959. std::atomic<int> connect_hits_{0};
  18960. };
  18961. } // namespace proxy_tunnel_test
  18962. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  18963. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  18964. // retry; otherwise proxy creds would be sent to the origin.
  18965. std::atomic<int> origin_hits{0};
  18966. std::atomic<bool> origin_saw_proxy_authz{false};
  18967. proxy_tunnel_test::ScopedSSLServer origin;
  18968. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  18969. origin_hits++;
  18970. if (req.has_header("Proxy-Authorization")) {
  18971. origin_saw_proxy_authz = true;
  18972. }
  18973. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18974. res.set_header("Proxy-Authenticate",
  18975. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  18976. "algorithm=MD5");
  18977. });
  18978. origin.listen();
  18979. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  18980. ASSERT_NE(0, proxy.port());
  18981. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  18982. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  18983. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  18984. // and answer with its own status, making this test flaky.
  18985. SSLClient cli("127.0.0.1", origin.port());
  18986. cli.enable_server_certificate_verification(false);
  18987. cli.set_proxy("127.0.0.1", proxy.port());
  18988. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18989. auto res = cli.Get("/x");
  18990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18991. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18992. EXPECT_EQ(1, origin_hits.load());
  18993. EXPECT_FALSE(origin_saw_proxy_authz.load());
  18994. EXPECT_EQ(1, proxy.connect_hits());
  18995. }
  18996. #endif