test.cc 720 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597
  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(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  595. string original = "Piri Tommy Villiers - on & on";
  596. string encoded = httplib::encode_uri_component(original);
  597. string decoded = httplib::decode_uri_component(encoded);
  598. EXPECT_EQ(decoded, original);
  599. }
  600. TEST(TrimTests, TrimStringTests) {
  601. EXPECT_EQ("abc", detail::trim_copy("abc"));
  602. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  603. EXPECT_TRUE(detail::trim_copy("").empty());
  604. }
  605. TEST(AsciiTest, LocaleIndependentClassification) {
  606. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  607. // which consult the global C locale: std::isalnum(0xC5) can return true
  608. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  609. // helpers must classify every byte by the ASCII grammar alone.
  610. for (int i = 0; i < 256; i++) {
  611. auto c = static_cast<char>(i);
  612. auto is_digit = i >= '0' && i <= '9';
  613. auto is_upper = i >= 'A' && i <= 'Z';
  614. auto is_lower = i >= 'a' && i <= 'z';
  615. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  616. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  617. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  618. << "byte " << i;
  619. }
  620. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  621. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  622. // Non-ASCII bytes must be percent-encoded, never passed through as
  623. // alphanumeric.
  624. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  625. }
  626. TEST(FromCharsTest, Double) {
  627. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  628. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  629. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  630. auto parse = [](const std::string &s, double &v) {
  631. return detail::from_chars(s.data(), s.data() + s.size(), v);
  632. };
  633. double v = -1.0;
  634. // Representative quality values.
  635. EXPECT_EQ(parse("0", v).ec, std::errc{});
  636. EXPECT_DOUBLE_EQ(v, 0.0);
  637. EXPECT_EQ(parse("1", v).ec, std::errc{});
  638. EXPECT_DOUBLE_EQ(v, 1.0);
  639. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  640. EXPECT_DOUBLE_EQ(v, 0.8);
  641. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  642. EXPECT_DOUBLE_EQ(v, 0.001);
  643. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  644. EXPECT_DOUBLE_EQ(v, 1.0);
  645. // A missing integer or fractional part is tolerated.
  646. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  647. EXPECT_DOUBLE_EQ(v, 0.5);
  648. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  649. EXPECT_DOUBLE_EQ(v, 5.0);
  650. // Values outside [0, 1] still parse; the caller range-checks them.
  651. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  652. EXPECT_DOUBLE_EQ(v, 123.456);
  653. // Stops at the first byte that is not part of the number and reports where.
  654. std::string trailing = "0.9, text/html";
  655. auto r = parse(trailing, v);
  656. EXPECT_EQ(r.ec, std::errc{});
  657. EXPECT_DOUBLE_EQ(v, 0.9);
  658. EXPECT_EQ(*r.ptr, ',');
  659. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  660. // outright, and an 'e'/'E' simply ends the number.
  661. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  662. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  663. std::string exp_input = "1.5e3";
  664. r = parse(exp_input, v);
  665. EXPECT_EQ(r.ec, std::errc{});
  666. EXPECT_DOUBLE_EQ(v, 1.5);
  667. EXPECT_EQ(*r.ptr, 'e');
  668. // Invalid inputs.
  669. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  670. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  671. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  672. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  673. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  674. // Pathological but well-formed inputs must stay bounded (no overflow, no
  675. // out-of-bounds table access) and stay within [0, 1] for the caller.
  676. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  677. std::errc{});
  678. EXPECT_DOUBLE_EQ(v, 0.0);
  679. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  680. std::errc{});
  681. EXPECT_GE(v, 0.0);
  682. EXPECT_LE(v, 1.0);
  683. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  684. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  685. }
  686. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  687. // Simple case without quality values
  688. std::vector<std::string> result1;
  689. EXPECT_TRUE(detail::parse_accept_header(
  690. "text/html,application/json,text/plain", result1));
  691. EXPECT_EQ(result1.size(), 3U);
  692. EXPECT_EQ(result1[0], "text/html");
  693. EXPECT_EQ(result1[1], "application/json");
  694. EXPECT_EQ(result1[2], "text/plain");
  695. // With quality values
  696. std::vector<std::string> result2;
  697. EXPECT_TRUE(detail::parse_accept_header(
  698. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  699. EXPECT_EQ(result2.size(), 3U);
  700. EXPECT_EQ(result2[0], "application/json"); // highest q value
  701. EXPECT_EQ(result2[1], "text/html");
  702. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  703. }
  704. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  705. // Mixed with and without quality values
  706. std::vector<std::string> result;
  707. EXPECT_TRUE(detail::parse_accept_header(
  708. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  709. EXPECT_EQ(result.size(), 3U);
  710. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  711. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  712. EXPECT_EQ(result[2], "application/json"); // q=0.5
  713. }
  714. TEST(ParseAcceptHeaderTest, EdgeCases) {
  715. // Empty header
  716. std::vector<std::string> empty_result;
  717. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  718. EXPECT_TRUE(empty_result.empty());
  719. // Single type
  720. std::vector<std::string> single_result;
  721. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  722. EXPECT_EQ(single_result.size(), 1U);
  723. EXPECT_EQ(single_result[0], "application/json");
  724. // Wildcard types
  725. std::vector<std::string> wildcard_result;
  726. EXPECT_TRUE(detail::parse_accept_header(
  727. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  728. EXPECT_EQ(wildcard_result.size(), 3U);
  729. EXPECT_EQ(wildcard_result[0], "application/json");
  730. EXPECT_EQ(wildcard_result[1], "text/*");
  731. EXPECT_EQ(wildcard_result[2], "*/*");
  732. }
  733. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  734. // Common browser Accept header
  735. std::vector<std::string> browser_result;
  736. EXPECT_TRUE(
  737. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  738. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  739. browser_result));
  740. EXPECT_EQ(browser_result.size(), 6U);
  741. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  742. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  743. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  744. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  745. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  746. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  747. // API client header
  748. std::vector<std::string> api_result;
  749. EXPECT_TRUE(detail::parse_accept_header(
  750. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  751. api_result));
  752. EXPECT_EQ(api_result.size(), 3U);
  753. EXPECT_EQ(api_result[0], "application/json");
  754. EXPECT_EQ(api_result[1], "application/xml");
  755. EXPECT_EQ(api_result[2], "text/plain");
  756. }
  757. TEST(ParseAcceptHeaderTest, SpecialCases) {
  758. // Quality value with 3 decimal places
  759. std::vector<std::string> decimal_result;
  760. EXPECT_TRUE(detail::parse_accept_header(
  761. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  762. EXPECT_EQ(decimal_result.size(), 2U);
  763. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  764. EXPECT_EQ(decimal_result[1], "text/html");
  765. // Zero quality (should still be included but with lowest priority)
  766. std::vector<std::string> zero_q_result;
  767. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  768. zero_q_result));
  769. EXPECT_EQ(zero_q_result.size(), 2U);
  770. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  771. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  772. // No spaces around commas
  773. std::vector<std::string> no_space_result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  776. no_space_result));
  777. EXPECT_EQ(no_space_result.size(), 3U);
  778. EXPECT_EQ(no_space_result[0], "text/html");
  779. EXPECT_EQ(no_space_result[1], "application/json");
  780. EXPECT_EQ(no_space_result[2], "text/plain");
  781. }
  782. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  783. // Quality values always use '.' as the decimal separator, so parsing must
  784. // not depend on the process locale. An embedding application may have
  785. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  786. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  787. std::string saved = cur ? cur : "C";
  788. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  789. "fr_FR.UTF-8"};
  790. bool switched = false;
  791. for (const auto loc : comma_locales) {
  792. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  793. std::localeconv()->decimal_point[0] == ',') {
  794. switched = true;
  795. break;
  796. }
  797. }
  798. if (!switched) {
  799. std::setlocale(LC_NUMERIC, saved.c_str());
  800. GTEST_SKIP() << "no comma-decimal locale available on this host";
  801. }
  802. // The higher-weighted type appears later in the list, so a correct parse
  803. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  804. // sensitive parse reads both weights as 0 and leaves the original order.
  805. std::vector<std::string> result;
  806. EXPECT_TRUE(detail::parse_accept_header(
  807. "application/json;q=0.1,text/html;q=0.9", result));
  808. ASSERT_EQ(result.size(), 2U);
  809. EXPECT_EQ(result[0], "text/html");
  810. EXPECT_EQ(result[1], "application/json");
  811. std::setlocale(LC_NUMERIC, saved.c_str());
  812. }
  813. TEST(ParseAcceptHeaderTest, InvalidCases) {
  814. std::vector<std::string> result;
  815. // Invalid quality value (> 1.0)
  816. EXPECT_FALSE(
  817. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  818. // Invalid quality value (< 0.0)
  819. EXPECT_FALSE(
  820. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  821. // Invalid quality value (not a number)
  822. EXPECT_FALSE(detail::parse_accept_header(
  823. "text/html;q=invalid,application/json", result));
  824. // Empty quality value
  825. EXPECT_FALSE(
  826. detail::parse_accept_header("text/html;q=,application/json", result));
  827. // Invalid media type format (no slash and not wildcard)
  828. EXPECT_FALSE(
  829. detail::parse_accept_header("invalidtype,application/json", result));
  830. // Empty media type
  831. result.clear();
  832. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  833. // Only commas
  834. result.clear();
  835. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  836. // Valid cases should still work
  837. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  838. EXPECT_EQ(result.size(), 1U);
  839. EXPECT_EQ(result[0], "*/*");
  840. EXPECT_TRUE(detail::parse_accept_header("*", result));
  841. EXPECT_EQ(result.size(), 1U);
  842. EXPECT_EQ(result[0], "*");
  843. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  844. EXPECT_EQ(result.size(), 1U);
  845. EXPECT_EQ(result[0], "text/*");
  846. }
  847. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  848. Server svr;
  849. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  850. EXPECT_EQ(req.accept_content_types.size(), 3U);
  851. EXPECT_EQ(req.accept_content_types[0], "application/json");
  852. EXPECT_EQ(req.accept_content_types[1], "text/html");
  853. EXPECT_EQ(req.accept_content_types[2], "*/*");
  854. res.set_content("ok", "text/plain");
  855. });
  856. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  857. EXPECT_TRUE(false);
  858. res.set_content("bad request", "text/plain");
  859. });
  860. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  861. auto se = detail::scope_exit([&] {
  862. svr.stop();
  863. listen_thread.join();
  864. ASSERT_FALSE(svr.is_running());
  865. });
  866. svr.wait_until_ready();
  867. Client cli("localhost", PORT);
  868. {
  869. auto res = cli.Get(
  870. "/accept_ok",
  871. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  873. EXPECT_EQ(StatusCode::OK_200, res->status);
  874. }
  875. {
  876. auto res = cli.Get("/accept_bad_request",
  877. Headers{{"Accept", "text/html;q=abc,application/json"}});
  878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  879. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  880. }
  881. }
  882. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  883. Server svr;
  884. svr.Get("/", [](const Request & /*req*/, Response &res) {
  885. res.set_content("ok", "text/plain");
  886. });
  887. std::atomic<int> start_count{0};
  888. std::atomic<bool> running_when_called{false};
  889. svr.set_start_handler([&]() {
  890. running_when_called = svr.is_running();
  891. start_count++;
  892. });
  893. auto port = svr.bind_to_any_port(HOST);
  894. std::thread t([&]() { svr.listen_after_bind(); });
  895. auto se = detail::scope_exit([&] {
  896. svr.stop();
  897. t.join();
  898. ASSERT_FALSE(svr.is_running());
  899. });
  900. svr.wait_until_ready();
  901. // A successful request proves the accept loop is running, which the start
  902. // handler precedes; so by now the handler must have run exactly once.
  903. Client cli(HOST, port);
  904. cli.set_connection_timeout(std::chrono::seconds(5));
  905. auto res = cli.Get("/");
  906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  907. EXPECT_EQ(StatusCode::OK_200, res->status);
  908. EXPECT_EQ(1, start_count.load());
  909. EXPECT_TRUE(running_when_called.load());
  910. }
  911. TEST(DivideTest, DivideStringTests) {
  912. auto divide = [](const std::string &str, char d) {
  913. std::string lhs;
  914. std::string rhs;
  915. detail::divide(str, d,
  916. [&](const char *lhs_data, std::size_t lhs_size,
  917. const char *rhs_data, std::size_t rhs_size) {
  918. lhs.assign(lhs_data, lhs_size);
  919. rhs.assign(rhs_data, rhs_size);
  920. });
  921. return std::make_pair(std::move(lhs), std::move(rhs));
  922. };
  923. {
  924. const auto res = divide("", '=');
  925. EXPECT_EQ(res.first, "");
  926. EXPECT_EQ(res.second, "");
  927. }
  928. {
  929. const auto res = divide("=", '=');
  930. EXPECT_EQ(res.first, "");
  931. EXPECT_EQ(res.second, "");
  932. }
  933. {
  934. const auto res = divide(" ", '=');
  935. EXPECT_EQ(res.first, " ");
  936. EXPECT_EQ(res.second, "");
  937. }
  938. {
  939. const auto res = divide("a", '=');
  940. EXPECT_EQ(res.first, "a");
  941. EXPECT_EQ(res.second, "");
  942. }
  943. {
  944. const auto res = divide("a=", '=');
  945. EXPECT_EQ(res.first, "a");
  946. EXPECT_EQ(res.second, "");
  947. }
  948. {
  949. const auto res = divide("=b", '=');
  950. EXPECT_EQ(res.first, "");
  951. EXPECT_EQ(res.second, "b");
  952. }
  953. {
  954. const auto res = divide("a=b", '=');
  955. EXPECT_EQ(res.first, "a");
  956. EXPECT_EQ(res.second, "b");
  957. }
  958. {
  959. const auto res = divide("a=b=", '=');
  960. EXPECT_EQ(res.first, "a");
  961. EXPECT_EQ(res.second, "b=");
  962. }
  963. {
  964. const auto res = divide("a=b=c", '=');
  965. EXPECT_EQ(res.first, "a");
  966. EXPECT_EQ(res.second, "b=c");
  967. }
  968. }
  969. TEST(SplitTest, ParseQueryString) {
  970. string s = "key1=val1&key2=val2&key3=val3";
  971. Params dic;
  972. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  973. [&](const char *b, const char *e) {
  974. string key, val;
  975. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  976. if (key.empty()) {
  977. key.assign(b2, e2);
  978. } else {
  979. val.assign(b2, e2);
  980. }
  981. });
  982. dic.emplace(key, val);
  983. });
  984. EXPECT_EQ("val1", dic.find("key1")->second);
  985. EXPECT_EQ("val2", dic.find("key2")->second);
  986. EXPECT_EQ("val3", dic.find("key3")->second);
  987. }
  988. TEST(SplitTest, ParseInvalidQueryTests) {
  989. {
  990. string s = " ";
  991. Params dict;
  992. detail::parse_query_text(s, dict);
  993. EXPECT_TRUE(dict.empty());
  994. }
  995. {
  996. string s = " = =";
  997. Params dict;
  998. detail::parse_query_text(s, dict);
  999. EXPECT_TRUE(dict.empty());
  1000. }
  1001. }
  1002. TEST(ParseQueryTest, ParseQueryString) {
  1003. {
  1004. std::string s = "key1=val1&key2=val2&key3=val3";
  1005. Params dic;
  1006. detail::parse_query_text(s, dic);
  1007. EXPECT_EQ("val1", dic.find("key1")->second);
  1008. EXPECT_EQ("val2", dic.find("key2")->second);
  1009. EXPECT_EQ("val3", dic.find("key3")->second);
  1010. }
  1011. {
  1012. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1013. Params dic;
  1014. detail::parse_query_text(s, dic);
  1015. EXPECT_EQ("", dic.find("key1")->second);
  1016. EXPECT_EQ("val1", dic.find("key2")->second);
  1017. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1018. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1019. }
  1020. }
  1021. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1022. Params dic;
  1023. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1024. dic.emplace("key1", "val1");
  1025. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1026. dic.emplace("key2", "val2");
  1027. dic.emplace("key3", "val3");
  1028. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1029. }
  1030. // Joins every entry of a Headers or Params into "key=value " so a whole
  1031. // traversal can be compared in one assertion. Both are instantiations of the
  1032. // same insertion-ordered container, so one helper serves both.
  1033. template <typename Map> static std::string entries_to_string(const Map &m) {
  1034. std::string s;
  1035. for (const auto &entry : m) {
  1036. s += entry.first + "=" + entry.second + " ";
  1037. }
  1038. return s;
  1039. }
  1040. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1041. // Params used to be a std::multimap, which sorted by name and handed the
  1042. // caller's query back alphabetised. A client signing its query string could
  1043. // not reproduce the order it asked for.
  1044. Params dic;
  1045. dic.emplace("zulu", "1");
  1046. dic.emplace("alpha", "2");
  1047. dic.emplace("mike", "3");
  1048. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1049. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1050. }
  1051. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1052. Params dic;
  1053. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1054. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1055. }
  1056. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1057. Request req;
  1058. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1059. req.params);
  1060. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1061. EXPECT_EQ("first", req.get_param_value("tag"));
  1062. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1063. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1064. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1065. EXPECT_EQ("", req.get_param_value("tag", 3));
  1066. }
  1067. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1068. // Params shares its container with Headers, which matches field names
  1069. // case-insensitively. Parameter names must not pick that up.
  1070. Params dic;
  1071. dic.emplace("Key", "upper");
  1072. dic.emplace("key", "lower");
  1073. EXPECT_EQ(2U, dic.size());
  1074. EXPECT_EQ(1U, dic.count("Key"));
  1075. EXPECT_EQ(1U, dic.count("key"));
  1076. EXPECT_EQ("upper", dic.find("Key")->second);
  1077. EXPECT_EQ("lower", dic.find("key")->second);
  1078. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1079. }
  1080. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1081. Server svr;
  1082. std::string order;
  1083. svr.Get("/order", [&](const Request &req, Response &res) {
  1084. order = entries_to_string(req.params);
  1085. res.set_content("ok", "text/plain");
  1086. });
  1087. auto port = svr.bind_to_any_port(HOST);
  1088. thread t = thread([&] { svr.listen_after_bind(); });
  1089. auto se = detail::scope_exit([&] {
  1090. svr.stop();
  1091. t.join();
  1092. ASSERT_FALSE(svr.is_running());
  1093. });
  1094. svr.wait_until_ready();
  1095. Client cli(HOST, port);
  1096. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1097. ASSERT_TRUE(res);
  1098. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1099. }
  1100. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1101. Server svr;
  1102. std::string field_order, file_order;
  1103. svr.Post("/order", [&](const Request &req, Response &res) {
  1104. for (const auto &field : req.form.fields) {
  1105. field_order += field.first + "=" + field.second.content + " ";
  1106. }
  1107. for (const auto &file : req.form.files) {
  1108. file_order += file.first + "=" + file.second.filename + " ";
  1109. }
  1110. res.set_content("ok", "text/plain");
  1111. });
  1112. auto port = svr.bind_to_any_port(HOST);
  1113. thread t = thread([&] { svr.listen_after_bind(); });
  1114. auto se = detail::scope_exit([&] {
  1115. svr.stop();
  1116. t.join();
  1117. ASSERT_FALSE(svr.is_running());
  1118. });
  1119. svr.wait_until_ready();
  1120. UploadFormDataItems items = {
  1121. {"zulu", "1", "", ""},
  1122. {"alpha", "2", "", ""},
  1123. {"mike", "3", "", ""},
  1124. {"zebra", "z", "z.txt", "text/plain"},
  1125. {"apple", "a", "a.txt", "text/plain"},
  1126. };
  1127. Client cli(HOST, port);
  1128. auto res = cli.Post("/order", items);
  1129. ASSERT_TRUE(res);
  1130. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1131. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1132. }
  1133. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1134. Server svr;
  1135. std::vector<std::string> values;
  1136. std::string first, second, out_of_range, order;
  1137. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1138. values = req.form.get_fields("tag");
  1139. first = req.form.get_field("tag", 0);
  1140. second = req.form.get_field("tag", 1);
  1141. out_of_range = req.form.get_field("tag", 2);
  1142. for (const auto &field : req.form.fields) {
  1143. order += field.first + "=" + field.second.content + " ";
  1144. }
  1145. res.set_content("ok", "text/plain");
  1146. });
  1147. auto port = svr.bind_to_any_port(HOST);
  1148. thread t = thread([&] { svr.listen_after_bind(); });
  1149. auto se = detail::scope_exit([&] {
  1150. svr.stop();
  1151. t.join();
  1152. ASSERT_FALSE(svr.is_running());
  1153. });
  1154. svr.wait_until_ready();
  1155. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1156. // not adjacent in the container.
  1157. UploadFormDataItems items = {
  1158. {"tag", "first", "", ""},
  1159. {"other", "x", "", ""},
  1160. {"tag", "second", "", ""},
  1161. };
  1162. Client cli(HOST, port);
  1163. auto res = cli.Post("/repeated", items);
  1164. ASSERT_TRUE(res);
  1165. ASSERT_EQ(2U, values.size());
  1166. EXPECT_EQ("first", values[0]);
  1167. EXPECT_EQ("second", values[1]);
  1168. EXPECT_EQ("first", first);
  1169. EXPECT_EQ("second", second);
  1170. // std::multimap already kept entries sharing a name in insertion order, so
  1171. // everything above passes without this change too. The whole traversal is
  1172. // what tells the two apart: sorting by name would hoist "other" to the front
  1173. // and the two "tag" parts would end up adjacent.
  1174. EXPECT_EQ("tag=first other=x tag=second ", order);
  1175. // Advancing past the last entry of a name used to run off the container;
  1176. // the container's saturating increment makes it return the default instead.
  1177. EXPECT_EQ("", out_of_range);
  1178. }
  1179. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1180. // Server::read_content() keeps a FormFields::iterator alive across the
  1181. // content callbacks that fill the part it points at. The container is
  1182. // vector-backed, so a later emplace can reallocate and invalidate an older
  1183. // iterator; 64 parts grow the vector through seven reallocations, which
  1184. // checks that every part's content still lands in its own entry.
  1185. const size_t part_count = 64;
  1186. // One formula for both the parts sent and the values expected back, so the
  1187. // two cannot drift apart.
  1188. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1189. auto content_of = [](size_t i) {
  1190. return std::string(64, static_cast<char>('a' + (i % 26)));
  1191. };
  1192. Server svr;
  1193. std::vector<std::pair<std::string, std::string>> received;
  1194. svr.Post("/many", [&](const Request &req, Response &res) {
  1195. for (const auto &field : req.form.fields) {
  1196. received.emplace_back(field.first, field.second.content);
  1197. }
  1198. res.set_content("ok", "text/plain");
  1199. });
  1200. auto port = svr.bind_to_any_port(HOST);
  1201. thread t = thread([&] { svr.listen_after_bind(); });
  1202. auto se = detail::scope_exit([&] {
  1203. svr.stop();
  1204. t.join();
  1205. ASSERT_FALSE(svr.is_running());
  1206. });
  1207. svr.wait_until_ready();
  1208. UploadFormDataItems items;
  1209. for (size_t i = 0; i < part_count; i++) {
  1210. items.push_back({name_of(i), content_of(i), "", ""});
  1211. }
  1212. Client cli(HOST, port);
  1213. auto res = cli.Post("/many", items);
  1214. ASSERT_TRUE(res);
  1215. ASSERT_EQ(part_count, received.size());
  1216. for (size_t i = 0; i < part_count; i++) {
  1217. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1218. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1219. }
  1220. }
  1221. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1222. string content_type = "multipart/form-data; boundary=something";
  1223. string boundary;
  1224. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1225. EXPECT_TRUE(ret);
  1226. EXPECT_EQ(boundary, "something");
  1227. }
  1228. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1229. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1230. string boundary;
  1231. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1232. EXPECT_TRUE(ret);
  1233. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1234. }
  1235. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1236. string content_type =
  1237. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1238. string boundary;
  1239. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1240. EXPECT_TRUE(ret);
  1241. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1242. }
  1243. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1244. string content_type =
  1245. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1246. string boundary;
  1247. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1248. EXPECT_TRUE(ret);
  1249. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1250. }
  1251. TEST(GetHeaderValueTest, DefaultValue) {
  1252. Headers headers = {{"Dummy", "Dummy"}};
  1253. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1254. EXPECT_STREQ("text/plain", val);
  1255. }
  1256. TEST(GetHeaderValueTest, DefaultValueInt) {
  1257. Headers headers = {{"Dummy", "Dummy"}};
  1258. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1259. EXPECT_EQ(100ull, val);
  1260. }
  1261. TEST(GetHeaderValueTest, RegularValue) {
  1262. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1263. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1264. EXPECT_STREQ("text/html", val);
  1265. }
  1266. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1267. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1268. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1269. EXPECT_STREQ("text/html", val);
  1270. }
  1271. TEST(GetHeaderValueTest, SetContent) {
  1272. Response res;
  1273. res.set_content("html", "text/html");
  1274. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1275. res.set_content("text", "text/plain");
  1276. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1277. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1278. }
  1279. TEST(GetHeaderValueTest, RegularValueInt) {
  1280. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1281. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1282. EXPECT_EQ(100ull, val);
  1283. }
  1284. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1285. Headers headers = {{"Content-Length", "x"}};
  1286. auto is_invalid_value = false;
  1287. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1288. is_invalid_value);
  1289. EXPECT_EQ(0ull, val);
  1290. EXPECT_TRUE(is_invalid_value);
  1291. }
  1292. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1293. // An all-digit value that overflows size_t must be reported as invalid, not
  1294. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1295. // a large length to a small one on 32-bit builds, leaving the framing length
  1296. // wrong while is_invalid_value stayed false.
  1297. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1298. auto is_invalid_value = false;
  1299. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1300. is_invalid_value);
  1301. EXPECT_TRUE(is_invalid_value);
  1302. // A well-formed length is unaffected.
  1303. Headers ok = {{"Content-Length", "1234"}};
  1304. is_invalid_value = false;
  1305. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1306. is_invalid_value);
  1307. EXPECT_EQ(1234ull, val);
  1308. EXPECT_FALSE(is_invalid_value);
  1309. }
  1310. TEST(GetHeaderValueTest, Range) {
  1311. {
  1312. Headers headers = {make_range_header({{1, -1}})};
  1313. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1314. EXPECT_STREQ("bytes=1-", val);
  1315. }
  1316. {
  1317. Headers headers = {make_range_header({{-1, 1}})};
  1318. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1319. EXPECT_STREQ("bytes=-1", val);
  1320. }
  1321. {
  1322. Headers headers = {make_range_header({{1, 10}})};
  1323. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1324. EXPECT_STREQ("bytes=1-10", val);
  1325. }
  1326. {
  1327. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1328. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1329. EXPECT_STREQ("bytes=1-10, 100-", val);
  1330. }
  1331. {
  1332. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1333. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1334. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1335. }
  1336. {
  1337. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1338. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1339. EXPECT_STREQ("bytes=0-0, -1", val);
  1340. }
  1341. }
  1342. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1343. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1344. // to depend on the standard library (libstdc++ handed back duplicates in
  1345. // reverse insertion order, libc++ in insertion order).
  1346. Request req;
  1347. req.set_header("Accept-Encoding", "gzip");
  1348. req.set_header("Accept-Encoding", "deflate");
  1349. req.set_header("Accept-Encoding", "br");
  1350. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1351. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1352. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1353. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1354. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1355. }
  1356. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1357. Request req;
  1358. req.set_header("X-Test", "only");
  1359. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1360. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1361. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1362. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1363. }
  1364. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1365. Headers headers;
  1366. headers.emplace("Host", "example.com");
  1367. headers.emplace("Accept-Encoding", "gzip");
  1368. headers.emplace("User-Agent", "test");
  1369. headers.emplace("Accept-Encoding", "deflate");
  1370. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1371. "Accept-Encoding=deflate ",
  1372. entries_to_string(headers));
  1373. }
  1374. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1375. Headers headers = {{"Content-Type", "text/html"},
  1376. {"CONTENT-TYPE", "text/xml"}};
  1377. EXPECT_EQ(2U, headers.count("content-type"));
  1378. auto it = headers.find("content-type");
  1379. ASSERT_TRUE(it != headers.end());
  1380. EXPECT_EQ("text/html", it->second);
  1381. }
  1382. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1383. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1384. // drop only those fields and leave everything positioned between them.
  1385. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1386. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1387. auto rng = headers.equal_range("a");
  1388. headers.erase(rng.first, rng.second);
  1389. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1390. }
  1391. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1392. Headers headers = {
  1393. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1394. EXPECT_EQ(3U, headers.erase("A"));
  1395. EXPECT_EQ(0U, headers.count("A"));
  1396. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1397. }
  1398. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1399. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1400. headers.emplace_front("Host", "example.com");
  1401. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1402. entries_to_string(headers));
  1403. }
  1404. TEST(ParseHeaderValueTest, Range) {
  1405. {
  1406. Ranges ranges;
  1407. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1408. EXPECT_TRUE(ret);
  1409. EXPECT_EQ(1u, ranges.size());
  1410. EXPECT_EQ(1u, ranges[0].first);
  1411. EXPECT_EQ(-1, ranges[0].second);
  1412. }
  1413. {
  1414. Ranges ranges;
  1415. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1416. EXPECT_TRUE(ret);
  1417. EXPECT_EQ(1u, ranges.size());
  1418. EXPECT_EQ(-1, ranges[0].first);
  1419. EXPECT_EQ(1u, ranges[0].second);
  1420. }
  1421. {
  1422. Ranges ranges;
  1423. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1424. EXPECT_TRUE(ret);
  1425. EXPECT_EQ(1u, ranges.size());
  1426. EXPECT_EQ(1u, ranges[0].first);
  1427. EXPECT_EQ(10u, ranges[0].second);
  1428. }
  1429. {
  1430. Ranges ranges;
  1431. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1432. EXPECT_FALSE(ret);
  1433. }
  1434. {
  1435. Ranges ranges;
  1436. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1437. EXPECT_TRUE(ret);
  1438. EXPECT_EQ(2u, ranges.size());
  1439. EXPECT_EQ(1u, ranges[0].first);
  1440. EXPECT_EQ(10u, ranges[0].second);
  1441. EXPECT_EQ(100u, ranges[1].first);
  1442. EXPECT_EQ(-1, ranges[1].second);
  1443. }
  1444. {
  1445. Ranges ranges;
  1446. auto ret =
  1447. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1448. EXPECT_TRUE(ret);
  1449. EXPECT_EQ(3u, ranges.size());
  1450. EXPECT_EQ(1u, ranges[0].first);
  1451. EXPECT_EQ(10u, ranges[0].second);
  1452. EXPECT_EQ(100u, ranges[1].first);
  1453. EXPECT_EQ(200u, ranges[1].second);
  1454. EXPECT_EQ(300u, ranges[2].first);
  1455. EXPECT_EQ(400u, ranges[2].second);
  1456. }
  1457. {
  1458. Ranges ranges;
  1459. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1460. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1461. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1462. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1463. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1464. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1465. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1466. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1467. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1468. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1469. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1470. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1471. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1472. EXPECT_TRUE(ranges.empty());
  1473. }
  1474. }
  1475. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1476. Request req;
  1477. req.set_header("Accept-Encoding", "gzip");
  1478. Response res;
  1479. res.set_header("Content-Type", "text/plain");
  1480. auto ret = detail::encoding_type(req, res);
  1481. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1482. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1483. #else
  1484. EXPECT_TRUE(ret == detail::EncodingType::None);
  1485. #endif
  1486. }
  1487. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1488. Request req;
  1489. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1490. Response res;
  1491. res.set_header("Content-Type", "text/plain");
  1492. auto ret = detail::encoding_type(req, res);
  1493. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1494. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1495. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1496. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1497. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1498. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1499. #else
  1500. EXPECT_TRUE(ret == detail::EncodingType::None);
  1501. #endif
  1502. }
  1503. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1504. Request req;
  1505. req.set_header("Accept-Encoding",
  1506. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1507. Response res;
  1508. res.set_header("Content-Type", "text/plain");
  1509. auto ret = detail::encoding_type(req, res);
  1510. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1511. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1512. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1513. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1514. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1515. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1516. #else
  1517. EXPECT_TRUE(ret == detail::EncodingType::None);
  1518. #endif
  1519. }
  1520. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1521. // All supported encodings rejected with q=0 should return None
  1522. Request req;
  1523. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1524. Response res;
  1525. res.set_header("Content-Type", "text/plain");
  1526. auto ret = detail::encoding_type(req, res);
  1527. EXPECT_TRUE(ret == detail::EncodingType::None);
  1528. }
  1529. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1530. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1531. Request req;
  1532. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1533. Response res;
  1534. res.set_header("Content-Type", "text/plain");
  1535. auto ret = detail::encoding_type(req, res);
  1536. EXPECT_TRUE(ret == detail::EncodingType::None);
  1537. }
  1538. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1539. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1540. Request req;
  1541. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1542. Response res;
  1543. res.set_header("Content-Type", "text/plain");
  1544. auto ret = detail::encoding_type(req, res);
  1545. EXPECT_TRUE(ret == detail::EncodingType::None);
  1546. }
  1547. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1548. // RFC 7231: Accept-Encoding values are case-insensitive
  1549. Request req;
  1550. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1551. Response res;
  1552. res.set_header("Content-Type", "text/plain");
  1553. auto ret = detail::encoding_type(req, res);
  1554. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1555. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1556. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1557. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1558. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1559. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1560. #else
  1561. EXPECT_TRUE(ret == detail::EncodingType::None);
  1562. #endif
  1563. }
  1564. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1565. // q value should determine priority, not hardcoded order
  1566. Request req;
  1567. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1568. Response res;
  1569. res.set_header("Content-Type", "text/plain");
  1570. auto ret = detail::encoding_type(req, res);
  1571. // gzip has highest q=1.0, so it should be selected even though
  1572. // br and zstd are also supported
  1573. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1574. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1575. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1576. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1577. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1578. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1579. #else
  1580. EXPECT_TRUE(ret == detail::EncodingType::None);
  1581. #endif
  1582. }
  1583. TEST(BufferStreamTest, read) {
  1584. detail::BufferStream strm1;
  1585. Stream &strm = strm1;
  1586. EXPECT_EQ(5, strm.write("hello"));
  1587. char buf[512];
  1588. EXPECT_EQ(2, strm.read(buf, 2));
  1589. EXPECT_EQ('h', buf[0]);
  1590. EXPECT_EQ('e', buf[1]);
  1591. EXPECT_EQ(2, strm.read(buf, 2));
  1592. EXPECT_EQ('l', buf[0]);
  1593. EXPECT_EQ('l', buf[1]);
  1594. EXPECT_EQ(1, strm.read(buf, 1));
  1595. EXPECT_EQ('o', buf[0]);
  1596. EXPECT_EQ(0, strm.read(buf, 1));
  1597. }
  1598. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1599. auto host = "www.httpwatch.com";
  1600. auto ip = hosted_at(host);
  1601. EXPECT_EQ("23.96.13.243", ip);
  1602. std::vector<std::string> addrs;
  1603. hosted_at(host, addrs);
  1604. EXPECT_EQ(1u, addrs.size());
  1605. }
  1606. #if 0 // It depends on each test environment...
  1607. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1608. auto host = "www.youtube.com";
  1609. std::vector<std::string> addrs;
  1610. hosted_at(host, addrs);
  1611. EXPECT_EQ(20u, addrs.size());
  1612. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1613. EXPECT_TRUE(it != addrs.end());
  1614. }
  1615. #endif
  1616. class ChunkedEncodingTest : public ::testing::Test {
  1617. protected:
  1618. ChunkedEncodingTest()
  1619. : cli_(HOST, PORT)
  1620. #ifdef CPPHTTPLIB_SSL_ENABLED
  1621. ,
  1622. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1623. #endif
  1624. {
  1625. cli_.set_connection_timeout(2);
  1626. #ifdef CPPHTTPLIB_SSL_ENABLED
  1627. cli_.enable_server_certificate_verification(false);
  1628. #endif
  1629. }
  1630. virtual void SetUp() {
  1631. read_file("./image.jpg", image_data_);
  1632. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1633. res.set_content("Hello World!", "text/plain");
  1634. });
  1635. svr_.Get(
  1636. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1637. res.set_chunked_content_provider(
  1638. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1639. size_t remaining = image_data_.size() - offset;
  1640. if (remaining == 0) {
  1641. sink.done();
  1642. } else {
  1643. constexpr size_t CHUNK_SIZE = 1024;
  1644. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1645. sink.write(&image_data_[offset], send_size);
  1646. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1647. }
  1648. return true;
  1649. });
  1650. });
  1651. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1652. svr_.wait_until_ready();
  1653. }
  1654. virtual void TearDown() {
  1655. svr_.stop();
  1656. if (!request_threads_.empty()) {
  1657. std::this_thread::sleep_for(std::chrono::seconds(1));
  1658. for (auto &t : request_threads_) {
  1659. t.join();
  1660. }
  1661. }
  1662. t_.join();
  1663. }
  1664. #ifdef CPPHTTPLIB_SSL_ENABLED
  1665. SSLClient cli_;
  1666. SSLServer svr_;
  1667. #else
  1668. Client cli_;
  1669. Server svr_;
  1670. #endif
  1671. thread t_;
  1672. std::vector<thread> request_threads_;
  1673. std::string image_data_;
  1674. };
  1675. TEST_F(ChunkedEncodingTest, NormalGet) {
  1676. auto res = cli_.Get("/chunked");
  1677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1678. std::string out;
  1679. read_file("./image.jpg", out);
  1680. EXPECT_EQ(StatusCode::OK_200, res->status);
  1681. EXPECT_EQ(out, res->body);
  1682. }
  1683. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1684. std::string body;
  1685. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1686. body.append(data, data_length);
  1687. return true;
  1688. });
  1689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1690. std::string out;
  1691. read_file("./image.jpg", out);
  1692. EXPECT_EQ(StatusCode::OK_200, res->status);
  1693. EXPECT_EQ(out, body);
  1694. }
  1695. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1696. std::string body;
  1697. auto res = cli_.Get(
  1698. "/chunked",
  1699. [&](const Response &response) {
  1700. EXPECT_EQ(StatusCode::OK_200, response.status);
  1701. return true;
  1702. },
  1703. [&](const char *data, size_t data_length) {
  1704. body.append(data, data_length);
  1705. return true;
  1706. });
  1707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1708. std::string out;
  1709. read_file("./image.jpg", out);
  1710. EXPECT_EQ(StatusCode::OK_200, res->status);
  1711. EXPECT_EQ(out, body);
  1712. }
  1713. TEST(RangeTest, FromHTTPBin_Online) {
  1714. auto host = "httpbingo.org";
  1715. auto path = std::string{"/range/32"};
  1716. #ifdef CPPHTTPLIB_SSL_ENABLED
  1717. auto port = 443;
  1718. SSLClient cli(host, port);
  1719. #else
  1720. auto port = 80;
  1721. Client cli(host, port);
  1722. #endif
  1723. cli.set_connection_timeout(5);
  1724. {
  1725. auto res = cli.Get(path);
  1726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1727. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1728. EXPECT_EQ(StatusCode::OK_200, res->status);
  1729. }
  1730. {
  1731. Headers headers = {make_range_header({{1, -1}})};
  1732. auto res = cli.Get(path, headers);
  1733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1734. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1735. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1736. }
  1737. {
  1738. Headers headers = {make_range_header({{1, 10}})};
  1739. auto res = cli.Get(path, headers);
  1740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1741. EXPECT_EQ("bcdefghijk", res->body);
  1742. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1743. }
  1744. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1745. // entire resource, while the original httpbin returned 200. Both are
  1746. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1747. {
  1748. Headers headers = {make_range_header({{0, 31}})};
  1749. auto res = cli.Get(path, headers);
  1750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1751. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1752. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1753. res->status == StatusCode::PartialContent_206);
  1754. }
  1755. {
  1756. Headers headers = {make_range_header({{0, -1}})};
  1757. auto res = cli.Get(path, headers);
  1758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1759. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1760. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1761. res->status == StatusCode::PartialContent_206);
  1762. }
  1763. // go-httpbin returns 206 with clamped range for over-range requests,
  1764. // while the original httpbin returned 416. Both behaviors are observed
  1765. // in real servers, so we only verify the request succeeds.
  1766. {
  1767. Headers headers = {make_range_header({{0, 32}})};
  1768. auto res = cli.Get(path, headers);
  1769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1770. }
  1771. }
  1772. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1773. auto host = "unresolvableaddress.local";
  1774. auto path = std::string{"/"};
  1775. #ifdef CPPHTTPLIB_SSL_ENABLED
  1776. auto port = 443;
  1777. SSLClient cli(host, port);
  1778. #else
  1779. auto port = 80;
  1780. Client cli(host, port);
  1781. #endif
  1782. cli.set_connection_timeout(1);
  1783. {
  1784. auto res = cli.Get(path);
  1785. ASSERT_FALSE(res);
  1786. }
  1787. std::this_thread::sleep_for(std::chrono::seconds(8));
  1788. }
  1789. #if defined(__linux__) && defined(__GLIBC__) && \
  1790. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1791. // Forward declaration: in split builds split.py strips `inline` and moves the
  1792. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1793. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1794. // against the symbol in both header-only and split builds.
  1795. namespace httplib {
  1796. namespace detail {
  1797. int getaddrinfo_with_timeout(const char *node, const char *service,
  1798. const struct addrinfo *hints,
  1799. struct addrinfo **res, time_t timeout_sec);
  1800. } // namespace detail
  1801. } // namespace httplib
  1802. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1803. //
  1804. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1805. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1806. // gai_suspend() call hits the connection timeout the function calls
  1807. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1808. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1809. // still alive and still references the now-destroyed stack frame.
  1810. //
  1811. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1812. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1813. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1814. // and runs them in a container.
  1815. namespace {
  1816. bool should_run_issue_2431_tests() {
  1817. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1818. return v && *v && std::string(v) != "0";
  1819. }
  1820. std::string unique_unresolvable_host(int n) {
  1821. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1822. // glibc still asks the configured nameserver — which is exactly the path
  1823. // we want to exercise. A unique label per call avoids the resolver cache.
  1824. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1825. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1826. std::to_string(n) + ".invalid";
  1827. }
  1828. } // namespace
  1829. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1830. if (!should_run_issue_2431_tests()) {
  1831. GTEST_SKIP()
  1832. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1833. }
  1834. for (int i = 0; i < 8; ++i) {
  1835. struct addrinfo hints;
  1836. memset(&hints, 0, sizeof(hints));
  1837. hints.ai_family = AF_UNSPEC;
  1838. hints.ai_socktype = SOCK_STREAM;
  1839. auto host = unique_unresolvable_host(i);
  1840. struct addrinfo *result = nullptr;
  1841. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1842. &result, /*timeout_sec=*/1);
  1843. if (rc == 0 && result) { freeaddrinfo(result); }
  1844. }
  1845. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1846. // stack region they still believe holds their gaicb.
  1847. std::this_thread::sleep_for(std::chrono::seconds(3));
  1848. }
  1849. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1850. if (!should_run_issue_2431_tests()) {
  1851. GTEST_SKIP()
  1852. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1853. }
  1854. std::atomic<bool> stop{false};
  1855. std::vector<std::thread> threads;
  1856. for (int t = 0; t < 8; ++t) {
  1857. threads.emplace_back([t, &stop] {
  1858. int i = 0;
  1859. while (!stop.load(std::memory_order_relaxed)) {
  1860. struct addrinfo hints;
  1861. memset(&hints, 0, sizeof(hints));
  1862. hints.ai_family = AF_UNSPEC;
  1863. hints.ai_socktype = SOCK_STREAM;
  1864. auto host = unique_unresolvable_host(t * 100000 + i++);
  1865. struct addrinfo *result = nullptr;
  1866. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1867. &result, /*timeout_sec=*/1);
  1868. if (rc == 0 && result) { freeaddrinfo(result); }
  1869. }
  1870. });
  1871. }
  1872. std::this_thread::sleep_for(std::chrono::seconds(8));
  1873. stop.store(true, std::memory_order_relaxed);
  1874. for (auto &th : threads) {
  1875. th.join();
  1876. }
  1877. std::this_thread::sleep_for(std::chrono::seconds(3));
  1878. }
  1879. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1880. if (!should_run_issue_2431_tests()) {
  1881. GTEST_SKIP()
  1882. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1883. }
  1884. std::atomic<bool> stop{false};
  1885. std::vector<std::thread> threads;
  1886. for (int t = 0; t < 8; ++t) {
  1887. threads.emplace_back([t, &stop] {
  1888. int i = 0;
  1889. while (!stop.load(std::memory_order_relaxed)) {
  1890. auto host = unique_unresolvable_host(t * 100000 + i++);
  1891. Client cli(host, 80);
  1892. cli.set_connection_timeout(1, 0);
  1893. cli.set_read_timeout(1, 0);
  1894. cli.set_write_timeout(1, 0);
  1895. (void)cli.Get("/");
  1896. }
  1897. });
  1898. }
  1899. std::this_thread::sleep_for(std::chrono::seconds(8));
  1900. stop.store(true, std::memory_order_relaxed);
  1901. for (auto &th : threads) {
  1902. th.join();
  1903. }
  1904. std::this_thread::sleep_for(std::chrono::seconds(3));
  1905. }
  1906. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1907. TEST(ConnectionErrorTest, InvalidHost) {
  1908. auto host = "-abcde.com";
  1909. #ifdef CPPHTTPLIB_SSL_ENABLED
  1910. auto port = 443;
  1911. SSLClient cli(host, port);
  1912. #else
  1913. auto port = 80;
  1914. Client cli(host, port);
  1915. #endif
  1916. cli.set_connection_timeout(std::chrono::seconds(2));
  1917. auto res = cli.Get("/");
  1918. ASSERT_TRUE(!res);
  1919. EXPECT_EQ(Error::Connection, res.error());
  1920. }
  1921. TEST(ConnectionErrorTest, InvalidHost2) {
  1922. auto host = "httpcan.org/";
  1923. #ifdef CPPHTTPLIB_SSL_ENABLED
  1924. SSLClient cli(host);
  1925. #else
  1926. Client cli(host);
  1927. #endif
  1928. cli.set_connection_timeout(std::chrono::seconds(2));
  1929. auto res = cli.Get("/");
  1930. ASSERT_TRUE(!res);
  1931. EXPECT_EQ(Error::Connection, res.error());
  1932. }
  1933. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1934. auto host = "httpcan.org/";
  1935. #ifdef CPPHTTPLIB_SSL_ENABLED
  1936. SSLClient cli(host);
  1937. #else
  1938. Client cli(host);
  1939. #endif
  1940. cli.set_connection_timeout(std::chrono::seconds(2));
  1941. auto res = cli.Get("/");
  1942. ASSERT_TRUE(!res);
  1943. stringstream s;
  1944. s << "error code: " << res.error();
  1945. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1946. }
  1947. TEST(ConnectionErrorTest, InvalidPort) {
  1948. auto host = "localhost";
  1949. auto port = 44380;
  1950. #ifdef CPPHTTPLIB_SSL_ENABLED
  1951. SSLClient cli(host, port);
  1952. #else
  1953. Client cli(host, port);
  1954. #endif
  1955. cli.set_connection_timeout(std::chrono::seconds(2));
  1956. auto res = cli.Get("/");
  1957. ASSERT_TRUE(!res);
  1958. EXPECT_TRUE(Error::Connection == res.error() ||
  1959. Error::ConnectionTimeout == res.error());
  1960. }
  1961. TEST(ConnectionErrorTest, Timeout_Online) {
  1962. auto host = "google.com";
  1963. #ifdef CPPHTTPLIB_SSL_ENABLED
  1964. auto port = 44380;
  1965. SSLClient cli(host, port);
  1966. #else
  1967. auto port = 8080;
  1968. Client cli(host, port);
  1969. #endif
  1970. cli.set_connection_timeout(std::chrono::seconds(2));
  1971. // only probe one address type so that the error reason
  1972. // correlates to the timed-out IPv4, not the unsupported
  1973. // IPv6 connection attempt
  1974. cli.set_address_family(AF_INET);
  1975. auto res = cli.Get("/");
  1976. ASSERT_TRUE(!res);
  1977. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1978. }
  1979. TEST(CancelTest, NoCancel_Online) {
  1980. auto host = "httpbingo.org";
  1981. auto path = std::string{"/range/32"};
  1982. #ifdef CPPHTTPLIB_SSL_ENABLED
  1983. auto port = 443;
  1984. SSLClient cli(host, port);
  1985. #else
  1986. auto port = 80;
  1987. Client cli(host, port);
  1988. #endif
  1989. cli.set_connection_timeout(std::chrono::seconds(5));
  1990. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1992. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1993. EXPECT_EQ(StatusCode::OK_200, res->status);
  1994. }
  1995. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1996. // Use /bytes with a large payload so that the DownloadProgress callback
  1997. // (which only fires for Content-Length responses) is invoked before the
  1998. // entire body is received, giving cancellation a chance to fire.
  1999. auto host = "httpbingo.org";
  2000. auto path = std::string{"/bytes/524288"};
  2001. #ifdef CPPHTTPLIB_SSL_ENABLED
  2002. auto port = 443;
  2003. SSLClient cli(host, port);
  2004. #else
  2005. auto port = 80;
  2006. Client cli(host, port);
  2007. #endif
  2008. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2009. cli.set_connection_timeout(std::chrono::seconds(5));
  2010. ASSERT_TRUE(!res);
  2011. EXPECT_EQ(Error::Canceled, res.error());
  2012. }
  2013. TEST(CancelTest, WithCancelLargePayload_Online) {
  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. cli.set_connection_timeout(std::chrono::seconds(5));
  2024. uint32_t count = 0;
  2025. auto res =
  2026. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2027. ASSERT_TRUE(!res);
  2028. EXPECT_EQ(Error::Canceled, res.error());
  2029. }
  2030. TEST(CancelTest, NoCancelPost) {
  2031. Server svr;
  2032. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2033. res.set_content("Hello World!", "text/plain");
  2034. });
  2035. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2036. auto se = detail::scope_exit([&] {
  2037. svr.stop();
  2038. thread.join();
  2039. ASSERT_FALSE(svr.is_running());
  2040. });
  2041. svr.wait_until_ready();
  2042. Client cli(HOST, PORT);
  2043. cli.set_connection_timeout(std::chrono::seconds(5));
  2044. auto res =
  2045. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2046. "application/json", [](uint64_t, uint64_t) { return true; });
  2047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2048. EXPECT_EQ("Hello World!", res->body);
  2049. EXPECT_EQ(StatusCode::OK_200, res->status);
  2050. }
  2051. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2052. Server svr;
  2053. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2054. res.set_content("Hello World!", "text/plain");
  2055. });
  2056. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2057. auto se = detail::scope_exit([&] {
  2058. svr.stop();
  2059. thread.join();
  2060. ASSERT_FALSE(svr.is_running());
  2061. });
  2062. svr.wait_until_ready();
  2063. Client cli(HOST, PORT);
  2064. cli.set_connection_timeout(std::chrono::seconds(5));
  2065. auto res =
  2066. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2067. "application/json", [](uint64_t, uint64_t) { return false; });
  2068. ASSERT_TRUE(!res);
  2069. EXPECT_EQ(Error::Canceled, res.error());
  2070. }
  2071. TEST(CancelTest, WithCancelLargePayloadPost) {
  2072. Server svr;
  2073. svr.set_payload_max_length(200 * 1024 * 1024);
  2074. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2075. res.set_content(LARGE_DATA, "text/plain");
  2076. });
  2077. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2078. auto se = detail::scope_exit([&] {
  2079. svr.stop();
  2080. thread.join();
  2081. ASSERT_FALSE(svr.is_running());
  2082. });
  2083. svr.wait_until_ready();
  2084. Client cli(HOST, PORT);
  2085. cli.set_payload_max_length(200 * 1024 * 1024);
  2086. cli.set_connection_timeout(std::chrono::seconds(5));
  2087. auto res =
  2088. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2089. "application/json", [](uint64_t, uint64_t) { return false; });
  2090. ASSERT_TRUE(!res);
  2091. EXPECT_EQ(Error::Canceled, res.error());
  2092. }
  2093. TEST(CancelTest, NoCancelPut) {
  2094. Server svr;
  2095. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2096. res.set_content("Hello World!", "text/plain");
  2097. });
  2098. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2099. auto se = detail::scope_exit([&] {
  2100. svr.stop();
  2101. thread.join();
  2102. ASSERT_FALSE(svr.is_running());
  2103. });
  2104. svr.wait_until_ready();
  2105. Client cli(HOST, PORT);
  2106. cli.set_connection_timeout(std::chrono::seconds(5));
  2107. auto res =
  2108. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2109. "application/json", [](uint64_t, uint64_t) { return true; });
  2110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2111. EXPECT_EQ("Hello World!", res->body);
  2112. EXPECT_EQ(StatusCode::OK_200, res->status);
  2113. }
  2114. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2115. Server svr;
  2116. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2117. res.set_content("Hello World!", "text/plain");
  2118. });
  2119. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2120. auto se = detail::scope_exit([&] {
  2121. svr.stop();
  2122. thread.join();
  2123. ASSERT_FALSE(svr.is_running());
  2124. });
  2125. svr.wait_until_ready();
  2126. Client cli(HOST, PORT);
  2127. cli.set_connection_timeout(std::chrono::seconds(5));
  2128. auto res =
  2129. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2130. "application/json", [](uint64_t, uint64_t) { return false; });
  2131. ASSERT_TRUE(!res);
  2132. EXPECT_EQ(Error::Canceled, res.error());
  2133. }
  2134. TEST(CancelTest, WithCancelLargePayloadPut) {
  2135. Server svr;
  2136. svr.set_payload_max_length(200 * 1024 * 1024);
  2137. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2138. res.set_content(LARGE_DATA, "text/plain");
  2139. });
  2140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2141. auto se = detail::scope_exit([&] {
  2142. svr.stop();
  2143. thread.join();
  2144. ASSERT_FALSE(svr.is_running());
  2145. });
  2146. svr.wait_until_ready();
  2147. Client cli(HOST, PORT);
  2148. cli.set_payload_max_length(200 * 1024 * 1024);
  2149. cli.set_connection_timeout(std::chrono::seconds(5));
  2150. auto res =
  2151. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2152. "application/json", [](uint64_t, uint64_t) { return false; });
  2153. ASSERT_TRUE(!res);
  2154. EXPECT_EQ(Error::Canceled, res.error());
  2155. }
  2156. TEST(CancelTest, NoCancelPatch) {
  2157. Server svr;
  2158. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2159. res.set_content("Hello World!", "text/plain");
  2160. });
  2161. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2162. auto se = detail::scope_exit([&] {
  2163. svr.stop();
  2164. thread.join();
  2165. ASSERT_FALSE(svr.is_running());
  2166. });
  2167. svr.wait_until_ready();
  2168. Client cli(HOST, PORT);
  2169. cli.set_connection_timeout(std::chrono::seconds(5));
  2170. auto res =
  2171. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2172. "application/json", [](uint64_t, uint64_t) { return true; });
  2173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2174. EXPECT_EQ("Hello World!", res->body);
  2175. EXPECT_EQ(StatusCode::OK_200, res->status);
  2176. }
  2177. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2178. Server svr;
  2179. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2180. res.set_content("Hello World!", "text/plain");
  2181. });
  2182. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2183. auto se = detail::scope_exit([&] {
  2184. svr.stop();
  2185. thread.join();
  2186. ASSERT_FALSE(svr.is_running());
  2187. });
  2188. svr.wait_until_ready();
  2189. Client cli(HOST, PORT);
  2190. cli.set_connection_timeout(std::chrono::seconds(5));
  2191. auto res =
  2192. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2193. "application/json", [](uint64_t, uint64_t) { return false; });
  2194. ASSERT_TRUE(!res);
  2195. EXPECT_EQ(Error::Canceled, res.error());
  2196. }
  2197. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2198. Server svr;
  2199. svr.set_payload_max_length(200 * 1024 * 1024);
  2200. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2201. res.set_content(LARGE_DATA, "text/plain");
  2202. });
  2203. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2204. auto se = detail::scope_exit([&] {
  2205. svr.stop();
  2206. thread.join();
  2207. ASSERT_FALSE(svr.is_running());
  2208. });
  2209. svr.wait_until_ready();
  2210. Client cli(HOST, PORT);
  2211. cli.set_payload_max_length(200 * 1024 * 1024);
  2212. cli.set_connection_timeout(std::chrono::seconds(5));
  2213. auto res =
  2214. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2215. "application/json", [](uint64_t, uint64_t) { return false; });
  2216. ASSERT_TRUE(!res);
  2217. EXPECT_EQ(Error::Canceled, res.error());
  2218. }
  2219. TEST(CancelTest, NoCancelDelete) {
  2220. Server svr;
  2221. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2222. res.set_content("Hello World!", "text/plain");
  2223. });
  2224. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2225. auto se = detail::scope_exit([&] {
  2226. svr.stop();
  2227. thread.join();
  2228. ASSERT_FALSE(svr.is_running());
  2229. });
  2230. svr.wait_until_ready();
  2231. Client cli(HOST, PORT);
  2232. cli.set_connection_timeout(std::chrono::seconds(5));
  2233. auto res =
  2234. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2235. "application/json", [](uint64_t, uint64_t) { return true; });
  2236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2237. EXPECT_EQ("Hello World!", res->body);
  2238. EXPECT_EQ(StatusCode::OK_200, res->status);
  2239. }
  2240. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2241. Server svr;
  2242. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2243. res.set_content("Hello World!", "text/plain");
  2244. });
  2245. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2246. auto se = detail::scope_exit([&] {
  2247. svr.stop();
  2248. thread.join();
  2249. ASSERT_FALSE(svr.is_running());
  2250. });
  2251. svr.wait_until_ready();
  2252. Client cli(HOST, PORT);
  2253. cli.set_connection_timeout(std::chrono::seconds(5));
  2254. auto res =
  2255. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2256. "application/json", [](uint64_t, uint64_t) { return false; });
  2257. ASSERT_TRUE(!res);
  2258. EXPECT_EQ(Error::Canceled, res.error());
  2259. }
  2260. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2261. Server svr;
  2262. svr.set_payload_max_length(200 * 1024 * 1024);
  2263. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2264. res.set_content(LARGE_DATA, "text/plain");
  2265. });
  2266. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2267. auto se = detail::scope_exit([&] {
  2268. svr.stop();
  2269. thread.join();
  2270. ASSERT_FALSE(svr.is_running());
  2271. });
  2272. svr.wait_until_ready();
  2273. Client cli(HOST, PORT);
  2274. cli.set_payload_max_length(200 * 1024 * 1024);
  2275. cli.set_connection_timeout(std::chrono::seconds(5));
  2276. auto res =
  2277. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2278. "application/json", [](uint64_t, uint64_t) { return false; });
  2279. ASSERT_TRUE(!res);
  2280. EXPECT_EQ(Error::Canceled, res.error());
  2281. }
  2282. static std::string remove_whitespace(const std::string &input) {
  2283. std::string output;
  2284. output.reserve(input.size());
  2285. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2286. [](unsigned char c) { return !std::isspace(c); });
  2287. return output;
  2288. }
  2289. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2290. auto host = "httpbingo.org";
  2291. auto path = std::string{"/basic-auth/hello/world"};
  2292. #ifdef CPPHTTPLIB_SSL_ENABLED
  2293. auto port = 443;
  2294. SSLClient cli(host, port);
  2295. #else
  2296. auto port = 80;
  2297. Client cli(host, port);
  2298. #endif
  2299. {
  2300. auto res = cli.Get(path);
  2301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2302. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2303. }
  2304. {
  2305. auto res = cli.Get(
  2306. path, Headers{make_basic_authentication_header("hello", "world")});
  2307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2308. auto body = remove_whitespace(res->body);
  2309. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2310. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2311. EXPECT_EQ(StatusCode::OK_200, res->status);
  2312. }
  2313. {
  2314. cli.set_basic_auth("hello", "world");
  2315. auto res = cli.Get(path);
  2316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2317. auto body = remove_whitespace(res->body);
  2318. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2319. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2320. EXPECT_EQ(StatusCode::OK_200, res->status);
  2321. }
  2322. {
  2323. cli.set_basic_auth("hello", "bad");
  2324. auto res = cli.Get(path);
  2325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2326. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2327. }
  2328. {
  2329. cli.set_basic_auth("bad", "world");
  2330. auto res = cli.Get(path);
  2331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2332. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2333. }
  2334. }
  2335. #ifdef CPPHTTPLIB_SSL_ENABLED
  2336. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2337. auto host = "httpbingo.org";
  2338. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2339. auto paths = std::vector<std::string>{
  2340. "/digest-auth/auth/hello/world/MD5",
  2341. "/digest-auth/auth/hello/world/SHA-256",
  2342. };
  2343. auto port = 443;
  2344. SSLClient cli(host, port);
  2345. {
  2346. auto res = cli.Get(unauth_path);
  2347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2348. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2349. }
  2350. {
  2351. cli.set_digest_auth("hello", "world");
  2352. for (const auto &path : paths) {
  2353. auto res = cli.Get(path.c_str());
  2354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2355. auto body = remove_whitespace(res->body);
  2356. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2357. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2358. EXPECT_EQ(StatusCode::OK_200, res->status);
  2359. }
  2360. cli.set_digest_auth("hello", "bad");
  2361. for (const auto &path : paths) {
  2362. auto res = cli.Get(path.c_str());
  2363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2364. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2365. }
  2366. }
  2367. }
  2368. #endif
  2369. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2370. auto host = "google.com";
  2371. auto another_host = "example.com";
  2372. auto wrong_ip = "0.0.0.0";
  2373. #ifdef CPPHTTPLIB_SSL_ENABLED
  2374. SSLClient cli(host);
  2375. #else
  2376. Client cli(host);
  2377. #endif
  2378. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2379. auto res = cli.Get("/");
  2380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2381. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2382. }
  2383. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2384. auto host = "google.com";
  2385. auto wrong_ip = "0.0.0.0";
  2386. #ifdef CPPHTTPLIB_SSL_ENABLED
  2387. SSLClient cli(host);
  2388. #else
  2389. Client cli(host);
  2390. #endif
  2391. cli.set_hostname_addr_map({{host, wrong_ip}});
  2392. auto res = cli.Get("/");
  2393. ASSERT_TRUE(!res);
  2394. EXPECT_EQ(Error::Connection, res.error());
  2395. }
  2396. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2397. // A mapped value that is not an IP literal must be resolved. "localhost"
  2398. // resolves from the hosts file, so this test needs no external DNS.
  2399. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2400. auto host = "target.invalid";
  2401. Server svr;
  2402. std::string received_host;
  2403. svr.Get("/hi", [&](const Request &req, Response &res) {
  2404. received_host = req.get_header_value("Host");
  2405. res.set_content("Hello World!", "text/plain");
  2406. });
  2407. auto port = svr.bind_to_any_port(HOST);
  2408. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2409. auto se = detail::scope_exit([&] {
  2410. svr.stop();
  2411. thread.join();
  2412. ASSERT_FALSE(svr.is_running());
  2413. });
  2414. svr.wait_until_ready();
  2415. Client cli(host, port);
  2416. cli.set_hostname_addr_map({{host, HOST}});
  2417. auto res = cli.Get("/hi");
  2418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2419. EXPECT_EQ(StatusCode::OK_200, res->status);
  2420. // The mapping only redirects the connection; the identity stays host_.
  2421. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2422. }
  2423. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2424. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2425. auto host = "target.invalid";
  2426. Server svr;
  2427. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2428. res.set_content("Hello World!", "text/plain");
  2429. });
  2430. auto port = svr.bind_to_any_port("127.0.0.1");
  2431. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2432. auto se = detail::scope_exit([&] {
  2433. svr.stop();
  2434. thread.join();
  2435. ASSERT_FALSE(svr.is_running());
  2436. });
  2437. svr.wait_until_ready();
  2438. Client cli(host, port);
  2439. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2440. auto res = cli.Get("/hi");
  2441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2442. EXPECT_EQ(StatusCode::OK_200, res->status);
  2443. }
  2444. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2445. // An empty mapped value must leave host_ as the connection target. Without
  2446. // that guard the empty value would become the host argument, getaddrinfo
  2447. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2448. // loopback - silently connecting somewhere the caller never asked for.
  2449. // The server listens on loopback, so such a fallback would succeed and is
  2450. // therefore observable as a failure of this test.
  2451. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2452. Server svr;
  2453. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2454. res.set_content("Hello World!", "text/plain");
  2455. });
  2456. auto port = svr.bind_to_any_port(HOST);
  2457. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2458. auto se = detail::scope_exit([&] {
  2459. svr.stop();
  2460. thread.join();
  2461. ASSERT_FALSE(svr.is_running());
  2462. });
  2463. svr.wait_until_ready();
  2464. Client cli(blackhole, port);
  2465. cli.set_hostname_addr_map({{blackhole, ""}});
  2466. cli.set_connection_timeout(1);
  2467. auto res = cli.Get("/hi");
  2468. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2469. }
  2470. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2471. auto host = "httpbingo.org";
  2472. auto path = std::string{"/absolute-redirect/3"};
  2473. #ifdef CPPHTTPLIB_SSL_ENABLED
  2474. SSLClient cli(host);
  2475. #else
  2476. Client cli(host);
  2477. #endif
  2478. cli.set_follow_location(true);
  2479. auto res = cli.Get(path);
  2480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2481. EXPECT_EQ(StatusCode::OK_200, res->status);
  2482. }
  2483. TEST(RedirectTest, Redirect_Online) {
  2484. auto host = "httpbingo.org";
  2485. auto path = std::string{"/redirect/3"};
  2486. #ifdef CPPHTTPLIB_SSL_ENABLED
  2487. SSLClient cli(host);
  2488. #else
  2489. Client cli(host);
  2490. #endif
  2491. cli.set_follow_location(true);
  2492. auto res = cli.Get(path);
  2493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2494. EXPECT_EQ(StatusCode::OK_200, res->status);
  2495. }
  2496. TEST(RelativeRedirectTest, Redirect_Online) {
  2497. auto host = "httpbingo.org";
  2498. auto path = std::string{"/relative-redirect/3"};
  2499. #ifdef CPPHTTPLIB_SSL_ENABLED
  2500. SSLClient cli(host);
  2501. #else
  2502. Client cli(host);
  2503. #endif
  2504. cli.set_follow_location(true);
  2505. auto res = cli.Get(path);
  2506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2507. EXPECT_EQ(StatusCode::OK_200, res->status);
  2508. }
  2509. TEST(TooManyRedirectTest, Redirect_Online) {
  2510. auto host = "httpbingo.org";
  2511. auto path = std::string{"/redirect/21"};
  2512. #ifdef CPPHTTPLIB_SSL_ENABLED
  2513. SSLClient cli(host);
  2514. #else
  2515. Client cli(host);
  2516. #endif
  2517. cli.set_follow_location(true);
  2518. auto res = cli.Get(path);
  2519. ASSERT_TRUE(!res);
  2520. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2521. }
  2522. #ifdef CPPHTTPLIB_SSL_ENABLED
  2523. TEST(YahooRedirectTest, Redirect_Online) {
  2524. Client cli("yahoo.com");
  2525. auto res = cli.Get("/");
  2526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2527. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2528. cli.set_follow_location(true);
  2529. res = cli.Get("/");
  2530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2531. EXPECT_EQ(StatusCode::OK_200, res->status);
  2532. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2533. }
  2534. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2535. #define REDIR_HOST "httpbingo.org"
  2536. #define REDIR_PATH "/redirect-to"
  2537. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2538. SSLClient cli(REDIR_HOST);
  2539. cli.set_follow_location(true);
  2540. auto res =
  2541. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2543. EXPECT_EQ(StatusCode::OK_200, res->status);
  2544. }
  2545. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2546. SSLClient cli(REDIR_HOST);
  2547. cli.set_follow_location(true);
  2548. Params params;
  2549. params.emplace("url", "http://example.com");
  2550. params.emplace("status_code", "302");
  2551. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. }
  2555. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2556. SSLClient cli(REDIR_HOST);
  2557. cli.set_follow_location(true);
  2558. Params params;
  2559. params.emplace("url", "http://example.com");
  2560. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2562. EXPECT_EQ(StatusCode::OK_200, res->status);
  2563. }
  2564. TEST(UrlWithSpace, Redirect_Online) {
  2565. SSLClient cli("edge.forgecdn.net");
  2566. cli.set_follow_location(true);
  2567. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. EXPECT_EQ(StatusCode::OK_200, res->status);
  2570. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2571. }
  2572. #endif
  2573. #if !defined(_WIN32) && !defined(_WIN64)
  2574. TEST(ReceiveSignals, Signal) {
  2575. auto setupSignalHandlers = []() {
  2576. struct sigaction act;
  2577. sigemptyset(&act.sa_mask);
  2578. act.sa_flags = SA_SIGINFO;
  2579. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2580. switch (sig) {
  2581. case SIGINT:
  2582. default: break;
  2583. }
  2584. };
  2585. ::sigaction(SIGINT, &act, nullptr);
  2586. };
  2587. Server svr;
  2588. int port = 0;
  2589. auto thread = std::thread([&]() {
  2590. setupSignalHandlers();
  2591. port = svr.bind_to_any_port(HOST);
  2592. svr.listen_after_bind();
  2593. });
  2594. auto se = detail::scope_exit([&] {
  2595. svr.stop();
  2596. thread.join();
  2597. ASSERT_FALSE(svr.is_running());
  2598. });
  2599. svr.wait_until_ready();
  2600. ASSERT_TRUE(svr.is_running());
  2601. pthread_kill(thread.native_handle(), SIGINT);
  2602. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2603. ASSERT_TRUE(svr.is_running());
  2604. }
  2605. #endif
  2606. TEST(RedirectToDifferentPort, Redirect) {
  2607. Server svr1;
  2608. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2609. res.set_content("Hello World!", "text/plain");
  2610. });
  2611. int svr1_port = 0;
  2612. auto thread1 = std::thread([&]() {
  2613. svr1_port = svr1.bind_to_any_port(HOST);
  2614. svr1.listen_after_bind();
  2615. });
  2616. Server svr2;
  2617. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2618. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2619. });
  2620. int svr2_port = 0;
  2621. auto thread2 = std::thread([&]() {
  2622. svr2_port = svr2.bind_to_any_port(HOST);
  2623. svr2.listen_after_bind();
  2624. });
  2625. auto se = detail::scope_exit([&] {
  2626. svr2.stop();
  2627. thread2.join();
  2628. svr1.stop();
  2629. thread1.join();
  2630. ASSERT_FALSE(svr2.is_running());
  2631. ASSERT_FALSE(svr1.is_running());
  2632. });
  2633. svr1.wait_until_ready();
  2634. svr2.wait_until_ready();
  2635. Client cli("localhost", svr2_port);
  2636. cli.set_follow_location(true);
  2637. auto res = cli.Get("/2");
  2638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2639. EXPECT_EQ(StatusCode::OK_200, res->status);
  2640. EXPECT_EQ("Hello World!", res->body);
  2641. }
  2642. static void
  2643. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2644. Server svr1;
  2645. std::string captured_authorization;
  2646. svr1.Get("/target", [&](const Request &req, Response &res) {
  2647. captured_authorization = req.get_header_value("Authorization");
  2648. res.set_content("OK", "text/plain");
  2649. });
  2650. int svr1_port = 0;
  2651. auto thread1 = std::thread([&]() {
  2652. svr1_port = svr1.bind_to_any_port(HOST);
  2653. svr1.listen_after_bind();
  2654. });
  2655. Server svr2;
  2656. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2657. res.set_redirect(
  2658. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2659. });
  2660. int svr2_port = 0;
  2661. auto thread2 = std::thread([&]() {
  2662. svr2_port = svr2.bind_to_any_port(HOST);
  2663. svr2.listen_after_bind();
  2664. });
  2665. auto se = detail::scope_exit([&] {
  2666. svr2.stop();
  2667. thread2.join();
  2668. svr1.stop();
  2669. thread1.join();
  2670. ASSERT_FALSE(svr2.is_running());
  2671. ASSERT_FALSE(svr1.is_running());
  2672. });
  2673. svr1.wait_until_ready();
  2674. svr2.wait_until_ready();
  2675. Client cli("localhost", svr2_port);
  2676. cli.set_follow_location(true);
  2677. set_auth(cli);
  2678. auto res = cli.Get("/redir");
  2679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2680. EXPECT_EQ(StatusCode::OK_200, res->status);
  2681. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2682. EXPECT_TRUE(captured_authorization.empty());
  2683. }
  2684. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2685. TestDoNotForwardCredentialsOnRedirect(
  2686. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2687. }
  2688. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2689. TestDoNotForwardCredentialsOnRedirect(
  2690. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2691. }
  2692. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2693. Server svr1;
  2694. std::string captured_cookie;
  2695. bool target_hit = false;
  2696. svr1.Get("/target", [&](const Request &req, Response &res) {
  2697. captured_cookie = req.get_header_value("Cookie");
  2698. target_hit = true;
  2699. res.set_content("OK", "text/plain");
  2700. });
  2701. int svr1_port = 0;
  2702. auto thread1 = std::thread([&]() {
  2703. svr1_port = svr1.bind_to_any_port(HOST);
  2704. svr1.listen_after_bind();
  2705. });
  2706. Server svr2;
  2707. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2708. res.set_redirect(
  2709. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2710. });
  2711. int svr2_port = 0;
  2712. auto thread2 = std::thread([&]() {
  2713. svr2_port = svr2.bind_to_any_port(HOST);
  2714. svr2.listen_after_bind();
  2715. });
  2716. auto se = detail::scope_exit([&] {
  2717. svr2.stop();
  2718. thread2.join();
  2719. svr1.stop();
  2720. thread1.join();
  2721. ASSERT_FALSE(svr2.is_running());
  2722. ASSERT_FALSE(svr1.is_running());
  2723. });
  2724. svr1.wait_until_ready();
  2725. svr2.wait_until_ready();
  2726. Client cli("localhost", svr2_port);
  2727. cli.set_follow_location(true);
  2728. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2729. auto res = cli.Get("/redir", headers);
  2730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2731. EXPECT_EQ(StatusCode::OK_200, res->status);
  2732. EXPECT_TRUE(target_hit);
  2733. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2734. EXPECT_TRUE(captured_cookie.empty());
  2735. }
  2736. TEST(RedirectToSamePort, ForwardCookie) {
  2737. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2738. // header so that ordinary session flows keep working.
  2739. Server svr;
  2740. std::string captured_cookie;
  2741. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2742. res.set_redirect("/target", 302);
  2743. });
  2744. svr.Get("/target", [&](const Request &req, Response &res) {
  2745. captured_cookie = req.get_header_value("Cookie");
  2746. res.set_content("OK", "text/plain");
  2747. });
  2748. auto port = svr.bind_to_any_port(HOST);
  2749. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2750. auto se = detail::scope_exit([&] {
  2751. svr.stop();
  2752. thread.join();
  2753. ASSERT_FALSE(svr.is_running());
  2754. });
  2755. svr.wait_until_ready();
  2756. Client cli(HOST, port);
  2757. cli.set_follow_location(true);
  2758. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2759. auto res = cli.Get("/redir", headers);
  2760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2761. EXPECT_EQ(StatusCode::OK_200, res->status);
  2762. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2763. }
  2764. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2765. Server svr;
  2766. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2767. // Port number that overflows int — should not crash
  2768. res.set_redirect("http://localhost:99999999999999999999/target");
  2769. });
  2770. auto port = svr.bind_to_any_port(HOST);
  2771. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2772. auto se = detail::scope_exit([&] {
  2773. svr.stop();
  2774. thread.join();
  2775. ASSERT_FALSE(svr.is_running());
  2776. });
  2777. svr.wait_until_ready();
  2778. Client cli(HOST, port);
  2779. cli.set_follow_location(true);
  2780. auto res = cli.Get("/redir");
  2781. // Should fail gracefully, not crash (no valid response due to bad port)
  2782. EXPECT_FALSE(res);
  2783. }
  2784. TEST(RedirectFromPageWithContent, Redirect) {
  2785. Server svr;
  2786. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2787. res.set_content("___", "text/plain");
  2788. res.set_redirect("/2");
  2789. });
  2790. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2791. res.set_content("Hello World!", "text/plain");
  2792. });
  2793. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2794. auto se = detail::scope_exit([&] {
  2795. svr.stop();
  2796. th.join();
  2797. ASSERT_FALSE(svr.is_running());
  2798. });
  2799. svr.wait_until_ready();
  2800. {
  2801. Client cli("localhost", PORT);
  2802. cli.set_follow_location(true);
  2803. std::string body;
  2804. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2805. body.append(data, data_length);
  2806. return true;
  2807. });
  2808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2809. EXPECT_EQ(StatusCode::OK_200, res->status);
  2810. EXPECT_EQ("Hello World!", body);
  2811. }
  2812. {
  2813. Client cli("localhost", PORT);
  2814. std::string body;
  2815. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2816. body.append(data, data_length);
  2817. return true;
  2818. });
  2819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2820. EXPECT_EQ(StatusCode::Found_302, res->status);
  2821. EXPECT_EQ("___", body);
  2822. }
  2823. }
  2824. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2825. Server svr;
  2826. auto port_str = std::to_string(PORT);
  2827. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2828. auto expected_host = "[::1]:" + port_str;
  2829. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2830. res.set_content("___", "text/plain");
  2831. // res.set_redirect("/2");
  2832. res.set_redirect(redirect_url);
  2833. });
  2834. svr.Get("/2", [&](const Request &req, Response &res) {
  2835. auto host_header = req.headers.find("Host");
  2836. ASSERT_TRUE(host_header != req.headers.end());
  2837. EXPECT_EQ(expected_host, host_header->second);
  2838. res.set_content("Hello World!", "text/plain");
  2839. });
  2840. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2841. auto se = detail::scope_exit([&] {
  2842. svr.stop();
  2843. th.join();
  2844. ASSERT_FALSE(svr.is_running());
  2845. });
  2846. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2847. // actually starts anything, so the condition !svr.is_running() will
  2848. // always remain true, and the loop never stops.
  2849. // This basically counts how many milliseconds have passed since the
  2850. // call to svr.listen(), and if after 5 seconds nothing started yet
  2851. // aborts the test.
  2852. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2853. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2854. ASSERT_LT(milliseconds, 5000U);
  2855. }
  2856. {
  2857. Client cli("::1", PORT);
  2858. cli.set_follow_location(true);
  2859. std::string body;
  2860. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2861. body.append(data, data_length);
  2862. return true;
  2863. });
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. EXPECT_EQ(StatusCode::OK_200, res->status);
  2866. EXPECT_EQ("Hello World!", body);
  2867. }
  2868. {
  2869. Client cli("::1", PORT);
  2870. std::string body;
  2871. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2872. body.append(data, data_length);
  2873. return true;
  2874. });
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. EXPECT_EQ(StatusCode::Found_302, res->status);
  2877. EXPECT_EQ("___", body);
  2878. }
  2879. }
  2880. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2881. Server svr;
  2882. svr.Get("/foo", [](const Request &req, Response &res) {
  2883. auto a = req.params.find("a");
  2884. if (a != req.params.end()) {
  2885. res.set_content((*a).second, "text/plain");
  2886. res.status = StatusCode::OK_200;
  2887. } else {
  2888. res.status = StatusCode::BadRequest_400;
  2889. }
  2890. });
  2891. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2892. auto se = detail::scope_exit([&] {
  2893. svr.stop();
  2894. thread.join();
  2895. ASSERT_FALSE(svr.is_running());
  2896. });
  2897. svr.wait_until_ready();
  2898. {
  2899. Client cli(HOST, PORT);
  2900. cli.set_path_encode(false);
  2901. auto res = cli.Get("/foo?a=explicitly+encoded");
  2902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2903. EXPECT_EQ(StatusCode::OK_200, res->status);
  2904. // This expects it back with a space, as the `+` won't have been
  2905. // url-encoded, and server-side the params get decoded turning `+`
  2906. // into spaces.
  2907. EXPECT_EQ("explicitly encoded", res->body);
  2908. }
  2909. }
  2910. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2911. // When path encoding is disabled the client must transmit the supplied
  2912. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2913. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2914. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2915. // than a space (0x20). Assert on the raw wire target to catch this.
  2916. Server svr;
  2917. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2918. svr.Get("/foo", [&](const Request &req, Response &res) {
  2919. EXPECT_EQ(expected_target, req.target);
  2920. res.status = StatusCode::OK_200;
  2921. });
  2922. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2923. auto se = detail::scope_exit([&] {
  2924. svr.stop();
  2925. thread.join();
  2926. ASSERT_FALSE(svr.is_running());
  2927. });
  2928. svr.wait_until_ready();
  2929. {
  2930. Client cli(HOST, PORT);
  2931. cli.set_path_encode(false);
  2932. auto res = cli.Get(expected_target.c_str());
  2933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2934. EXPECT_EQ(StatusCode::OK_200, res->status);
  2935. }
  2936. }
  2937. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2938. // `open_stream()` used to skip the path encoding that the buffered send
  2939. // path applies, so the same `path` produced different bytes in the request
  2940. // line depending on which API was used. Assert the two agree.
  2941. Server svr;
  2942. std::string target;
  2943. svr.Get(".*", [&](const Request &req, Response &res) {
  2944. target = req.target;
  2945. res.status = StatusCode::OK_200;
  2946. });
  2947. auto port = svr.bind_to_any_port(HOST);
  2948. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2949. auto se = detail::scope_exit([&] {
  2950. svr.stop();
  2951. thread.join();
  2952. ASSERT_FALSE(svr.is_running());
  2953. });
  2954. svr.wait_until_ready();
  2955. struct {
  2956. const char *path;
  2957. const char *expected;
  2958. } cases[] = {
  2959. {"/a b?x=1", "/a%20b?x=1"},
  2960. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2961. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2962. };
  2963. for (const auto &c : cases) {
  2964. Client cli(HOST, port);
  2965. target.clear();
  2966. auto res = cli.Get(c.path);
  2967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2968. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2969. auto buffered_target = target;
  2970. target.clear();
  2971. auto handle = cli.open_stream("GET", c.path);
  2972. EXPECT_TRUE(handle.is_valid())
  2973. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2974. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2975. }
  2976. }
  2977. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2978. // The `set_path_encode(false)` contract — transmit the supplied target
  2979. // verbatim — must hold for the streaming API too.
  2980. Server svr;
  2981. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2982. std::string target;
  2983. svr.Get("/foo", [&](const Request &req, Response &res) {
  2984. target = req.target;
  2985. res.status = StatusCode::OK_200;
  2986. });
  2987. auto port = svr.bind_to_any_port(HOST);
  2988. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2989. auto se = detail::scope_exit([&] {
  2990. svr.stop();
  2991. thread.join();
  2992. ASSERT_FALSE(svr.is_running());
  2993. });
  2994. svr.wait_until_ready();
  2995. {
  2996. Client cli(HOST, port);
  2997. cli.set_path_encode(false);
  2998. auto handle = cli.open_stream("GET", expected_target);
  2999. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3000. EXPECT_EQ(expected_target, target);
  3001. }
  3002. }
  3003. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3004. // With path encoding enabled a CR/LF in the target is percent-encoded
  3005. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3006. // write_request_line still backstops `set_path_encode(false)`, which is
  3007. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3008. Server svr;
  3009. // Captured before routing: the decoded path contains a newline, which a
  3010. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3011. std::string target;
  3012. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3013. target = req.target;
  3014. res.status = StatusCode::OK_200;
  3015. return Server::HandlerResponse::Handled;
  3016. });
  3017. auto port = svr.bind_to_any_port(HOST);
  3018. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3019. auto se = detail::scope_exit([&] {
  3020. svr.stop();
  3021. thread.join();
  3022. ASSERT_FALSE(svr.is_running());
  3023. });
  3024. svr.wait_until_ready();
  3025. {
  3026. Client cli(HOST, port);
  3027. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3028. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3029. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3030. }
  3031. }
  3032. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3033. // Nothing may reach the wire: a raw CR/LF target would split the request
  3034. // line and inject headers.
  3035. Server svr;
  3036. // Pre-routing so that "not called" means nothing reached the server at all,
  3037. // rather than merely failing to match a handler pattern.
  3038. auto handler_called = false;
  3039. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3040. handler_called = true;
  3041. res.status = StatusCode::OK_200;
  3042. return Server::HandlerResponse::Handled;
  3043. });
  3044. auto port = svr.bind_to_any_port(HOST);
  3045. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3046. auto se = detail::scope_exit([&] {
  3047. svr.stop();
  3048. thread.join();
  3049. ASSERT_FALSE(svr.is_running());
  3050. });
  3051. svr.wait_until_ready();
  3052. {
  3053. Client cli(HOST, port);
  3054. cli.set_path_encode(false);
  3055. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3056. EXPECT_FALSE(handle.is_valid());
  3057. EXPECT_EQ(Error::Write, handle.error);
  3058. EXPECT_FALSE(handler_called);
  3059. }
  3060. }
  3061. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3062. // Which of the two branches runs is decided by whether the query component
  3063. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3064. // an empty query and must still fall back to building one from
  3065. // `req.params`, while a non-empty query must win over `req.params`.
  3066. Server svr;
  3067. std::string target;
  3068. svr.Get("/foo", [&](const Request &req, Response &res) {
  3069. target = req.target;
  3070. res.status = StatusCode::OK_200;
  3071. });
  3072. auto port = svr.bind_to_any_port(HOST);
  3073. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3074. auto se = detail::scope_exit([&] {
  3075. svr.stop();
  3076. thread.join();
  3077. ASSERT_FALSE(svr.is_running());
  3078. });
  3079. svr.wait_until_ready();
  3080. {
  3081. // Trailing `?` -> empty query component -> `req.params` is used.
  3082. Client cli(HOST, port);
  3083. Request req;
  3084. req.method = "GET";
  3085. req.path = "/foo?";
  3086. req.params.emplace("a", "1");
  3087. target.clear();
  3088. auto res = cli.send(req);
  3089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3090. EXPECT_EQ("/foo?a=1", target);
  3091. }
  3092. {
  3093. // Non-empty query in `req.path` -> `req.params` is not appended.
  3094. Client cli(HOST, port);
  3095. Request req;
  3096. req.method = "GET";
  3097. req.path = "/foo?b=2";
  3098. req.params.emplace("a", "1");
  3099. target.clear();
  3100. auto res = cli.send(req);
  3101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3102. EXPECT_EQ("/foo?b=2", target);
  3103. }
  3104. }
  3105. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3106. Server svr;
  3107. svr.Get("/", [](const Request &req, Response &) {
  3108. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3109. });
  3110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3111. auto se = detail::scope_exit([&] {
  3112. svr.stop();
  3113. thread.join();
  3114. ASSERT_FALSE(svr.is_running());
  3115. });
  3116. svr.wait_until_ready();
  3117. {
  3118. Client cli(HOST, PORT);
  3119. cli.set_path_encode(false);
  3120. auto res = cli.Get("/?something=%0A");
  3121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3122. EXPECT_EQ(StatusCode::OK_200, res->status);
  3123. }
  3124. }
  3125. TEST(BindServerTest, BindDualStack) {
  3126. Server svr;
  3127. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3128. res.set_content("Hello World!", "text/plain");
  3129. });
  3130. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3131. auto se = detail::scope_exit([&] {
  3132. svr.stop();
  3133. thread.join();
  3134. ASSERT_FALSE(svr.is_running());
  3135. });
  3136. svr.wait_until_ready();
  3137. {
  3138. Client cli("127.0.0.1", PORT);
  3139. auto res = cli.Get("/1");
  3140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3141. EXPECT_EQ(StatusCode::OK_200, res->status);
  3142. EXPECT_EQ("Hello World!", res->body);
  3143. }
  3144. {
  3145. Client cli("::1", PORT);
  3146. auto res = cli.Get("/1");
  3147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3148. EXPECT_EQ(StatusCode::OK_200, res->status);
  3149. EXPECT_EQ("Hello World!", res->body);
  3150. }
  3151. }
  3152. TEST(BindServerTest, BindAndListenSeparately) {
  3153. Server svr;
  3154. int port = svr.bind_to_any_port("0.0.0.0");
  3155. ASSERT_TRUE(svr.is_valid());
  3156. ASSERT_TRUE(port > 0);
  3157. svr.stop();
  3158. }
  3159. // Reports whether anything is still listening on a loopback port. A plain
  3160. // connect() is used instead of a Client request because a socket left bound by
  3161. // mistake accepts the connection into its backlog and never answers, which
  3162. // would hang the test instead of failing it.
  3163. static bool is_loopback_port_accepting(int port) {
  3164. sockaddr_in addr{};
  3165. addr.sin_family = AF_INET;
  3166. addr.sin_port = htons(static_cast<uint16_t>(port));
  3167. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3168. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3169. EXPECT_NE(sock, INVALID_SOCKET);
  3170. if (sock == INVALID_SOCKET) { return false; }
  3171. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3172. static_cast<socklen_t>(sizeof(addr)));
  3173. detail::close_socket(sock);
  3174. return ret == 0;
  3175. }
  3176. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3177. Server svr;
  3178. auto port = svr.bind_to_any_port("127.0.0.1");
  3179. ASSERT_TRUE(port > 0);
  3180. svr.stop();
  3181. // bind_to_any_port() already called listen(2), so until stop() closed the
  3182. // descriptor the port kept accepting connections into the backlog. ASSERT
  3183. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3184. // below blocks forever in the accept loop.
  3185. ASSERT_FALSE(is_loopback_port_accepting(port));
  3186. // Nothing is left to accept on, so listen_after_bind() must report failure
  3187. // instead of returning success without ever serving.
  3188. EXPECT_FALSE(svr.listen_after_bind());
  3189. // The failed listen marks the server decommissioned, so a waiter returns
  3190. // instead of spinning forever.
  3191. svr.wait_until_ready();
  3192. }
  3193. #ifdef CPPHTTPLIB_SSL_ENABLED
  3194. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3195. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3196. CLIENT_CA_CERT_DIR);
  3197. int port = svr.bind_to_any_port("0.0.0.0");
  3198. ASSERT_TRUE(svr.is_valid());
  3199. ASSERT_TRUE(port > 0);
  3200. svr.stop();
  3201. }
  3202. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3203. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3204. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3205. int port = svr.bind_to_any_port("0.0.0.0");
  3206. ASSERT_TRUE(svr.is_valid());
  3207. ASSERT_TRUE(port > 0);
  3208. svr.stop();
  3209. }
  3210. TEST(BindServerTest, UpdateCertsPem) {
  3211. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3212. int port = svr.bind_to_any_port("0.0.0.0");
  3213. ASSERT_TRUE(svr.is_valid());
  3214. ASSERT_TRUE(port > 0);
  3215. // Read PEM files
  3216. std::string cert_pem, key_pem, ca_pem;
  3217. read_file(SERVER_CERT_FILE, cert_pem);
  3218. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3219. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3220. // Update server certificates using PEM API
  3221. ASSERT_TRUE(
  3222. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3223. ASSERT_TRUE(svr.is_valid());
  3224. svr.stop();
  3225. }
  3226. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3227. // Start server with client CA (enables client auth)
  3228. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3229. ASSERT_TRUE(svr.is_valid());
  3230. bool handler_called = false;
  3231. svr.Get("/test", [&](const Request &req, Response &res) {
  3232. handler_called = true;
  3233. // Verify client certificate is present
  3234. auto cert = req.peer_cert();
  3235. EXPECT_TRUE(static_cast<bool>(cert));
  3236. res.set_content("ok", "text/plain");
  3237. });
  3238. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3239. auto se = detail::scope_exit([&] {
  3240. svr.stop();
  3241. t.join();
  3242. ASSERT_FALSE(svr.is_running());
  3243. });
  3244. svr.wait_until_ready();
  3245. // Read PEM files
  3246. std::string cert_pem, key_pem, ca_pem;
  3247. read_file(SERVER_CERT_FILE, cert_pem);
  3248. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3249. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3250. // Update server certificates and client CA using PEM API while server running
  3251. ASSERT_TRUE(
  3252. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3253. // Connect with client certificate
  3254. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3255. cli.enable_server_certificate_verification(false);
  3256. cli.set_connection_timeout(30);
  3257. auto res = cli.Get("/test");
  3258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3259. ASSERT_EQ(StatusCode::OK_200, res->status);
  3260. ASSERT_TRUE(handler_called);
  3261. EXPECT_EQ("ok", res->body);
  3262. }
  3263. #endif
  3264. TEST(ErrorHandlerTest, ContentLength) {
  3265. Server svr;
  3266. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3267. res.status = StatusCode::OK_200;
  3268. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3269. "text/html"); // <= Content-Length still 13
  3270. });
  3271. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3272. res.set_content("Hello World!\n", "text/plain");
  3273. res.status = 524;
  3274. });
  3275. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3276. auto se = detail::scope_exit([&] {
  3277. svr.stop();
  3278. thread.join();
  3279. ASSERT_FALSE(svr.is_running());
  3280. });
  3281. svr.wait_until_ready();
  3282. {
  3283. Client cli(HOST, PORT);
  3284. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3288. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3289. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3290. }
  3291. }
  3292. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3293. TEST(ExceptionTest, WithoutExceptionHandler) {
  3294. Server svr;
  3295. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3296. throw std::runtime_error("exception...");
  3297. });
  3298. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3299. throw std::runtime_error("exception\r\n...");
  3300. });
  3301. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3302. auto se = detail::scope_exit([&] {
  3303. svr.stop();
  3304. listen_thread.join();
  3305. ASSERT_FALSE(svr.is_running());
  3306. });
  3307. svr.wait_until_ready();
  3308. Client cli("localhost", PORT);
  3309. {
  3310. auto res = cli.Get("/exception");
  3311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3312. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3313. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3314. }
  3315. {
  3316. auto res = cli.Get("/unknown");
  3317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3318. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3319. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3320. }
  3321. }
  3322. TEST(ExceptionTest, WithExceptionHandler) {
  3323. Server svr;
  3324. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3325. std::exception_ptr ep) {
  3326. EXPECT_FALSE(ep == nullptr);
  3327. try {
  3328. std::rethrow_exception(ep);
  3329. } catch (std::exception &e) {
  3330. EXPECT_EQ("abc", std::string(e.what()));
  3331. } catch (...) {}
  3332. res.status = StatusCode::InternalServerError_500;
  3333. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3334. "text/html"); // <= Content-Length still 13 at this point
  3335. });
  3336. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3337. res.set_content("Hello World!\n", "text/plain");
  3338. throw std::runtime_error("abc");
  3339. });
  3340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3341. auto se = detail::scope_exit([&] {
  3342. svr.stop();
  3343. thread.join();
  3344. ASSERT_FALSE(svr.is_running());
  3345. });
  3346. svr.wait_until_ready();
  3347. for (size_t i = 0; i < 10; i++) {
  3348. Client cli(HOST, PORT);
  3349. for (size_t j = 0; j < 100; j++) {
  3350. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3352. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3353. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3354. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3355. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3356. }
  3357. cli.set_keep_alive(true);
  3358. for (size_t j = 0; j < 100; j++) {
  3359. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3361. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3362. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3363. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3364. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3365. }
  3366. }
  3367. }
  3368. TEST(ExceptionTest, AndErrorHandler) {
  3369. Server svr;
  3370. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3371. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3372. });
  3373. svr.set_exception_handler(
  3374. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3375. EXPECT_FALSE(ep == nullptr);
  3376. try {
  3377. std::rethrow_exception(ep);
  3378. } catch (std::exception &e) {
  3379. res.set_content(e.what(), "text/html");
  3380. } catch (...) {}
  3381. res.status = StatusCode::InternalServerError_500;
  3382. });
  3383. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3384. throw std::runtime_error("EXCEPTION");
  3385. });
  3386. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3387. res.set_content("ERROR", "text/html");
  3388. res.status = StatusCode::InternalServerError_500;
  3389. });
  3390. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3391. auto se = detail::scope_exit([&] {
  3392. svr.stop();
  3393. thread.join();
  3394. ASSERT_FALSE(svr.is_running());
  3395. });
  3396. svr.wait_until_ready();
  3397. Client cli(HOST, PORT);
  3398. {
  3399. auto res = cli.Get("/exception");
  3400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3401. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3402. EXPECT_EQ("EXCEPTION", res->body);
  3403. }
  3404. {
  3405. auto res = cli.Get("/error");
  3406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3407. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3408. EXPECT_EQ("ERROR", res->body);
  3409. }
  3410. {
  3411. auto res = cli.Get("/invalid");
  3412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3413. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3414. EXPECT_EQ("NOT_FOUND", res->body);
  3415. }
  3416. }
  3417. #endif
  3418. TEST(NoContentTest, ContentLength) {
  3419. Server svr;
  3420. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3421. res.status = StatusCode::NoContent_204;
  3422. });
  3423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3424. auto se = detail::scope_exit([&] {
  3425. svr.stop();
  3426. thread.join();
  3427. ASSERT_FALSE(svr.is_running());
  3428. });
  3429. svr.wait_until_ready();
  3430. {
  3431. Client cli(HOST, PORT);
  3432. auto res = cli.Get("/hi");
  3433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3434. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3435. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3436. }
  3437. }
  3438. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3439. #ifdef CPPHTTPLIB_SSL_ENABLED
  3440. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3441. ASSERT_TRUE(svr.is_valid());
  3442. #else
  3443. Server svr;
  3444. #endif
  3445. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3446. if (req.path == "/routing_handler") {
  3447. res.set_header("PRE_ROUTING", "on");
  3448. res.set_content("Routing Handler", "text/plain");
  3449. return httplib::Server::HandlerResponse::Handled;
  3450. }
  3451. return httplib::Server::HandlerResponse::Unhandled;
  3452. });
  3453. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3454. res.set_content("Error", "text/html");
  3455. });
  3456. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3457. if (req.path == "/routing_handler") {
  3458. res.set_header("POST_ROUTING", "on");
  3459. }
  3460. });
  3461. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3462. res.set_content("Hello World!\n", "text/plain");
  3463. });
  3464. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3465. auto se = detail::scope_exit([&] {
  3466. svr.stop();
  3467. thread.join();
  3468. ASSERT_FALSE(svr.is_running());
  3469. });
  3470. svr.wait_until_ready();
  3471. {
  3472. #ifdef CPPHTTPLIB_SSL_ENABLED
  3473. SSLClient cli(HOST, PORT);
  3474. cli.enable_server_certificate_verification(false);
  3475. #else
  3476. Client cli(HOST, PORT);
  3477. #endif
  3478. auto res = cli.Get("/routing_handler");
  3479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3480. EXPECT_EQ(StatusCode::OK_200, res->status);
  3481. EXPECT_EQ("Routing Handler", res->body);
  3482. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3483. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3484. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3485. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3486. }
  3487. {
  3488. #ifdef CPPHTTPLIB_SSL_ENABLED
  3489. SSLClient cli(HOST, PORT);
  3490. cli.enable_server_certificate_verification(false);
  3491. #else
  3492. Client cli(HOST, PORT);
  3493. #endif
  3494. auto res = cli.Get("/hi");
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. EXPECT_EQ("Hello World!\n", res->body);
  3498. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3499. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3500. }
  3501. {
  3502. #ifdef CPPHTTPLIB_SSL_ENABLED
  3503. SSLClient cli(HOST, PORT);
  3504. cli.enable_server_certificate_verification(false);
  3505. #else
  3506. Client cli(HOST, PORT);
  3507. #endif
  3508. auto res = cli.Get("/aaa");
  3509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3510. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3511. EXPECT_EQ("Error", res->body);
  3512. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3513. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3514. }
  3515. }
  3516. TEST(RequestHandlerTest, PreRequestHandler) {
  3517. auto route_path = "/user/:user";
  3518. Server svr;
  3519. svr.Get("/hi", [](const Request &, Response &res) {
  3520. res.set_content("hi", "text/plain");
  3521. });
  3522. svr.Get(route_path, [](const Request &req, Response &res) {
  3523. res.set_content(req.path_params.at("user"), "text/plain");
  3524. });
  3525. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3526. if (req.matched_route == route_path) {
  3527. auto user = req.path_params.at("user");
  3528. if (user != "john") {
  3529. res.status = StatusCode::Forbidden_403;
  3530. res.set_content("error", "text/html");
  3531. return Server::HandlerResponse::Handled;
  3532. }
  3533. }
  3534. return Server::HandlerResponse::Unhandled;
  3535. });
  3536. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3537. auto se = detail::scope_exit([&] {
  3538. svr.stop();
  3539. thread.join();
  3540. ASSERT_FALSE(svr.is_running());
  3541. });
  3542. svr.wait_until_ready();
  3543. Client cli(HOST, PORT);
  3544. {
  3545. auto res = cli.Get("/hi");
  3546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3547. EXPECT_EQ(StatusCode::OK_200, res->status);
  3548. EXPECT_EQ("hi", res->body);
  3549. }
  3550. {
  3551. auto res = cli.Get("/user/john");
  3552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3553. EXPECT_EQ(StatusCode::OK_200, res->status);
  3554. EXPECT_EQ("john", res->body);
  3555. }
  3556. {
  3557. auto res = cli.Get("/user/invalid-user");
  3558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3559. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3560. EXPECT_EQ("error", res->body);
  3561. }
  3562. }
  3563. // The pre-request handler must run before the request body is read, so a
  3564. // rejected request never forces the server to buffer a (potentially large)
  3565. // body. Here the posted body is larger than the payload limit: if the body
  3566. // were read first the server would answer 413, but because the pre-request
  3567. // handler runs first it answers 403 and the body is never read.
  3568. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3569. Server svr;
  3570. svr.set_payload_max_length(8);
  3571. auto handler_ran = false;
  3572. svr.Post("/reject", [&](const Request &req, Response &res) {
  3573. handler_ran = true;
  3574. res.set_content(req.body, "text/plain");
  3575. });
  3576. svr.Post("/accept", [](const Request &req, Response &res) {
  3577. res.set_content(req.body, "text/plain");
  3578. });
  3579. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3580. if (req.matched_route == "/reject") {
  3581. res.status = StatusCode::Forbidden_403;
  3582. res.set_content("denied", "text/plain");
  3583. return Server::HandlerResponse::Handled;
  3584. }
  3585. return Server::HandlerResponse::Unhandled;
  3586. });
  3587. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3588. auto se = detail::scope_exit([&] {
  3589. svr.stop();
  3590. thread.join();
  3591. ASSERT_FALSE(svr.is_running());
  3592. });
  3593. svr.wait_until_ready();
  3594. Client cli(HOST, PORT);
  3595. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3596. // rejects with 403 before the body is read, so 413 is never reached.
  3597. {
  3598. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3600. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3601. EXPECT_EQ("denied", res->body);
  3602. EXPECT_FALSE(handler_ran);
  3603. }
  3604. // An approved route still reads the body and enforces the payload limit.
  3605. {
  3606. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3608. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3609. }
  3610. }
  3611. TEST(UserDataTest, BasicOperations) {
  3612. httplib::UserData ud;
  3613. // Initially empty
  3614. EXPECT_FALSE(ud.has("key"));
  3615. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3616. // set and get
  3617. ud.set("key", 42);
  3618. EXPECT_TRUE(ud.has("key"));
  3619. auto *p = ud.get<int>("key");
  3620. ASSERT_NE(nullptr, p);
  3621. EXPECT_EQ(42, *p);
  3622. // Type mismatch → nullptr
  3623. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3624. // Overwrite with different type
  3625. ud.set("key", std::string("hello"));
  3626. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3627. auto *s = ud.get<std::string>("key");
  3628. ASSERT_NE(nullptr, s);
  3629. EXPECT_EQ("hello", *s);
  3630. // erase
  3631. ud.erase("key");
  3632. EXPECT_FALSE(ud.has("key"));
  3633. // clear
  3634. ud.set("a", 1);
  3635. ud.set("b", 2);
  3636. ud.clear();
  3637. EXPECT_FALSE(ud.has("a"));
  3638. EXPECT_FALSE(ud.has("b"));
  3639. }
  3640. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3641. struct AuthCtx {
  3642. std::string user_id;
  3643. };
  3644. Server svr;
  3645. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3646. res.user_data.set("auth", AuthCtx{"alice"});
  3647. return Server::HandlerResponse::Unhandled;
  3648. });
  3649. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3650. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3651. ASSERT_NE(nullptr, ctx);
  3652. res.set_content("Hello " + ctx->user_id, "text/plain");
  3653. });
  3654. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3655. auto se = detail::scope_exit([&] {
  3656. svr.stop();
  3657. thread.join();
  3658. ASSERT_FALSE(svr.is_running());
  3659. });
  3660. svr.wait_until_ready();
  3661. Client cli(HOST, PORT);
  3662. auto res = cli.Get("/me");
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::OK_200, res->status);
  3665. EXPECT_EQ("Hello alice", res->body);
  3666. }
  3667. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3668. struct RoleCtx {
  3669. std::string role;
  3670. };
  3671. Server svr;
  3672. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3673. res.user_data.set("role", RoleCtx{"admin"});
  3674. return Server::HandlerResponse::Unhandled;
  3675. });
  3676. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3677. auto *ctx = res.user_data.get<RoleCtx>("role");
  3678. ASSERT_NE(nullptr, ctx);
  3679. res.set_content(ctx->role, "text/plain");
  3680. });
  3681. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3682. auto se = detail::scope_exit([&] {
  3683. svr.stop();
  3684. thread.join();
  3685. ASSERT_FALSE(svr.is_running());
  3686. });
  3687. svr.wait_until_ready();
  3688. Client cli(HOST, PORT);
  3689. auto res = cli.Get("/role");
  3690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. EXPECT_EQ("admin", res->body);
  3693. }
  3694. TEST(InvalidFormatTest, StatusCode) {
  3695. Server svr;
  3696. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3697. res.set_content("Hello World!\n", "text/plain");
  3698. res.status = 9999; // Status should be a three-digit code...
  3699. });
  3700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3701. auto se = detail::scope_exit([&] {
  3702. svr.stop();
  3703. thread.join();
  3704. ASSERT_FALSE(svr.is_running());
  3705. });
  3706. svr.wait_until_ready();
  3707. {
  3708. Client cli(HOST, PORT);
  3709. auto res = cli.Get("/hi");
  3710. ASSERT_FALSE(res);
  3711. }
  3712. }
  3713. TEST(URLFragmentTest, WithFragment) {
  3714. Server svr;
  3715. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3716. EXPECT_TRUE(req.target == "/hi");
  3717. });
  3718. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3719. auto se = detail::scope_exit([&] {
  3720. svr.stop();
  3721. thread.join();
  3722. ASSERT_FALSE(svr.is_running());
  3723. });
  3724. svr.wait_until_ready();
  3725. {
  3726. Client cli(HOST, PORT);
  3727. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3728. EXPECT_TRUE(res);
  3729. EXPECT_EQ(StatusCode::OK_200, res->status);
  3730. res = cli.Get("/hi%23key1=val1=key2=val2");
  3731. EXPECT_TRUE(res);
  3732. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3733. }
  3734. }
  3735. TEST(HeaderWriter, SetHeaderWriter) {
  3736. Server svr;
  3737. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3738. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3739. return detail::write_headers(strm, hdrs);
  3740. });
  3741. svr.Get("/hi", [](const Request &req, Response &res) {
  3742. auto it = req.headers.find("CustomClientHeader");
  3743. EXPECT_TRUE(it != req.headers.end());
  3744. EXPECT_EQ(it->second, "CustomClientValue");
  3745. res.set_content("Hello World!\n", "text/plain");
  3746. });
  3747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3748. auto se = detail::scope_exit([&] {
  3749. svr.stop();
  3750. thread.join();
  3751. ASSERT_FALSE(svr.is_running());
  3752. });
  3753. svr.wait_until_ready();
  3754. {
  3755. Client cli(HOST, PORT);
  3756. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3757. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3758. return detail::write_headers(strm, hdrs);
  3759. });
  3760. auto res = cli.Get("/hi");
  3761. EXPECT_TRUE(res);
  3762. EXPECT_EQ(StatusCode::OK_200, res->status);
  3763. auto it = res->headers.find("CustomServerHeader");
  3764. EXPECT_TRUE(it != res->headers.end());
  3765. EXPECT_EQ(it->second, "CustomServerValue");
  3766. }
  3767. }
  3768. class ServerTest : public ::testing::Test {
  3769. protected:
  3770. ServerTest()
  3771. : cli_(HOST, PORT)
  3772. #ifdef CPPHTTPLIB_SSL_ENABLED
  3773. ,
  3774. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3775. #endif
  3776. {
  3777. #ifdef CPPHTTPLIB_SSL_ENABLED
  3778. cli_.enable_server_certificate_verification(false);
  3779. #endif
  3780. // Allow LARGE_DATA (100MB) responses
  3781. cli_.set_payload_max_length(200 * 1024 * 1024);
  3782. }
  3783. virtual void SetUp() {
  3784. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3785. svr_.set_payload_max_length(200 * 1024 * 1024);
  3786. svr_.set_mount_point("/", "./www");
  3787. svr_.set_mount_point("/mount", "./www2");
  3788. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3789. svr_.Get("/hi",
  3790. [&](const Request & /*req*/, Response &res) {
  3791. res.set_content("Hello World!", "text/plain");
  3792. })
  3793. .Get("/file_content",
  3794. [&](const Request & /*req*/, Response &res) {
  3795. res.set_file_content("./www/dir/test.html");
  3796. })
  3797. .Get("/file_content_with_content_type",
  3798. [&](const Request & /*req*/, Response &res) {
  3799. res.set_file_content("./www/file", "text/plain");
  3800. })
  3801. .Get("/invalid_file_content",
  3802. [&](const Request & /*req*/, Response &res) {
  3803. res.set_file_content("./www/dir/invalid_file_path");
  3804. })
  3805. .Get("/http_response_splitting",
  3806. [&](const Request & /*req*/, Response &res) {
  3807. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3808. EXPECT_EQ(0U, res.headers.size());
  3809. EXPECT_FALSE(res.has_header("a"));
  3810. res.set_header("a", "1\nSet-Cookie: a=1");
  3811. EXPECT_EQ(0U, res.headers.size());
  3812. EXPECT_FALSE(res.has_header("a"));
  3813. res.set_header("a", "1\rSet-Cookie: a=1");
  3814. EXPECT_EQ(0U, res.headers.size());
  3815. EXPECT_FALSE(res.has_header("a"));
  3816. res.set_header("a\r\nb", "0");
  3817. EXPECT_EQ(0U, res.headers.size());
  3818. EXPECT_FALSE(res.has_header("a"));
  3819. res.set_header("a\rb", "0");
  3820. EXPECT_EQ(0U, res.headers.size());
  3821. EXPECT_FALSE(res.has_header("a"));
  3822. res.set_header("a\nb", "0");
  3823. EXPECT_EQ(0U, res.headers.size());
  3824. EXPECT_FALSE(res.has_header("a"));
  3825. res.set_redirect("1\r\nSet-Cookie: a=1");
  3826. EXPECT_EQ(0U, res.headers.size());
  3827. EXPECT_FALSE(res.has_header("Location"));
  3828. })
  3829. .Get("/slow",
  3830. [&](const Request & /*req*/, Response &res) {
  3831. std::this_thread::sleep_for(std::chrono::seconds(4));
  3832. res.set_content("slow", "text/plain");
  3833. })
  3834. #if 0
  3835. .Post("/slowpost",
  3836. [&](const Request & /*req*/, Response &res) {
  3837. std::this_thread::sleep_for(std::chrono::seconds(2));
  3838. res.set_content("slow", "text/plain");
  3839. })
  3840. #endif
  3841. .Get("/remote_addr",
  3842. [&](const Request &req, Response &res) {
  3843. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3844. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3845. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3846. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3847. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3848. #endif
  3849. res.set_content(req.remote_addr, "text/plain");
  3850. })
  3851. .Get("/local_addr",
  3852. [&](const Request &req, Response &res) {
  3853. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3854. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3855. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3856. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3857. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3858. #endif
  3859. auto local_addr = req.local_addr;
  3860. auto local_port = std::to_string(req.local_port);
  3861. res.set_content(local_addr.append(":").append(local_port),
  3862. "text/plain");
  3863. })
  3864. .Get("/endwith%",
  3865. [&](const Request & /*req*/, Response &res) {
  3866. res.set_content("Hello World!", "text/plain");
  3867. })
  3868. .Get("/a\\+\\+b",
  3869. [&](const Request &req, Response &res) {
  3870. ASSERT_TRUE(req.has_param("a +b"));
  3871. auto val = req.get_param_value("a +b");
  3872. res.set_content(val, "text/plain");
  3873. })
  3874. .Get("/", [&](const Request & /*req*/,
  3875. Response &res) { res.set_redirect("/hi"); })
  3876. .Post("/1",
  3877. [](const Request & /*req*/, Response &res) {
  3878. res.set_redirect("/2", StatusCode::SeeOther_303);
  3879. })
  3880. .Get("/2",
  3881. [](const Request & /*req*/, Response &res) {
  3882. res.set_content("redirected.", "text/plain");
  3883. res.status = StatusCode::OK_200;
  3884. })
  3885. .Post("/person",
  3886. [&](const Request &req, Response &res) {
  3887. if (req.has_param("name") && req.has_param("note")) {
  3888. persons_[req.get_param_value("name")] =
  3889. req.get_param_value("note");
  3890. } else {
  3891. res.status = StatusCode::BadRequest_400;
  3892. }
  3893. })
  3894. .Put("/person",
  3895. [&](const Request &req, Response &res) {
  3896. if (req.has_param("name") && req.has_param("note")) {
  3897. persons_[req.get_param_value("name")] =
  3898. req.get_param_value("note");
  3899. } else {
  3900. res.status = StatusCode::BadRequest_400;
  3901. }
  3902. })
  3903. .Get("/person/(.*)",
  3904. [&](const Request &req, Response &res) {
  3905. string name = req.matches[1];
  3906. if (persons_.find(name) != persons_.end()) {
  3907. auto note = persons_[name];
  3908. res.set_content(note, "text/plain");
  3909. } else {
  3910. res.status = StatusCode::NotFound_404;
  3911. }
  3912. })
  3913. .Delete("/person",
  3914. [&](const Request &req, Response &res) {
  3915. if (req.has_param("name")) {
  3916. string name = req.get_param_value("name");
  3917. if (persons_.find(name) != persons_.end()) {
  3918. persons_.erase(name);
  3919. res.set_content("DELETED", "text/plain");
  3920. } else {
  3921. res.status = StatusCode::NotFound_404;
  3922. }
  3923. } else {
  3924. res.status = StatusCode::BadRequest_400;
  3925. }
  3926. })
  3927. .Post("/x-www-form-urlencoded-json",
  3928. [&](const Request &req, Response &res) {
  3929. auto json = req.get_param_value("json");
  3930. ASSERT_EQ(JSON_DATA, json);
  3931. res.set_content(json, "appliation/json");
  3932. res.status = StatusCode::OK_200;
  3933. })
  3934. .Get("/streamed-chunked",
  3935. [&](const Request & /*req*/, Response &res) {
  3936. res.set_chunked_content_provider(
  3937. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3938. sink.os << "123";
  3939. sink.os << "456";
  3940. sink.os << "789";
  3941. sink.done();
  3942. return true;
  3943. });
  3944. })
  3945. .Get("/streamed-chunked-with-prohibited-trailer",
  3946. [&](const Request & /*req*/, Response &res) {
  3947. auto i = new int(0);
  3948. // Declare both a prohibited trailer (Content-Length) and an
  3949. // allowed one
  3950. res.set_header("Trailer", "Content-Length, X-Allowed");
  3951. res.set_chunked_content_provider(
  3952. "text/plain",
  3953. [i](size_t /*offset*/, DataSink &sink) {
  3954. switch (*i) {
  3955. case 0: sink.os << "123"; break;
  3956. case 1: sink.os << "456"; break;
  3957. case 2: sink.os << "789"; break;
  3958. case 3: {
  3959. sink.done_with_trailer(
  3960. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3961. } break;
  3962. }
  3963. (*i)++;
  3964. return true;
  3965. },
  3966. [i](bool success) {
  3967. EXPECT_TRUE(success);
  3968. delete i;
  3969. });
  3970. })
  3971. .Get("/streamed-chunked2",
  3972. [&](const Request & /*req*/, Response &res) {
  3973. auto i = new int(0);
  3974. res.set_chunked_content_provider(
  3975. "text/plain",
  3976. [i](size_t /*offset*/, DataSink &sink) {
  3977. switch (*i) {
  3978. case 0: sink.os << "123"; break;
  3979. case 1: sink.os << "456"; break;
  3980. case 2: sink.os << "789"; break;
  3981. case 3: sink.done(); break;
  3982. }
  3983. (*i)++;
  3984. return true;
  3985. },
  3986. [i](bool success) {
  3987. EXPECT_TRUE(success);
  3988. delete i;
  3989. });
  3990. })
  3991. .Get("/streamed-chunked-with-trailer",
  3992. [&](const Request & /*req*/, Response &res) {
  3993. auto i = new int(0);
  3994. res.set_header("Trailer", "Dummy1, Dummy2");
  3995. res.set_chunked_content_provider(
  3996. "text/plain",
  3997. [i](size_t /*offset*/, DataSink &sink) {
  3998. switch (*i) {
  3999. case 0: sink.os << "123"; break;
  4000. case 1: sink.os << "456"; break;
  4001. case 2: sink.os << "789"; break;
  4002. case 3: {
  4003. sink.done_with_trailer(
  4004. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4005. } break;
  4006. }
  4007. (*i)++;
  4008. return true;
  4009. },
  4010. [i](bool success) {
  4011. EXPECT_TRUE(success);
  4012. delete i;
  4013. });
  4014. })
  4015. .Get("/streamed",
  4016. [&](const Request & /*req*/, Response &res) {
  4017. res.set_content_provider(
  4018. 6, "text/plain",
  4019. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4020. sink.os << (offset < 3 ? "a" : "b");
  4021. return true;
  4022. });
  4023. })
  4024. .Get("/streamed-without-length",
  4025. [&](const Request & /*req*/, Response &res) {
  4026. auto data = new std::string("abcdefg");
  4027. res.set_content_provider(
  4028. "text/plain",
  4029. [data](size_t offset, DataSink &sink) {
  4030. if (offset < data->size()) {
  4031. sink.os << data->substr(offset);
  4032. }
  4033. sink.done();
  4034. return true;
  4035. },
  4036. [data](bool success) {
  4037. EXPECT_TRUE(success);
  4038. delete data;
  4039. });
  4040. })
  4041. .Get("/streamed-with-range",
  4042. [&](const Request &req, Response &res) {
  4043. auto data = new std::string("abcdefg");
  4044. // An explicit status keeps the server from picking the 206 it
  4045. // would otherwise choose for a ranged request, so the response
  4046. // is not a partial representation.
  4047. auto status = req.get_param_value("status");
  4048. if (status == "200") {
  4049. res.status = StatusCode::OK_200;
  4050. } else if (status == "403") {
  4051. res.status = StatusCode::Forbidden_403;
  4052. }
  4053. res.set_content_provider(
  4054. data->size(), "text/plain",
  4055. [data](size_t offset, size_t length, DataSink &sink) {
  4056. size_t DATA_CHUNK_SIZE = 4;
  4057. const auto &d = *data;
  4058. auto out_len =
  4059. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4060. auto ret =
  4061. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4062. EXPECT_TRUE(ret);
  4063. return true;
  4064. },
  4065. [data, &req](bool success) {
  4066. EXPECT_EQ(success, !req.has_param("error"));
  4067. delete data;
  4068. });
  4069. })
  4070. .Get("/streamed-cancel",
  4071. [&](const Request & /*req*/, Response &res) {
  4072. res.set_content_provider(
  4073. size_t(-1), "text/plain",
  4074. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4075. sink.os << "data_chunk";
  4076. return true;
  4077. });
  4078. })
  4079. .Get("/regex-with-delimiter",
  4080. [&](const Request &req, Response & /*res*/) {
  4081. ASSERT_TRUE(req.has_param("key"));
  4082. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4083. })
  4084. .Get("/with-range",
  4085. [&](const Request & /*req*/, Response &res) {
  4086. res.set_content("abcdefg", "text/plain");
  4087. })
  4088. .Get("/test-start-time",
  4089. [&](const Request &req, Response & /*res*/) {
  4090. EXPECT_NE(req.start_time_,
  4091. std::chrono::steady_clock::time_point::min());
  4092. })
  4093. .Get("/with-range-customized-response",
  4094. [&](const Request & /*req*/, Response &res) {
  4095. res.status = StatusCode::BadRequest_400;
  4096. res.set_content(JSON_DATA, "application/json");
  4097. })
  4098. .Post("/chunked",
  4099. [&](const Request &req, Response & /*res*/) {
  4100. EXPECT_EQ(req.body, "dechunked post body");
  4101. })
  4102. .Post("/large-chunked",
  4103. [&](const Request &req, Response & /*res*/) {
  4104. std::string expected(6 * 30 * 1024u, 'a');
  4105. EXPECT_EQ(req.body, expected);
  4106. })
  4107. .Post("/multipart",
  4108. [&](const Request &req, Response & /*res*/) {
  4109. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4110. req.form.get_field_count("text2") +
  4111. req.form.get_field_count("file3") +
  4112. req.form.get_field_count("file4"));
  4113. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4114. req.form.get_file_count("file2"));
  4115. ASSERT_TRUE(!req.form.has_file("???"));
  4116. ASSERT_TRUE(!req.form.has_field("???"));
  4117. ASSERT_TRUE(req.body.empty());
  4118. {
  4119. const auto &text = req.form.get_field("text1");
  4120. EXPECT_EQ("text default", text);
  4121. }
  4122. {
  4123. const auto &text = req.form.get_field("text2");
  4124. EXPECT_EQ("aωb", text);
  4125. }
  4126. {
  4127. const auto &file = req.form.get_file("file1");
  4128. EXPECT_EQ("hello.txt", file.filename);
  4129. EXPECT_EQ("text/plain", file.content_type);
  4130. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4131. }
  4132. {
  4133. const auto &file = req.form.get_file("file2");
  4134. EXPECT_EQ("world.json", file.filename);
  4135. EXPECT_EQ("application/json", file.content_type);
  4136. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4137. }
  4138. {
  4139. const auto &text = req.form.get_field("file3");
  4140. EXPECT_EQ(0u, text.size());
  4141. }
  4142. {
  4143. const auto &text = req.form.get_field("file4");
  4144. EXPECT_EQ(0u, text.size());
  4145. }
  4146. })
  4147. .Post("/multipart/multi_file_values",
  4148. [&](const Request &req, Response & /*res*/) {
  4149. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4150. req.form.get_field_count("multi_text1"));
  4151. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4152. ASSERT_TRUE(!req.form.has_file("???"));
  4153. ASSERT_TRUE(!req.form.has_field("???"));
  4154. ASSERT_TRUE(req.body.empty());
  4155. {
  4156. const auto &text = req.form.get_field("text");
  4157. EXPECT_EQ("default text", text);
  4158. }
  4159. {
  4160. const auto &text1_values = req.form.get_fields("multi_text1");
  4161. EXPECT_EQ(2u, text1_values.size());
  4162. EXPECT_EQ("aaaaa", text1_values[0]);
  4163. EXPECT_EQ("bbbbb", text1_values[1]);
  4164. }
  4165. {
  4166. const auto &file1_values = req.form.get_files("multi_file1");
  4167. EXPECT_EQ(2u, file1_values.size());
  4168. auto file1 = file1_values[0];
  4169. EXPECT_EQ(file1.filename, "hello.txt");
  4170. EXPECT_EQ(file1.content_type, "text/plain");
  4171. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4172. auto file2 = file1_values[1];
  4173. EXPECT_EQ(file2.filename, "world.json");
  4174. EXPECT_EQ(file2.content_type, "application/json");
  4175. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4176. }
  4177. })
  4178. .Post("/empty",
  4179. [&](const Request &req, Response &res) {
  4180. EXPECT_EQ(req.body, "");
  4181. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4182. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4183. res.set_content("empty", "text/plain");
  4184. })
  4185. .Post("/empty-no-content-type",
  4186. [&](const Request &req, Response &res) {
  4187. EXPECT_EQ(req.body, "");
  4188. EXPECT_FALSE(req.has_header("Content-Type"));
  4189. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4190. res.set_content("empty-no-content-type", "text/plain");
  4191. })
  4192. .Post("/path-only",
  4193. [&](const Request &req, Response &res) {
  4194. EXPECT_EQ(req.body, "");
  4195. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4196. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4197. res.set_content("path-only", "text/plain");
  4198. })
  4199. .Post("/path-headers-only",
  4200. [&](const Request &req, Response &res) {
  4201. EXPECT_EQ(req.body, "");
  4202. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4203. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4204. EXPECT_EQ("world", req.get_header_value("hello"));
  4205. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4206. res.set_content("path-headers-only", "text/plain");
  4207. })
  4208. .Post("/post-large",
  4209. [&](const Request &req, Response &res) {
  4210. EXPECT_EQ(req.body, LARGE_DATA);
  4211. res.set_content(req.body, "text/plain");
  4212. })
  4213. .Post("/post-loopback",
  4214. [&](const Request &, Response &res,
  4215. ContentReader const &content_reader) {
  4216. std::string body;
  4217. content_reader([&](const char *data, size_t data_length) {
  4218. body.append(data, data_length);
  4219. return true;
  4220. });
  4221. res.set_content(body, "text/plain");
  4222. })
  4223. .Put("/put-loopback",
  4224. [&](const Request &, Response &res,
  4225. ContentReader const &content_reader) {
  4226. std::string body;
  4227. content_reader([&](const char *data, size_t data_length) {
  4228. body.append(data, data_length);
  4229. return true;
  4230. });
  4231. res.set_content(body, "text/plain");
  4232. })
  4233. .Patch("/patch-loopback",
  4234. [&](const Request &, Response &res,
  4235. ContentReader const &content_reader) {
  4236. std::string body;
  4237. content_reader([&](const char *data, size_t data_length) {
  4238. body.append(data, data_length);
  4239. return true;
  4240. });
  4241. res.set_content(body, "text/plain");
  4242. })
  4243. .Put("/empty-no-content-type",
  4244. [&](const Request &req, Response &res) {
  4245. EXPECT_EQ(req.body, "");
  4246. EXPECT_FALSE(req.has_header("Content-Type"));
  4247. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4248. res.set_content("empty-no-content-type", "text/plain");
  4249. })
  4250. .Put("/put",
  4251. [&](const Request &req, Response &res) {
  4252. EXPECT_EQ(req.body, "PUT");
  4253. res.set_content(req.body, "text/plain");
  4254. })
  4255. .Put("/put-large",
  4256. [&](const Request &req, Response &res) {
  4257. EXPECT_EQ(req.body, LARGE_DATA);
  4258. res.set_content(req.body, "text/plain");
  4259. })
  4260. .Patch("/patch",
  4261. [&](const Request &req, Response &res) {
  4262. EXPECT_EQ(req.body, "PATCH");
  4263. res.set_content(req.body, "text/plain");
  4264. })
  4265. .Delete("/delete",
  4266. [&](const Request & /*req*/, Response &res) {
  4267. res.set_content("DELETE", "text/plain");
  4268. })
  4269. .Delete("/delete-body",
  4270. [&](const Request &req, Response &res) {
  4271. EXPECT_EQ(req.body, "content");
  4272. res.set_content(req.body, "text/plain");
  4273. })
  4274. .Options(R"(\*)",
  4275. [&](const Request & /*req*/, Response &res) {
  4276. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4277. })
  4278. .Get("/request-target",
  4279. [&](const Request &req, Response & /*res*/) {
  4280. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4281. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4282. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4283. })
  4284. .Get("/long-query-value",
  4285. [&](const Request &req, Response & /*res*/) {
  4286. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4287. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4288. })
  4289. .Get("/too-long-query-value",
  4290. [&](const Request &req, Response & /*res*/) {
  4291. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4292. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4293. })
  4294. .Get("/array-param",
  4295. [&](const Request &req, Response & /*res*/) {
  4296. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4297. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4298. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4299. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4300. })
  4301. .Get("/array-param-values",
  4302. [&](const Request &req, Response & /*res*/) {
  4303. auto values = req.get_param_values("array");
  4304. EXPECT_EQ(3u, values.size());
  4305. EXPECT_EQ("value1", values[0]);
  4306. EXPECT_EQ("value2", values[1]);
  4307. EXPECT_EQ("value3", values[2]);
  4308. auto empty = req.get_param_values("nonexistent");
  4309. EXPECT_TRUE(empty.empty());
  4310. })
  4311. .Post("/validate-no-multiple-headers",
  4312. [&](const Request &req, Response & /*res*/) {
  4313. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4314. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4315. })
  4316. .Post("/content_receiver",
  4317. [&](const Request &req, Response &res,
  4318. const ContentReader &content_reader) {
  4319. if (req.is_multipart_form_data()) {
  4320. std::vector<FormData> items;
  4321. content_reader(
  4322. [&](const FormData &file) {
  4323. items.push_back(file);
  4324. return true;
  4325. },
  4326. [&](const char *data, size_t data_length) {
  4327. items.back().content.append(data, data_length);
  4328. return true;
  4329. });
  4330. EXPECT_EQ(5u, items.size());
  4331. {
  4332. const auto &file = get_file_value(items, "text1");
  4333. EXPECT_TRUE(file.filename.empty());
  4334. EXPECT_EQ("text default", file.content);
  4335. }
  4336. {
  4337. const auto &file = get_file_value(items, "text2");
  4338. EXPECT_TRUE(file.filename.empty());
  4339. EXPECT_EQ("aωb", file.content);
  4340. }
  4341. {
  4342. const auto &file = get_file_value(items, "file1");
  4343. EXPECT_EQ("hello.txt", file.filename);
  4344. EXPECT_EQ("text/plain", file.content_type);
  4345. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4346. }
  4347. {
  4348. const auto &file = get_file_value(items, "file2");
  4349. EXPECT_EQ("world.json", file.filename);
  4350. EXPECT_EQ("application/json", file.content_type);
  4351. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4352. }
  4353. {
  4354. const auto &file = get_file_value(items, "file3");
  4355. EXPECT_TRUE(file.filename.empty());
  4356. EXPECT_EQ("application/octet-stream", file.content_type);
  4357. EXPECT_EQ(0u, file.content.size());
  4358. }
  4359. } else {
  4360. std::string body;
  4361. content_reader([&](const char *data, size_t data_length) {
  4362. EXPECT_EQ(7U, data_length);
  4363. body.append(data, data_length);
  4364. return true;
  4365. });
  4366. EXPECT_EQ(body, "content");
  4367. res.set_content(body, "text/plain");
  4368. }
  4369. })
  4370. .Put("/content_receiver",
  4371. [&](const Request & /*req*/, Response &res,
  4372. const ContentReader &content_reader) {
  4373. std::string body;
  4374. content_reader([&](const char *data, size_t data_length) {
  4375. body.append(data, data_length);
  4376. return true;
  4377. });
  4378. EXPECT_EQ(body, "content");
  4379. res.set_content(body, "text/plain");
  4380. })
  4381. .Patch("/content_receiver",
  4382. [&](const Request & /*req*/, Response &res,
  4383. const ContentReader &content_reader) {
  4384. std::string body;
  4385. content_reader([&](const char *data, size_t data_length) {
  4386. body.append(data, data_length);
  4387. return true;
  4388. });
  4389. EXPECT_EQ(body, "content");
  4390. res.set_content(body, "text/plain");
  4391. })
  4392. .Post("/query-string-and-body",
  4393. [&](const Request &req, Response & /*res*/) {
  4394. ASSERT_TRUE(req.has_param("key"));
  4395. EXPECT_EQ(req.get_param_value("key"), "value");
  4396. EXPECT_EQ(req.body, "content");
  4397. })
  4398. .Get("/last-request",
  4399. [&](const Request &req, Response & /*res*/) {
  4400. EXPECT_EQ("close", req.get_header_value("Connection"));
  4401. })
  4402. .Get(R"(/redirect/(\d+))",
  4403. [&](const Request &req, Response &res) {
  4404. auto num = std::stoi(req.matches[1]) + 1;
  4405. std::string url = "/redirect/" + std::to_string(num);
  4406. res.set_redirect(url);
  4407. })
  4408. .Post("/binary",
  4409. [&](const Request &req, Response &res) {
  4410. EXPECT_EQ(4U, req.body.size());
  4411. EXPECT_EQ("application/octet-stream",
  4412. req.get_header_value("Content-Type"));
  4413. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4414. res.set_content(req.body, "application/octet-stream");
  4415. })
  4416. .Put("/binary",
  4417. [&](const Request &req, Response &res) {
  4418. EXPECT_EQ(4U, req.body.size());
  4419. EXPECT_EQ("application/octet-stream",
  4420. req.get_header_value("Content-Type"));
  4421. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4422. res.set_content(req.body, "application/octet-stream");
  4423. })
  4424. .Patch("/binary",
  4425. [&](const Request &req, Response &res) {
  4426. EXPECT_EQ(4U, req.body.size());
  4427. EXPECT_EQ("application/octet-stream",
  4428. req.get_header_value("Content-Type"));
  4429. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4430. res.set_content(req.body, "application/octet-stream");
  4431. })
  4432. .Delete("/binary",
  4433. [&](const Request &req, Response &res) {
  4434. EXPECT_EQ(4U, req.body.size());
  4435. EXPECT_EQ("application/octet-stream",
  4436. req.get_header_value("Content-Type"));
  4437. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4438. res.set_content(req.body, "application/octet-stream");
  4439. })
  4440. .Get("/issue1772",
  4441. [&](const Request & /*req*/, Response &res) {
  4442. res.status = 401;
  4443. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4444. })
  4445. .Delete("/issue609",
  4446. [](const httplib::Request &, httplib::Response &res,
  4447. const httplib::ContentReader &) {
  4448. res.set_content("ok", "text/plain");
  4449. })
  4450. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4451. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4452. .Get("/compress",
  4453. [&](const Request & /*req*/, Response &res) {
  4454. res.set_content(
  4455. "12345678901234567890123456789012345678901234567890123456789"
  4456. "01234567890123456789012345678901234567890",
  4457. "text/plain");
  4458. })
  4459. .Get("/compress-with-charset",
  4460. [&](const Request & /*req*/, Response &res) {
  4461. res.set_content(
  4462. "12345678901234567890123456789012345678901234567890123456789"
  4463. "01234567890123456789012345678901234567890",
  4464. "application/json; charset=utf-8");
  4465. })
  4466. .Get("/nocompress",
  4467. [&](const Request & /*req*/, Response &res) {
  4468. res.set_content(
  4469. "12345678901234567890123456789012345678901234567890123456789"
  4470. "01234567890123456789012345678901234567890",
  4471. "application/octet-stream");
  4472. })
  4473. .Post("/compress-multipart",
  4474. [&](const Request &req, Response & /*res*/) {
  4475. EXPECT_EQ(2u, req.form.fields.size());
  4476. ASSERT_TRUE(!req.form.has_field("???"));
  4477. {
  4478. const auto &text = req.form.get_field("key1");
  4479. EXPECT_EQ("test", text);
  4480. }
  4481. {
  4482. const auto &text = req.form.get_field("key2");
  4483. EXPECT_EQ("--abcdefg123", text);
  4484. }
  4485. })
  4486. #endif
  4487. ;
  4488. persons_["john"] = "programmer";
  4489. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4490. svr_.wait_until_ready();
  4491. }
  4492. virtual void TearDown() {
  4493. svr_.stop();
  4494. if (!request_threads_.empty()) {
  4495. std::this_thread::sleep_for(std::chrono::seconds(1));
  4496. for (auto &t : request_threads_) {
  4497. t.join();
  4498. }
  4499. }
  4500. t_.join();
  4501. }
  4502. map<string, string> persons_;
  4503. #ifdef CPPHTTPLIB_SSL_ENABLED
  4504. SSLClient cli_;
  4505. SSLServer svr_;
  4506. #else
  4507. Client cli_;
  4508. Server svr_;
  4509. #endif
  4510. thread t_;
  4511. std::vector<thread> request_threads_;
  4512. };
  4513. TEST_F(ServerTest, GetMethod200) {
  4514. auto res = cli_.Get("/hi");
  4515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4516. EXPECT_EQ("HTTP/1.1", res->version);
  4517. EXPECT_EQ(StatusCode::OK_200, res->status);
  4518. EXPECT_EQ("OK", res->reason);
  4519. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4520. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4521. EXPECT_EQ("Hello World!", res->body);
  4522. }
  4523. TEST_F(ServerTest, GetEmptyFile) {
  4524. auto res = cli_.Get("/empty_file");
  4525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4526. EXPECT_EQ(StatusCode::OK_200, res->status);
  4527. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4528. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4529. EXPECT_EQ("", res->body);
  4530. }
  4531. TEST_F(ServerTest, GetFileContent) {
  4532. auto res = cli_.Get("/file_content");
  4533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4534. EXPECT_EQ(StatusCode::OK_200, res->status);
  4535. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4536. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4537. EXPECT_EQ("test.html", res->body);
  4538. }
  4539. TEST_F(ServerTest, GetFileContentWithRange) {
  4540. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4542. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4543. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4544. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4545. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4546. EXPECT_EQ("est", res->body);
  4547. }
  4548. TEST_F(ServerTest, GetFileContentWithContentType) {
  4549. auto res = cli_.Get("/file_content_with_content_type");
  4550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4551. EXPECT_EQ(StatusCode::OK_200, res->status);
  4552. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4553. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4554. EXPECT_EQ("file\n", res->body);
  4555. }
  4556. TEST_F(ServerTest, GetInvalidFileContent) {
  4557. auto res = cli_.Get("/invalid_file_content");
  4558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4560. }
  4561. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4562. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4564. EXPECT_EQ("HTTP/1.1", res->version);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4567. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4568. EXPECT_EQ("Hello World!", res->body);
  4569. }
  4570. TEST_F(ServerTest, GetMethod302) {
  4571. auto res = cli_.Get("/");
  4572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4573. EXPECT_EQ(StatusCode::Found_302, res->status);
  4574. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4575. }
  4576. TEST_F(ServerTest, GetMethod302Redirect) {
  4577. cli_.set_follow_location(true);
  4578. auto res = cli_.Get("/");
  4579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4580. EXPECT_EQ(StatusCode::OK_200, res->status);
  4581. EXPECT_EQ("Hello World!", res->body);
  4582. EXPECT_EQ("/hi", res->location);
  4583. }
  4584. TEST_F(ServerTest, GetMethod404) {
  4585. auto res = cli_.Get("/invalid");
  4586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4588. }
  4589. TEST_F(ServerTest, HeadMethod200) {
  4590. auto res = cli_.Head("/hi");
  4591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4592. EXPECT_EQ(StatusCode::OK_200, res->status);
  4593. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4594. EXPECT_TRUE(res->body.empty());
  4595. }
  4596. TEST_F(ServerTest, HeadMethod200Static) {
  4597. auto res = cli_.Head("/mount/dir/index.html");
  4598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4599. EXPECT_EQ(StatusCode::OK_200, res->status);
  4600. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4601. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4602. EXPECT_TRUE(res->body.empty());
  4603. }
  4604. TEST_F(ServerTest, HeadMethod404) {
  4605. auto res = cli_.Head("/invalid");
  4606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4607. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4608. EXPECT_TRUE(res->body.empty());
  4609. }
  4610. TEST_F(ServerTest, GetMethodPersonJohn) {
  4611. auto res = cli_.Get("/person/john");
  4612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4615. EXPECT_EQ("programmer", res->body);
  4616. }
  4617. TEST_F(ServerTest, PostMethod1) {
  4618. auto res = cli_.Get("/person/john1");
  4619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4620. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4621. res = cli_.Post("/person", "name=john1&note=coder",
  4622. "application/x-www-form-urlencoded");
  4623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4624. ASSERT_EQ(StatusCode::OK_200, res->status);
  4625. res = cli_.Get("/person/john1");
  4626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4627. ASSERT_EQ(StatusCode::OK_200, res->status);
  4628. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4629. ASSERT_EQ("coder", res->body);
  4630. }
  4631. TEST_F(ServerTest, PostMethod2) {
  4632. auto res = cli_.Get("/person/john2");
  4633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4634. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4635. Params params;
  4636. params.emplace("name", "john2");
  4637. params.emplace("note", "coder");
  4638. res = cli_.Post("/person", params);
  4639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4640. ASSERT_EQ(StatusCode::OK_200, res->status);
  4641. res = cli_.Get("/person/john2");
  4642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4643. ASSERT_EQ(StatusCode::OK_200, res->status);
  4644. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4645. ASSERT_EQ("coder", res->body);
  4646. }
  4647. TEST_F(ServerTest, PutMethod3) {
  4648. auto res = cli_.Get("/person/john3");
  4649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4650. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4651. Params params;
  4652. params.emplace("name", "john3");
  4653. params.emplace("note", "coder");
  4654. res = cli_.Put("/person", params);
  4655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4656. ASSERT_EQ(StatusCode::OK_200, res->status);
  4657. res = cli_.Get("/person/john3");
  4658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4659. ASSERT_EQ(StatusCode::OK_200, res->status);
  4660. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4661. ASSERT_EQ("coder", res->body);
  4662. }
  4663. TEST_F(ServerTest, DeleteMethod1) {
  4664. auto res = cli_.Get("/person/john4");
  4665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4666. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4667. Params params;
  4668. params.emplace("name", "john4");
  4669. params.emplace("note", "coder");
  4670. res = cli_.Post("/person", params);
  4671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4672. ASSERT_EQ(StatusCode::OK_200, res->status);
  4673. res = cli_.Get("/person/john4");
  4674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4675. ASSERT_EQ(StatusCode::OK_200, res->status);
  4676. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4677. ASSERT_EQ("coder", res->body);
  4678. Params delete_params;
  4679. delete_params.emplace("name", "john4");
  4680. res = cli_.Delete("/person", delete_params);
  4681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4682. ASSERT_EQ(StatusCode::OK_200, res->status);
  4683. ASSERT_EQ("DELETED", res->body);
  4684. res = cli_.Get("/person/john4");
  4685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4686. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4687. }
  4688. TEST_F(ServerTest, DeleteMethod2) {
  4689. auto res = cli_.Get("/person/john5");
  4690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4691. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4692. Params params;
  4693. params.emplace("name", "john5");
  4694. params.emplace("note", "developer");
  4695. res = cli_.Post("/person", params);
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. ASSERT_EQ(StatusCode::OK_200, res->status);
  4698. res = cli_.Get("/person/john5");
  4699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4700. ASSERT_EQ(StatusCode::OK_200, res->status);
  4701. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4702. ASSERT_EQ("developer", res->body);
  4703. Params delete_params;
  4704. delete_params.emplace("name", "john5");
  4705. Headers headers;
  4706. headers.emplace("Custom-Header", "test-value");
  4707. res = cli_.Delete("/person", headers, delete_params);
  4708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4709. ASSERT_EQ(StatusCode::OK_200, res->status);
  4710. ASSERT_EQ("DELETED", res->body);
  4711. res = cli_.Get("/person/john5");
  4712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4713. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4714. }
  4715. TEST_F(ServerTest, DeleteMethod3) {
  4716. auto res = cli_.Get("/person/john6");
  4717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4718. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4719. Params params;
  4720. params.emplace("name", "john6");
  4721. params.emplace("note", "tester");
  4722. res = cli_.Post("/person", params);
  4723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4724. ASSERT_EQ(StatusCode::OK_200, res->status);
  4725. res = cli_.Get("/person/john6");
  4726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4727. ASSERT_EQ(StatusCode::OK_200, res->status);
  4728. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4729. ASSERT_EQ("tester", res->body);
  4730. Params delete_params;
  4731. delete_params.emplace("name", "john6");
  4732. Headers headers;
  4733. headers.emplace("Custom-Header", "test-value");
  4734. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4736. ASSERT_EQ(StatusCode::OK_200, res->status);
  4737. ASSERT_EQ("DELETED", res->body);
  4738. res = cli_.Get("/person/john6");
  4739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4740. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4741. }
  4742. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4743. Params params;
  4744. params.emplace("json", JSON_DATA);
  4745. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4747. ASSERT_EQ(StatusCode::OK_200, res->status);
  4748. ASSERT_EQ(JSON_DATA, res->body);
  4749. }
  4750. TEST_F(ServerTest, PostEmptyContent) {
  4751. auto res = cli_.Post("/empty", "", "text/plain");
  4752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4753. ASSERT_EQ(StatusCode::OK_200, res->status);
  4754. ASSERT_EQ("empty", res->body);
  4755. }
  4756. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4757. auto res = cli_.Post("/empty-no-content-type");
  4758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4759. ASSERT_EQ(StatusCode::OK_200, res->status);
  4760. ASSERT_EQ("empty-no-content-type", res->body);
  4761. }
  4762. TEST_F(ServerTest, PostPathOnly) {
  4763. auto res = cli_.Post("/path-only");
  4764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4765. ASSERT_EQ(StatusCode::OK_200, res->status);
  4766. ASSERT_EQ("path-only", res->body);
  4767. }
  4768. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4769. auto res = cli_.Post("/path-headers-only",
  4770. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4772. ASSERT_EQ(StatusCode::OK_200, res->status);
  4773. ASSERT_EQ("path-headers-only", res->body);
  4774. }
  4775. TEST_F(ServerTest, PostLarge) {
  4776. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4778. ASSERT_EQ(StatusCode::OK_200, res->status);
  4779. EXPECT_EQ(LARGE_DATA, res->body);
  4780. }
  4781. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4782. auto res = cli_.Put("/empty-no-content-type");
  4783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4784. ASSERT_EQ(StatusCode::OK_200, res->status);
  4785. ASSERT_EQ("empty-no-content-type", res->body);
  4786. }
  4787. TEST_F(ServerTest, GetMethodDir) {
  4788. auto res = cli_.Get("/dir/");
  4789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4792. auto body = R"(<html>
  4793. <head>
  4794. </head>
  4795. <body>
  4796. <a href="/dir/test.html">Test</a>
  4797. <a href="/hi">hi</a>
  4798. </body>
  4799. </html>
  4800. )";
  4801. EXPECT_EQ(body, res->body);
  4802. }
  4803. TEST_F(ServerTest, GetMethodDirTest) {
  4804. auto res = cli_.Get("/dir/test.html");
  4805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4806. EXPECT_EQ(StatusCode::OK_200, res->status);
  4807. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4808. EXPECT_EQ("test.html", res->body);
  4809. }
  4810. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4811. auto res = cli_.Get("/dir/../dir/test.html");
  4812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4813. EXPECT_EQ(StatusCode::OK_200, res->status);
  4814. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4815. EXPECT_EQ("test.html", res->body);
  4816. }
  4817. TEST_F(ServerTest, GetMethodInvalidPath) {
  4818. auto res = cli_.Get("/dir/../test.html");
  4819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4821. }
  4822. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4823. auto res = cli_.Get("/../www/dir/test.html");
  4824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4825. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4826. }
  4827. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4828. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4830. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4831. }
  4832. TEST_F(ServerTest, GetMethodDirMountTest) {
  4833. auto res = cli_.Get("/mount/dir/test.html");
  4834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4835. EXPECT_EQ(StatusCode::OK_200, res->status);
  4836. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4837. EXPECT_EQ("test.html", res->body);
  4838. }
  4839. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4840. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4842. EXPECT_EQ(StatusCode::OK_200, res->status);
  4843. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4844. EXPECT_EQ("test.html", res->body);
  4845. }
  4846. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4847. auto res = cli_.Get("/mount/dir/../test.html");
  4848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4850. }
  4851. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4852. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4855. }
  4856. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4857. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4860. }
  4861. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4862. auto res = cli_.Get("/mount/dir/../../www2/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, GetMethodOutOfBaseDirMountWithBackslash) {
  4867. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4869. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4870. }
  4871. TEST_F(ServerTest, PostMethod303) {
  4872. auto res = cli_.Post("/1", "body", "text/plain");
  4873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4874. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4875. EXPECT_EQ("/2", res->get_header_value("Location"));
  4876. }
  4877. TEST_F(ServerTest, PostMethod303Redirect) {
  4878. cli_.set_follow_location(true);
  4879. auto res = cli_.Post("/1", "body", "text/plain");
  4880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. EXPECT_EQ("redirected.", res->body);
  4883. EXPECT_EQ("/2", res->location);
  4884. }
  4885. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4886. auto res = cli_.Get("/dir/test.abcde");
  4887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4888. EXPECT_EQ(StatusCode::OK_200, res->status);
  4889. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4890. EXPECT_EQ("abcde", res->body);
  4891. }
  4892. TEST_F(ServerTest, StaticFileRange) {
  4893. auto res =
  4894. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4896. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4897. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4898. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4899. EXPECT_EQ(true, res->has_header("Content-Range"));
  4900. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4901. EXPECT_EQ(std::string("cd"), res->body);
  4902. }
  4903. TEST_F(ServerTest, StaticFileRanges) {
  4904. auto res = cli_.Get("/dir/test.abcde",
  4905. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4907. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4908. EXPECT_TRUE(
  4909. res->get_header_value("Content-Type")
  4910. .find(
  4911. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4912. 0);
  4913. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4914. }
  4915. TEST_F(ServerTest, StaticFileRangeHead) {
  4916. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4919. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4920. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4921. EXPECT_EQ(true, res->has_header("Content-Range"));
  4922. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4923. }
  4924. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4925. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4927. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4929. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4930. EXPECT_EQ(true, res->has_header("Content-Range"));
  4931. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4932. res->get_header_value("Content-Range"));
  4933. EXPECT_EQ("LAST\n", res->body);
  4934. }
  4935. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4936. auto res =
  4937. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4939. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4940. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4941. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4942. EXPECT_EQ(true, res->has_header("Content-Range"));
  4943. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4944. }
  4945. TEST_F(ServerTest, StaticFileBigFile) {
  4946. auto res = cli_.Get("/dir/1MB.txt");
  4947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4948. EXPECT_EQ(StatusCode::OK_200, res->status);
  4949. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4950. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4951. }
  4952. TEST_F(ServerTest, InvalidBaseDirMount) {
  4953. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4954. }
  4955. TEST_F(ServerTest, Binary) {
  4956. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4957. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4958. "application/octet-stream");
  4959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4960. ASSERT_EQ(StatusCode::OK_200, res->status);
  4961. ASSERT_EQ(4U, res->body.size());
  4962. res = cli_.Put("/binary", binary.data(), binary.size(),
  4963. "application/octet-stream");
  4964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4965. ASSERT_EQ(StatusCode::OK_200, res->status);
  4966. ASSERT_EQ(4U, res->body.size());
  4967. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4968. "application/octet-stream");
  4969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4970. ASSERT_EQ(StatusCode::OK_200, res->status);
  4971. ASSERT_EQ(4U, res->body.size());
  4972. res = cli_.Delete("/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. }
  4978. TEST_F(ServerTest, BinaryString) {
  4979. auto binary = std::string("\x00\x01\x02\x03", 4);
  4980. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4982. ASSERT_EQ(StatusCode::OK_200, res->status);
  4983. ASSERT_EQ(4U, res->body.size());
  4984. res = cli_.Put("/binary", binary, "application/octet-stream");
  4985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4986. ASSERT_EQ(StatusCode::OK_200, res->status);
  4987. ASSERT_EQ(4U, res->body.size());
  4988. res = cli_.Patch("/binary", binary, "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. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4994. ASSERT_EQ(StatusCode::OK_200, res->status);
  4995. ASSERT_EQ(4U, res->body.size());
  4996. }
  4997. TEST_F(ServerTest, EmptyRequest) {
  4998. auto res = cli_.Get("");
  4999. ASSERT_TRUE(!res);
  5000. EXPECT_EQ(Error::Connection, res.error());
  5001. }
  5002. TEST_F(ServerTest, LongRequest) {
  5003. std::string request;
  5004. for (size_t i = 0; i < 545; i++) {
  5005. request += "/TooLongRequest";
  5006. }
  5007. request += "OK";
  5008. auto res = cli_.Get(request.c_str());
  5009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5010. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5011. }
  5012. TEST_F(ServerTest, TooLongRequest) {
  5013. std::string request;
  5014. for (size_t i = 0; i < 546; i++) {
  5015. request += "/TooLongRequest";
  5016. }
  5017. request += "_NG";
  5018. auto start = std::chrono::high_resolution_clock::now();
  5019. cli_.set_keep_alive(true);
  5020. auto res = cli_.Get(request.c_str());
  5021. auto end = std::chrono::high_resolution_clock::now();
  5022. auto elapsed =
  5023. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5024. .count();
  5025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5026. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5027. EXPECT_LE(elapsed, 1000);
  5028. EXPECT_EQ("close", res->get_header_value("Connection"));
  5029. EXPECT_FALSE(cli_.is_socket_open());
  5030. }
  5031. TEST_F(ServerTest, AlmostTooLongRequest) {
  5032. // test for #2046 - URI length check shouldn't include other content on req
  5033. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5034. // leading /, space, HTTP/1.1)
  5035. std::string request =
  5036. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5037. auto res = cli_.Get(request.c_str());
  5038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5039. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5040. }
  5041. TEST_F(ServerTest, LongHeader) {
  5042. Request req;
  5043. req.method = "GET";
  5044. req.path = "/hi";
  5045. std::string host_and_port;
  5046. host_and_port += HOST;
  5047. host_and_port += ":";
  5048. host_and_port += std::to_string(PORT);
  5049. req.headers.emplace("Host", host_and_port.c_str());
  5050. req.headers.emplace("Accept", "*/*");
  5051. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5052. req.headers.emplace(
  5053. "Header-Name",
  5054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5063. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5064. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5065. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5066. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5067. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5068. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5072. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5073. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5082. "@@@@@@@@@@@@@@@@");
  5083. auto res = std::make_shared<Response>();
  5084. auto error = Error::Success;
  5085. auto ret = cli_.send(req, *res, error);
  5086. ASSERT_TRUE(ret);
  5087. EXPECT_EQ(StatusCode::OK_200, res->status);
  5088. }
  5089. TEST_F(ServerTest, LongQueryValue) {
  5090. auto start = std::chrono::high_resolution_clock::now();
  5091. cli_.set_keep_alive(true);
  5092. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5093. auto end = std::chrono::high_resolution_clock::now();
  5094. auto elapsed =
  5095. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5096. .count();
  5097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5098. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5099. EXPECT_LE(elapsed, 1000);
  5100. EXPECT_EQ("close", res->get_header_value("Connection"));
  5101. EXPECT_FALSE(cli_.is_socket_open());
  5102. }
  5103. TEST_F(ServerTest, TooLongQueryValue) {
  5104. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5105. ASSERT_FALSE(res);
  5106. EXPECT_EQ(Error::Read, res.error());
  5107. }
  5108. TEST_F(ServerTest, TooLongHeader) {
  5109. Request req;
  5110. req.method = "GET";
  5111. req.path = "/hi";
  5112. std::string host_and_port;
  5113. host_and_port += HOST;
  5114. host_and_port += ":";
  5115. host_and_port += std::to_string(PORT);
  5116. req.headers.emplace("Host", host_and_port.c_str());
  5117. req.headers.emplace("Accept", "*/*");
  5118. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5119. req.headers.emplace(
  5120. "Header-Name",
  5121. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5122. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5123. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5124. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5125. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5126. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5127. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5128. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5129. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5130. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5131. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5132. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5149. "@@@@@@@@@@@@@@@@@");
  5150. auto res = std::make_shared<Response>();
  5151. auto error = Error::Success;
  5152. auto ret = cli_.send(req, *res, error);
  5153. ASSERT_TRUE(ret);
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. }
  5156. TEST_F(ServerTest, HeaderCountAtLimit) {
  5157. // Test with headers just under the 100 limit
  5158. httplib::Headers headers;
  5159. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5160. // This should keep us just under the 100 header limit
  5161. for (int i = 0; i < 95; i++) {
  5162. std::string name = "X-Test-Header-" + std::to_string(i);
  5163. std::string value = "value" + std::to_string(i);
  5164. headers.emplace(name, value);
  5165. }
  5166. // This should work fine as we're under the limit
  5167. auto res = cli_.Get("/hi", headers);
  5168. EXPECT_TRUE(res);
  5169. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5170. }
  5171. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5172. // Test with many headers to exceed the 100 limit
  5173. httplib::Headers headers;
  5174. // Add 150 headers to definitely exceed the 100 limit
  5175. for (int i = 0; i < 150; i++) {
  5176. std::string name = "X-Test-Header-" + std::to_string(i);
  5177. std::string value = "value" + std::to_string(i);
  5178. headers.emplace(name, value);
  5179. }
  5180. // This should fail due to exceeding header count limit
  5181. cli_.set_keep_alive(true);
  5182. auto res = cli_.Get("/hi", headers);
  5183. // The server should respond with 400 Bad Request
  5184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5185. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5186. EXPECT_EQ("close", res->get_header_value("Connection"));
  5187. EXPECT_FALSE(cli_.is_socket_open());
  5188. }
  5189. TEST_F(ServerTest, PercentEncoding) {
  5190. auto res = cli_.Get("/e%6edwith%");
  5191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5192. EXPECT_EQ(StatusCode::OK_200, res->status);
  5193. }
  5194. TEST_F(ServerTest, PercentEncodingUnicode) {
  5195. auto res = cli_.Get("/e%u006edwith%");
  5196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5197. EXPECT_EQ(StatusCode::OK_200, res->status);
  5198. }
  5199. TEST_F(ServerTest, InvalidPercentEncoding) {
  5200. auto res = cli_.Get("/%endwith%");
  5201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5202. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5203. }
  5204. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5205. auto res = cli_.Get("/%uendwith%");
  5206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5207. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5208. }
  5209. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5210. auto res = cli_.Get("/hello?aaa=bbb%");
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5213. }
  5214. TEST_F(ServerTest, PlusSignEncoding) {
  5215. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. EXPECT_EQ(StatusCode::OK_200, res->status);
  5218. EXPECT_EQ("a +b", res->body);
  5219. }
  5220. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5221. // This test simulates a potential DoS attack using many headers
  5222. // to verify our security fix prevents memory exhaustion
  5223. httplib::Headers attack_headers;
  5224. // Attempt to add many headers like an attacker would (200 headers to far
  5225. // exceed limit)
  5226. for (int i = 0; i < 200; i++) {
  5227. std::string name = "X-Attack-Header-" + std::to_string(i);
  5228. std::string value = "attack_payload_" + std::to_string(i);
  5229. attack_headers.emplace(name, value);
  5230. }
  5231. // Try to POST with excessive headers
  5232. cli_.set_keep_alive(true);
  5233. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5234. // Should either fail or return 400 Bad Request due to security limit
  5235. if (res) {
  5236. // If we get a response, it should be 400 Bad Request
  5237. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5238. EXPECT_EQ("close", res->get_header_value("Connection"));
  5239. }
  5240. EXPECT_FALSE(cli_.is_socket_open());
  5241. }
  5242. TEST_F(ServerTest, MultipartFormData) {
  5243. UploadFormDataItems items = {
  5244. {"text1", "text default", "", ""},
  5245. {"text2", "aωb", "", ""},
  5246. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5247. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5248. {"file3", "", "", "application/octet-stream"},
  5249. {"file4", "", "", " application/json tmp-string "}};
  5250. auto res = cli_.Post("/multipart", items);
  5251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. }
  5254. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5255. UploadFormDataItems items = {
  5256. {"text", "default text", "", ""},
  5257. {"multi_text1", "aaaaa", "", ""},
  5258. {"multi_text1", "bbbbb", "", ""},
  5259. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5260. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5261. "application/json"},
  5262. };
  5263. auto res = cli_.Post("/multipart/multi_file_values", items);
  5264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5265. EXPECT_EQ(StatusCode::OK_200, res->status);
  5266. }
  5267. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5268. auto res = cli_.Get("/hi");
  5269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5270. EXPECT_EQ(StatusCode::OK_200, res->status);
  5271. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5272. EXPECT_EQ("Hello World!", res->body);
  5273. }
  5274. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5275. Request req;
  5276. req.method = "POST";
  5277. req.path = "/chunked";
  5278. std::string host_and_port;
  5279. host_and_port += HOST;
  5280. host_and_port += ":";
  5281. host_and_port += std::to_string(PORT);
  5282. req.headers.emplace("Host", host_and_port.c_str());
  5283. req.headers.emplace("Accept", "*/*");
  5284. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5285. req.headers.emplace("Content-Type", "text/plain");
  5286. req.headers.emplace("Content-Length", "0");
  5287. req.headers.emplace(
  5288. "Transfer-Encoding",
  5289. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5290. // Client does not chunk, so make a chunked body manually.
  5291. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5292. auto res = std::make_shared<Response>();
  5293. auto error = Error::Success;
  5294. auto ret = cli_.send(req, *res, error);
  5295. ASSERT_TRUE(ret);
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. }
  5298. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5299. // rather than treat them as valid lengths.
  5300. template <typename ClientT>
  5301. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5302. Request req;
  5303. req.method = "POST";
  5304. req.path = "/chunked";
  5305. std::string host_and_port;
  5306. host_and_port += HOST;
  5307. host_and_port += ":";
  5308. host_and_port += std::to_string(PORT);
  5309. req.headers.emplace("Host", host_and_port.c_str());
  5310. req.headers.emplace("Content-Length", "0");
  5311. req.headers.emplace("Transfer-Encoding", "chunked");
  5312. req.body = body;
  5313. auto res = std::make_shared<Response>();
  5314. auto error = Error::Success;
  5315. ASSERT_TRUE(cli.send(req, *res, error));
  5316. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5317. }
  5318. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5319. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5320. }
  5321. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5322. expect_chunked_body_rejected(
  5323. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5324. }
  5325. TEST_F(ServerTest, GetStreamed2) {
  5326. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5329. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5330. EXPECT_EQ(true, res->has_header("Content-Range"));
  5331. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5332. EXPECT_EQ(std::string("ab"), res->body);
  5333. }
  5334. TEST_F(ServerTest, GetStreamed) {
  5335. auto res = cli_.Get("/streamed");
  5336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5337. EXPECT_EQ(StatusCode::OK_200, res->status);
  5338. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5339. EXPECT_EQ(std::string("aaabbb"), res->body);
  5340. }
  5341. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5342. auto res = cli_.Get("/streamed-without-length",
  5343. Headers{make_range_header({{0, -1}})});
  5344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5345. EXPECT_EQ(StatusCode::OK_200, res->status);
  5346. EXPECT_EQ(false, res->has_header("Content-Length"));
  5347. EXPECT_EQ(false, res->has_header("Content-Range"));
  5348. EXPECT_EQ(std::string("abcdefg"), res->body);
  5349. }
  5350. TEST_F(ServerTest, GetStreamedWithRange1) {
  5351. auto res =
  5352. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5354. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5355. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5356. EXPECT_EQ(true, res->has_header("Content-Range"));
  5357. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5358. EXPECT_EQ(std::string("def"), res->body);
  5359. }
  5360. TEST_F(ServerTest, GetStreamedWithRange2) {
  5361. auto res =
  5362. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5364. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5365. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5366. EXPECT_EQ(true, res->has_header("Content-Range"));
  5367. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5368. EXPECT_EQ(std::string("bcdefg"), res->body);
  5369. }
  5370. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5371. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5373. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5374. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5375. EXPECT_EQ(true, res->has_header("Content-Range"));
  5376. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5377. EXPECT_EQ(std::string("efg"), res->body);
  5378. }
  5379. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5380. auto res =
  5381. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5383. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5384. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5385. EXPECT_EQ(false, res->has_header("Content-Range"));
  5386. EXPECT_EQ(0U, res->body.size());
  5387. }
  5388. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5389. // Only a 206 is served as a partial representation. Under any other status
  5390. // `apply_ranges()` reported the full content length, so the body must match
  5391. // that header, and the content provider must never be asked for an offset
  5392. // outside the representation.
  5393. auto check = [&](int status, const char *range) {
  5394. auto path =
  5395. std::string("/streamed-with-range?status=") + std::to_string(status);
  5396. auto ctx = path + " Range: " + range;
  5397. auto res = cli_.Get(path, Headers{{"Range", range}});
  5398. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5399. EXPECT_EQ(status, res->status) << ctx;
  5400. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5402. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5403. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5404. };
  5405. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5406. check(403, "bytes=3-5");
  5407. // The offset is far past the representation.
  5408. check(403, "bytes=100000-100200");
  5409. // `first_pos` is still -1 here, and the bounds asserts in
  5410. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5411. check(403, "bytes=-3");
  5412. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5413. // multipart branch would have written one that is empty.
  5414. check(403, "bytes=1-2, 4-5");
  5415. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5416. // covers the whole representation.
  5417. check(200, "bytes=3-5");
  5418. check(200, "bytes=1-2, 4-5");
  5419. }
  5420. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5421. auto res =
  5422. cli_.Get("/streamed-with-range",
  5423. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5424. "92233720368547758079223372036854775807"}});
  5425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5426. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5427. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5428. EXPECT_EQ(false, res->has_header("Content-Range"));
  5429. EXPECT_EQ(0U, res->body.size());
  5430. }
  5431. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5432. auto res = cli_.Get(
  5433. "/with-range",
  5434. Headers{{"Range",
  5435. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5436. {"Accept-Encoding", ""}});
  5437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5438. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5439. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5440. EXPECT_EQ(true, res->has_header("Content-Range"));
  5441. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5442. EXPECT_EQ(std::string("abcdefg"), res->body);
  5443. }
  5444. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5445. auto res = cli_.Get("/with-range", Headers{
  5446. {"Range", "bytes=0-"},
  5447. {"Accept-Encoding", ""},
  5448. });
  5449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5450. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5451. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5452. EXPECT_EQ(true, res->has_header("Content-Range"));
  5453. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5454. EXPECT_EQ(std::string("abcdefg"), res->body);
  5455. }
  5456. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5457. auto res = cli_.Get("/streamed-with-range",
  5458. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5460. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5461. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5462. EXPECT_EQ(false, res->has_header("Content-Range"));
  5463. EXPECT_EQ(267U, res->body.size());
  5464. // Check that both range contents are present
  5465. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5466. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5467. // Check that Content-Range headers are present for both ranges
  5468. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5469. std::string::npos);
  5470. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5471. std::string::npos);
  5472. }
  5473. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5474. Ranges ranges;
  5475. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5476. ranges.emplace_back(0, -1);
  5477. }
  5478. auto res = cli_.Get("/streamed-with-range?error",
  5479. Headers{{make_range_header(ranges)}});
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5482. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5483. EXPECT_EQ(false, res->has_header("Content-Range"));
  5484. EXPECT_EQ(0U, res->body.size());
  5485. }
  5486. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5487. auto res = cli_.Get("/streamed-with-range",
  5488. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5490. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5491. EXPECT_EQ(5U, res->body.size());
  5492. // Check that overlapping ranges are coalesced into a single range
  5493. EXPECT_EQ("bcdef", res->body);
  5494. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5495. // Should be single range, not multipart
  5496. EXPECT_TRUE(res->has_header("Content-Range"));
  5497. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5498. }
  5499. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5500. auto res = cli_.Get("/streamed-with-range",
  5501. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5503. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5504. EXPECT_EQ(268U, res->body.size());
  5505. // Check that both range contents are present
  5506. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5507. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5508. // Check that Content-Range headers are present for both ranges
  5509. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5510. std::string::npos);
  5511. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5512. std::string::npos);
  5513. }
  5514. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5515. auto res = cli_.Get("/streamed-with-range",
  5516. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5519. EXPECT_EQ(269U, res->body.size());
  5520. // Check that both duplicate range contents are present
  5521. size_t first_abc = res->body.find("abc\r\n");
  5522. EXPECT_TRUE(first_abc != std::string::npos);
  5523. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5524. EXPECT_TRUE(second_abc != std::string::npos);
  5525. // Check that Content-Range headers are present for both ranges
  5526. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5527. EXPECT_TRUE(first_range != std::string::npos);
  5528. size_t second_range =
  5529. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5530. EXPECT_TRUE(second_range != std::string::npos);
  5531. }
  5532. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5533. auto res =
  5534. cli_.Get("/streamed-with-range?error",
  5535. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5537. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5538. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5539. EXPECT_EQ(false, res->has_header("Content-Range"));
  5540. EXPECT_EQ(0U, res->body.size());
  5541. }
  5542. TEST_F(ServerTest, GetStreamedEndless) {
  5543. uint64_t offset = 0;
  5544. auto res = cli_.Get("/streamed-cancel",
  5545. [&](const char * /*data*/, uint64_t data_length) {
  5546. if (offset < 100) {
  5547. offset += data_length;
  5548. return true;
  5549. }
  5550. return false;
  5551. });
  5552. ASSERT_TRUE(!res);
  5553. EXPECT_EQ(Error::Canceled, res.error());
  5554. }
  5555. TEST_F(ServerTest, ClientStop) {
  5556. std::atomic_size_t count{4};
  5557. std::vector<std::thread> threads;
  5558. for (auto i = count.load(); i != 0; --i) {
  5559. threads.emplace_back([&]() {
  5560. auto res = cli_.Get("/streamed-cancel",
  5561. [&](const char *, uint64_t) { return true; });
  5562. --count;
  5563. ASSERT_TRUE(!res);
  5564. EXPECT_TRUE(res.error() == Error::Canceled ||
  5565. res.error() == Error::Read || res.error() == Error::Write);
  5566. });
  5567. }
  5568. std::this_thread::sleep_for(std::chrono::seconds(2));
  5569. while (count != 0) {
  5570. cli_.stop();
  5571. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5572. }
  5573. for (auto &t : threads) {
  5574. t.join();
  5575. }
  5576. }
  5577. TEST_F(ServerTest, GetWithRange1) {
  5578. auto res = cli_.Get("/with-range", Headers{
  5579. make_range_header({{3, 5}}),
  5580. {"Accept-Encoding", ""},
  5581. });
  5582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5583. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5584. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5585. EXPECT_EQ(true, res->has_header("Content-Range"));
  5586. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5587. EXPECT_EQ(std::string("def"), res->body);
  5588. }
  5589. TEST_F(ServerTest, GetWithRange2) {
  5590. auto res = cli_.Get("/with-range", Headers{
  5591. make_range_header({{1, -1}}),
  5592. {"Accept-Encoding", ""},
  5593. });
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5596. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5597. EXPECT_EQ(true, res->has_header("Content-Range"));
  5598. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5599. EXPECT_EQ(std::string("bcdefg"), res->body);
  5600. }
  5601. TEST_F(ServerTest, GetWithRange3) {
  5602. auto res = cli_.Get("/with-range", Headers{
  5603. make_range_header({{0, 0}}),
  5604. {"Accept-Encoding", ""},
  5605. });
  5606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5607. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5608. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5609. EXPECT_EQ(true, res->has_header("Content-Range"));
  5610. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5611. EXPECT_EQ(std::string("a"), res->body);
  5612. }
  5613. TEST_F(ServerTest, GetWithRange4) {
  5614. auto res = cli_.Get("/with-range", Headers{
  5615. make_range_header({{-1, 2}}),
  5616. {"Accept-Encoding", ""},
  5617. });
  5618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5619. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5620. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5621. EXPECT_EQ(true, res->has_header("Content-Range"));
  5622. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5623. EXPECT_EQ(std::string("fg"), res->body);
  5624. }
  5625. TEST_F(ServerTest, GetWithRange5) {
  5626. auto res = cli_.Get("/with-range", Headers{
  5627. make_range_header({{0, 5}}),
  5628. {"Accept-Encoding", ""},
  5629. });
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5632. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5633. EXPECT_EQ(true, res->has_header("Content-Range"));
  5634. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5635. EXPECT_EQ(std::string("abcdef"), res->body);
  5636. }
  5637. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5638. auto res =
  5639. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5641. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5642. }
  5643. TEST_F(ServerTest, GetWithRangeMultipart) {
  5644. auto res =
  5645. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5647. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5648. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5649. EXPECT_EQ(false, res->has_header("Content-Range"));
  5650. EXPECT_EQ(267U, res->body.size());
  5651. }
  5652. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5653. auto res = cli_.Get("/with-range",
  5654. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5656. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5657. }
  5658. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5659. auto res = cli_.Get("/with-range-customized-response",
  5660. Headers{{make_range_header({{1, 2}})}});
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5663. EXPECT_EQ(true, res->has_header("Content-Length"));
  5664. EXPECT_EQ(false, res->has_header("Content-Range"));
  5665. EXPECT_EQ(JSON_DATA, res->body);
  5666. }
  5667. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5668. auto res = cli_.Get("/with-range-customized-response",
  5669. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5672. EXPECT_EQ(true, res->has_header("Content-Length"));
  5673. EXPECT_EQ(false, res->has_header("Content-Range"));
  5674. EXPECT_EQ(JSON_DATA, res->body);
  5675. }
  5676. TEST_F(ServerTest, Issue1772) {
  5677. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5679. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5680. }
  5681. TEST_F(ServerTest, Issue609) {
  5682. auto res = cli_.Delete("/issue609");
  5683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5684. EXPECT_EQ(StatusCode::OK_200, res->status);
  5685. EXPECT_EQ(std::string("ok"), res->body);
  5686. }
  5687. TEST_F(ServerTest, GetStreamedChunked) {
  5688. auto res = cli_.Get("/streamed-chunked");
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. EXPECT_EQ(StatusCode::OK_200, res->status);
  5691. EXPECT_EQ(std::string("123456789"), res->body);
  5692. }
  5693. TEST_F(ServerTest, GetStreamedChunked2) {
  5694. auto res = cli_.Get("/streamed-chunked2");
  5695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5696. EXPECT_EQ(StatusCode::OK_200, res->status);
  5697. EXPECT_EQ(std::string("123456789"), res->body);
  5698. }
  5699. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5700. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. EXPECT_EQ(StatusCode::OK_200, res->status);
  5703. EXPECT_EQ(std::string("123456789"), res->body);
  5704. EXPECT_TRUE(res->has_header("Trailer"));
  5705. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5706. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5707. // Trailers are now stored separately from headers (security fix)
  5708. EXPECT_EQ(2U, res->trailers.size());
  5709. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5710. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5711. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5712. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5713. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5714. // Verify trailers are NOT in headers (security verification)
  5715. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5716. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5717. }
  5718. TEST_F(ServerTest, LargeChunkedPost) {
  5719. Request req;
  5720. req.method = "POST";
  5721. req.path = "/large-chunked";
  5722. std::string host_and_port;
  5723. host_and_port += HOST;
  5724. host_and_port += ":";
  5725. host_and_port += std::to_string(PORT);
  5726. req.headers.emplace("Host", host_and_port.c_str());
  5727. req.headers.emplace("Accept", "*/*");
  5728. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5729. req.headers.emplace("Content-Type", "text/plain");
  5730. req.headers.emplace("Content-Length", "0");
  5731. req.headers.emplace("Transfer-Encoding", "chunked");
  5732. std::string long_string(30 * 1024u, 'a');
  5733. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5734. // Attempt to make a large enough post to exceed OS buffers, to test that
  5735. // the server handles short reads if the full chunk data isn't available.
  5736. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5737. auto res = std::make_shared<Response>();
  5738. auto error = Error::Success;
  5739. auto ret = cli_.send(req, *res, error);
  5740. ASSERT_TRUE(ret);
  5741. EXPECT_EQ(StatusCode::OK_200, res->status);
  5742. }
  5743. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5744. auto res = cli_.Get("/remote_addr");
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. EXPECT_EQ(StatusCode::OK_200, res->status);
  5747. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5748. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5749. }
  5750. TEST_F(ServerTest, GetMethodLocalAddr) {
  5751. auto res = cli_.Get("/local_addr");
  5752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5753. EXPECT_EQ(StatusCode::OK_200, res->status);
  5754. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5755. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5756. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5757. }
  5758. TEST_F(ServerTest, HTTPResponseSplitting) {
  5759. auto res = cli_.Get("/http_response_splitting");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. EXPECT_EQ(StatusCode::OK_200, res->status);
  5762. }
  5763. TEST_F(ServerTest, SlowRequest) {
  5764. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5765. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5766. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5767. }
  5768. #if 0
  5769. TEST_F(ServerTest, SlowPost) {
  5770. char buffer[64 * 1024];
  5771. memset(buffer, 0x42, sizeof(buffer));
  5772. auto res = cli_.Post(
  5773. "/slowpost", 64 * 1024 * 1024,
  5774. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5775. auto ret = sink.write(buffer, sizeof(buffer));
  5776. EXPECT_TRUE(ret);
  5777. return true;
  5778. },
  5779. "text/plain");
  5780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5781. EXPECT_EQ(StatusCode::OK_200, res->status);
  5782. }
  5783. TEST_F(ServerTest, SlowPostFail) {
  5784. char buffer[64 * 1024];
  5785. memset(buffer, 0x42, sizeof(buffer));
  5786. cli_.set_write_timeout(std::chrono::seconds(0));
  5787. auto res = cli_.Post(
  5788. "/slowpost", 64 * 1024 * 1024,
  5789. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5790. sink.write(buffer, sizeof(buffer));
  5791. return true;
  5792. },
  5793. "text/plain");
  5794. ASSERT_TRUE(!res);
  5795. EXPECT_EQ(Error::Write, res.error());
  5796. }
  5797. #endif
  5798. TEST_F(ServerTest, Put) {
  5799. auto res = cli_.Put("/put", "PUT", "text/plain");
  5800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5801. EXPECT_EQ(StatusCode::OK_200, res->status);
  5802. EXPECT_EQ("PUT", res->body);
  5803. }
  5804. TEST_F(ServerTest, PutWithContentProvider) {
  5805. auto res = cli_.Put(
  5806. "/put", 3,
  5807. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5808. sink.os << "PUT";
  5809. return true;
  5810. },
  5811. "text/plain");
  5812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5813. EXPECT_EQ(StatusCode::OK_200, res->status);
  5814. EXPECT_EQ("PUT", res->body);
  5815. }
  5816. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5817. auto res = cli_.Post(
  5818. "/post", 42,
  5819. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5820. return false;
  5821. },
  5822. "text/plain");
  5823. ASSERT_TRUE(!res);
  5824. EXPECT_EQ(Error::Canceled, res.error());
  5825. }
  5826. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5827. auto res = cli_.Put(
  5828. "/put",
  5829. [](size_t /*offset*/, DataSink &sink) {
  5830. sink.os << "PUT";
  5831. sink.done();
  5832. return true;
  5833. },
  5834. "text/plain");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. EXPECT_EQ(StatusCode::OK_200, res->status);
  5837. EXPECT_EQ("PUT", res->body);
  5838. }
  5839. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5840. auto res = cli_.Post(
  5841. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5842. "text/plain");
  5843. ASSERT_TRUE(!res);
  5844. EXPECT_EQ(Error::Canceled, res.error());
  5845. }
  5846. TEST_F(ServerTest, PostLoopBack) {
  5847. std::string body;
  5848. auto res = cli_.Post(
  5849. "/post-loopback", 9,
  5850. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5851. EXPECT_EQ(9u, length);
  5852. sink.write("123", 3);
  5853. sink.write("456", 3);
  5854. sink.write("789", 3);
  5855. return true;
  5856. },
  5857. "text/plain",
  5858. [&body](const char *data, size_t data_length) {
  5859. body.append(data, data_length);
  5860. return true;
  5861. });
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. EXPECT_EQ(StatusCode::OK_200, res->status);
  5864. EXPECT_EQ("123456789", body);
  5865. }
  5866. TEST_F(ServerTest, PutLoopBack) {
  5867. std::string body;
  5868. auto res = cli_.Put(
  5869. "/put-loopback", 9,
  5870. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5871. EXPECT_EQ(9u, length);
  5872. sink.write("123", 3);
  5873. sink.write("456", 3);
  5874. sink.write("789", 3);
  5875. return true;
  5876. },
  5877. "text/plain",
  5878. [&body](const char *data, size_t data_length) {
  5879. body.append(data, data_length);
  5880. return true;
  5881. });
  5882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5883. EXPECT_EQ(StatusCode::OK_200, res->status);
  5884. EXPECT_EQ("123456789", body);
  5885. }
  5886. TEST_F(ServerTest, PatchLoopBack) {
  5887. std::string body;
  5888. auto res = cli_.Patch(
  5889. "/patch-loopback", 9,
  5890. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5891. EXPECT_EQ(9u, length);
  5892. sink.write("123", 3);
  5893. sink.write("456", 3);
  5894. sink.write("789", 3);
  5895. return true;
  5896. },
  5897. "text/plain",
  5898. [&body](const char *data, size_t data_length) {
  5899. body.append(data, data_length);
  5900. return true;
  5901. });
  5902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5903. EXPECT_EQ(StatusCode::OK_200, res->status);
  5904. EXPECT_EQ("123456789", body);
  5905. }
  5906. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5907. std::string body;
  5908. auto res = cli_.Post(
  5909. "/post-loopback",
  5910. [](size_t /*offset*/, DataSink &sink) {
  5911. sink.write("123", 3);
  5912. sink.write("456", 3);
  5913. sink.write("789", 3);
  5914. sink.done();
  5915. return true;
  5916. },
  5917. "text/plain",
  5918. [&body](const char *data, size_t data_length) {
  5919. body.append(data, data_length);
  5920. return true;
  5921. });
  5922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5923. EXPECT_EQ(StatusCode::OK_200, res->status);
  5924. EXPECT_EQ("123456789", body);
  5925. }
  5926. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5927. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5928. cli_.set_compress(true);
  5929. auto res = cli_.Put(
  5930. "/put", 3,
  5931. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5932. sink.os << "PUT";
  5933. return true;
  5934. },
  5935. "text/plain");
  5936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5937. EXPECT_EQ(StatusCode::OK_200, res->status);
  5938. EXPECT_EQ("PUT", res->body);
  5939. }
  5940. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5941. cli_.set_compress(true);
  5942. auto res = cli_.Post(
  5943. "/post", 42,
  5944. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5945. return false;
  5946. },
  5947. "text/plain");
  5948. ASSERT_TRUE(!res);
  5949. EXPECT_EQ(Error::Canceled, res.error());
  5950. }
  5951. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5952. cli_.set_compress(true);
  5953. auto res = cli_.Put(
  5954. "/put",
  5955. [](size_t /*offset*/, DataSink &sink) {
  5956. sink.os << "PUT";
  5957. sink.done();
  5958. return true;
  5959. },
  5960. "text/plain");
  5961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5962. EXPECT_EQ(StatusCode::OK_200, res->status);
  5963. EXPECT_EQ("PUT", res->body);
  5964. }
  5965. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5966. cli_.set_compress(true);
  5967. auto res = cli_.Post(
  5968. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5969. "text/plain");
  5970. ASSERT_TRUE(!res);
  5971. EXPECT_EQ(Error::Canceled, res.error());
  5972. }
  5973. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5974. cli_.set_compress(true);
  5975. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. EXPECT_EQ(LARGE_DATA, res->body);
  5979. }
  5980. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5981. #ifdef CPPHTTPLIB_SSL_ENABLED
  5982. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5983. Client cli(s.c_str());
  5984. cli.enable_server_certificate_verification(false);
  5985. #else
  5986. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5987. Client cli(s.c_str());
  5988. #endif
  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. // The compressed size should be less than a 10th of the original. May vary
  5995. // depending on the zlib library.
  5996. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5997. static_cast<uint64_t>(10 * 1024 * 1024));
  5998. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5999. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6000. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6001. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6002. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6003. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6004. #endif
  6005. }
  6006. TEST_F(ServerTest, PutContentWithDeflate) {
  6007. cli_.set_compress(false);
  6008. Headers headers;
  6009. headers.emplace("Content-Encoding", "deflate");
  6010. // PUT in deflate format:
  6011. auto res = cli_.Put("/put", headers,
  6012. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6014. EXPECT_EQ(StatusCode::OK_200, res->status);
  6015. EXPECT_EQ("PUT", res->body);
  6016. }
  6017. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6018. Headers headers;
  6019. headers.emplace("Accept-Encoding", "gzip, deflate");
  6020. auto res = cli_.Get("/streamed-chunked", headers);
  6021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6022. EXPECT_EQ(StatusCode::OK_200, res->status);
  6023. EXPECT_EQ(std::string("123456789"), res->body);
  6024. }
  6025. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6026. Headers headers;
  6027. headers.emplace("Accept-Encoding", "gzip, deflate");
  6028. auto res = cli_.Get("/streamed-chunked2", headers);
  6029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6030. EXPECT_EQ(StatusCode::OK_200, res->status);
  6031. EXPECT_EQ(std::string("123456789"), res->body);
  6032. }
  6033. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6034. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. EXPECT_EQ(StatusCode::OK_200, res->status);
  6037. }
  6038. TEST(GzipDecompressor, ChunkedDecompression) {
  6039. std::string data;
  6040. for (size_t i = 0; i < 32 * 1024; ++i) {
  6041. data.push_back(static_cast<char>('a' + i % 26));
  6042. }
  6043. std::string compressed_data;
  6044. {
  6045. httplib::detail::gzip_compressor compressor;
  6046. bool result = compressor.compress(
  6047. data.data(), data.size(),
  6048. /*last=*/true,
  6049. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6050. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6051. compressed_data_size);
  6052. return true;
  6053. });
  6054. ASSERT_TRUE(result);
  6055. }
  6056. std::string decompressed_data;
  6057. {
  6058. httplib::detail::gzip_decompressor decompressor;
  6059. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6060. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6061. size_t chunk_size = 130;
  6062. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6063. chunk_begin += chunk_size) {
  6064. size_t current_chunk_size =
  6065. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6066. bool result = decompressor.decompress(
  6067. compressed_data.data() + chunk_begin, current_chunk_size,
  6068. [&](const char *decompressed_data_chunk,
  6069. size_t decompressed_data_chunk_size) {
  6070. decompressed_data.insert(decompressed_data.size(),
  6071. decompressed_data_chunk,
  6072. decompressed_data_chunk_size);
  6073. return true;
  6074. });
  6075. ASSERT_TRUE(result);
  6076. }
  6077. }
  6078. ASSERT_EQ(data, decompressed_data);
  6079. }
  6080. TEST(GzipDecompressor, DeflateDecompression) {
  6081. std::string original_text = "Raw deflate without gzip";
  6082. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6083. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6084. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6085. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6086. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6087. std::string decompressed_data;
  6088. {
  6089. httplib::detail::gzip_decompressor decompressor;
  6090. bool result = decompressor.decompress(
  6091. compressed_data.data(), compressed_data.size(),
  6092. [&](const char *decompressed_data_chunk,
  6093. size_t decompressed_data_chunk_size) {
  6094. decompressed_data.insert(decompressed_data.size(),
  6095. decompressed_data_chunk,
  6096. decompressed_data_chunk_size);
  6097. return true;
  6098. });
  6099. ASSERT_TRUE(result);
  6100. }
  6101. ASSERT_EQ(original_text, decompressed_data);
  6102. }
  6103. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6104. std::string original_text = "Raw deflate without gzip";
  6105. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6106. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6107. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6108. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6109. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6110. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6111. std::string decompressed_data;
  6112. {
  6113. httplib::detail::gzip_decompressor decompressor;
  6114. bool result = decompressor.decompress(
  6115. compressed_data.data(), compressed_data.size(),
  6116. [&](const char *decompressed_data_chunk,
  6117. size_t decompressed_data_chunk_size) {
  6118. decompressed_data.insert(decompressed_data.size(),
  6119. decompressed_data_chunk,
  6120. decompressed_data_chunk_size);
  6121. return true;
  6122. });
  6123. ASSERT_TRUE(result);
  6124. }
  6125. ASSERT_EQ(original_text, decompressed_data);
  6126. }
  6127. #endif
  6128. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6129. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6130. Headers headers;
  6131. headers.emplace("Accept-Encoding", "br");
  6132. auto res = cli_.Get("/streamed-chunked", headers);
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. EXPECT_EQ(StatusCode::OK_200, res->status);
  6135. EXPECT_EQ(std::string("123456789"), res->body);
  6136. }
  6137. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6138. Headers headers;
  6139. headers.emplace("Accept-Encoding", "br");
  6140. auto res = cli_.Get("/streamed-chunked2", headers);
  6141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6142. EXPECT_EQ(StatusCode::OK_200, res->status);
  6143. EXPECT_EQ(std::string("123456789"), res->body);
  6144. }
  6145. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6146. cli_.set_compress(true);
  6147. auto res = cli_.Put(
  6148. "/put", 3,
  6149. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6150. sink.os << "PUT";
  6151. return true;
  6152. },
  6153. "text/plain");
  6154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6155. EXPECT_EQ(StatusCode::OK_200, res->status);
  6156. EXPECT_EQ("PUT", res->body);
  6157. }
  6158. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6159. cli_.set_compress(true);
  6160. auto res = cli_.Put(
  6161. "/put",
  6162. [](size_t /*offset*/, DataSink &sink) {
  6163. sink.os << "PUT";
  6164. sink.done();
  6165. return true;
  6166. },
  6167. "text/plain");
  6168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6169. EXPECT_EQ(StatusCode::OK_200, res->status);
  6170. EXPECT_EQ("PUT", res->body);
  6171. }
  6172. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6173. cli_.set_compress(true);
  6174. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::OK_200, res->status);
  6177. EXPECT_EQ(LARGE_DATA, res->body);
  6178. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6179. }
  6180. #endif
  6181. TEST_F(ServerTest, Patch) {
  6182. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. EXPECT_EQ(StatusCode::OK_200, res->status);
  6185. EXPECT_EQ("PATCH", res->body);
  6186. }
  6187. TEST_F(ServerTest, Delete) {
  6188. auto res = cli_.Delete("/delete");
  6189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6190. EXPECT_EQ(StatusCode::OK_200, res->status);
  6191. EXPECT_EQ("DELETE", res->body);
  6192. }
  6193. TEST_F(ServerTest, DeleteContentReceiver) {
  6194. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6196. EXPECT_EQ(StatusCode::OK_200, res->status);
  6197. EXPECT_EQ("content", res->body);
  6198. }
  6199. TEST_F(ServerTest, Options) {
  6200. auto res = cli_.Options("*");
  6201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6202. EXPECT_EQ(StatusCode::OK_200, res->status);
  6203. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6204. EXPECT_TRUE(res->body.empty());
  6205. }
  6206. TEST_F(ServerTest, URL) {
  6207. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. EXPECT_EQ(StatusCode::OK_200, res->status);
  6210. }
  6211. TEST_F(ServerTest, ArrayParam) {
  6212. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. }
  6216. TEST_F(ServerTest, ArrayParamValues) {
  6217. auto res =
  6218. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. EXPECT_EQ(StatusCode::OK_200, res->status);
  6221. }
  6222. TEST_F(ServerTest, NoMultipleHeaders) {
  6223. Headers headers = {{"Content-Length", "5"}};
  6224. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6225. "text/plain");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. EXPECT_EQ(StatusCode::OK_200, res->status);
  6228. }
  6229. TEST_F(ServerTest, PostContentReceiver) {
  6230. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. ASSERT_EQ(StatusCode::OK_200, res->status);
  6233. ASSERT_EQ("content", res->body);
  6234. }
  6235. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6236. UploadFormDataItems items = {
  6237. {"text1", "text default", "", ""},
  6238. {"text2", "aωb", "", ""},
  6239. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6240. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6241. {"file3", "", "", "application/octet-stream"},
  6242. };
  6243. auto res = cli_.Post("/content_receiver", items);
  6244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6245. EXPECT_EQ(StatusCode::OK_200, res->status);
  6246. }
  6247. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6248. UploadFormDataItems items = {
  6249. {"text1", "text default", "", ""},
  6250. {"text2", "aωb", "", ""},
  6251. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6252. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6253. {"file3", "", "", "application/octet-stream"},
  6254. };
  6255. auto boundary = std::string("+++++");
  6256. std::string body;
  6257. for (const auto &item : items) {
  6258. body += "--" + boundary + "\r\n";
  6259. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6260. if (!item.filename.empty()) {
  6261. body += "; filename=\"" + item.filename + "\"";
  6262. }
  6263. body += "\r\n";
  6264. if (!item.content_type.empty()) {
  6265. body += "Content-Type: " + item.content_type + "\r\n";
  6266. }
  6267. body += "\r\n";
  6268. body += item.content + "\r\n";
  6269. }
  6270. body += "--" + boundary + "--\r\n";
  6271. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6272. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. }
  6276. TEST(MultipartFormDataTest, FieldEscaping) {
  6277. Server svr;
  6278. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6279. const ContentReader &content_reader) {
  6280. ASSERT_TRUE(req.is_multipart_form_data());
  6281. std::vector<FormData> received;
  6282. content_reader(
  6283. [&](const FormData &file) {
  6284. received.push_back(file);
  6285. return true;
  6286. },
  6287. [&](const char *data, size_t data_length) {
  6288. received.back().content.append(data, data_length);
  6289. return true;
  6290. });
  6291. // '"', CR and LF in names and filenames are escaped following the
  6292. // WHATWG HTML standard, so each part still parses as a single part
  6293. // with no injected headers. Content types get CR/LF escaped too,
  6294. // while '"' (legal there, e.g. quoted charset) is preserved.
  6295. ASSERT_EQ(4U, received.size());
  6296. EXPECT_EQ("na%22me", received[0].name);
  6297. EXPECT_EQ("quoted name", received[0].content);
  6298. EXPECT_EQ("file", received[1].name);
  6299. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6300. received[1].filename);
  6301. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6302. EXPECT_EQ("injected", received[1].content);
  6303. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6304. EXPECT_EQ("my%22file.txt", received[2].filename);
  6305. EXPECT_EQ("cr lf name", received[2].content);
  6306. EXPECT_EQ("typed", received[3].name);
  6307. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6308. received[3].content_type);
  6309. EXPECT_EQ("typed content", received[3].content);
  6310. });
  6311. auto port = svr.bind_to_any_port("localhost");
  6312. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6313. auto se = detail::scope_exit([&] {
  6314. svr.stop();
  6315. t.join();
  6316. ASSERT_FALSE(svr.is_running());
  6317. });
  6318. svr.wait_until_ready();
  6319. Client cli("localhost", port);
  6320. UploadFormDataItems items = {
  6321. {"na\"me", "quoted name", "", ""},
  6322. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6323. "application/octet-stream"},
  6324. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6325. {"typed", "typed content", "",
  6326. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6327. };
  6328. auto res = cli.Post("/post", items);
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. EXPECT_EQ(StatusCode::OK_200, res->status);
  6331. }
  6332. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6333. const UploadFormDataItems items = {
  6334. {"name1", "Content 1", "", ""},
  6335. {"name2", "Content 2", "file2.txt", "text/plain"},
  6336. };
  6337. Server svr;
  6338. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6339. const ContentReader &content_reader) {
  6340. ASSERT_TRUE(req.is_multipart_form_data());
  6341. std::vector<FormData> received;
  6342. content_reader(
  6343. [&](const FormData &file) {
  6344. received.push_back(file);
  6345. return true;
  6346. },
  6347. [&](const char *data, size_t data_length) {
  6348. received.back().content.append(data, data_length);
  6349. return true;
  6350. });
  6351. ASSERT_EQ(2U, received.size());
  6352. EXPECT_EQ("name1", received[0].name);
  6353. EXPECT_EQ("Content 1", received[0].content);
  6354. EXPECT_EQ("name2", received[1].name);
  6355. EXPECT_EQ("Content 2", received[1].content);
  6356. EXPECT_EQ("file2.txt", received[1].filename);
  6357. EXPECT_EQ("text/plain", received[1].content_type);
  6358. });
  6359. auto port = svr.bind_to_any_port("localhost");
  6360. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6361. auto se = detail::scope_exit([&] {
  6362. svr.stop();
  6363. t.join();
  6364. ASSERT_FALSE(svr.is_running());
  6365. });
  6366. svr.wait_until_ready();
  6367. Client cli("localhost", port);
  6368. // Whole-body serialization with a generated boundary
  6369. {
  6370. MultipartFormDataWriter writer;
  6371. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6372. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6373. writer.content_type());
  6374. auto body = writer.serialize(items);
  6375. EXPECT_EQ(body.size(), writer.content_length(items));
  6376. auto res = cli.Post("/post", body, writer.content_type());
  6377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6378. EXPECT_EQ(StatusCode::OK_200, res->status);
  6379. }
  6380. // Per-part framing with a custom boundary via a content provider
  6381. {
  6382. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6383. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6384. MultipartFormDataWriter writer("custom-boundary_123");
  6385. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6386. std::string body;
  6387. for (const auto &item : items) {
  6388. body += writer.item_begin(item);
  6389. body += item.content;
  6390. body += MultipartFormDataWriter::item_end();
  6391. }
  6392. body += writer.finish();
  6393. EXPECT_EQ(body.size(), writer.content_length(items));
  6394. auto res = cli.Post(
  6395. "/post", body.size(),
  6396. [&](size_t offset, size_t length, DataSink &sink) {
  6397. sink.write(body.data() + offset, length);
  6398. return true;
  6399. },
  6400. writer.content_type());
  6401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6402. EXPECT_EQ(StatusCode::OK_200, res->status);
  6403. }
  6404. }
  6405. TEST_F(ServerTest, PostContentReceiverGzip) {
  6406. cli_.set_compress(true);
  6407. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6409. ASSERT_EQ(StatusCode::OK_200, res->status);
  6410. ASSERT_EQ("content", res->body);
  6411. }
  6412. TEST_F(ServerTest, PutContentReceiver) {
  6413. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6415. ASSERT_EQ(StatusCode::OK_200, res->status);
  6416. ASSERT_EQ("content", res->body);
  6417. }
  6418. TEST_F(ServerTest, PatchContentReceiver) {
  6419. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6421. ASSERT_EQ(StatusCode::OK_200, res->status);
  6422. ASSERT_EQ("content", res->body);
  6423. }
  6424. template <typename ClientType>
  6425. void TestWithHeadersAndContentReceiver(
  6426. ClientType &cli,
  6427. std::function<Result(ClientType &, const std::string &, const Headers &,
  6428. const std::string &, const std::string &,
  6429. ContentReceiver, DownloadProgress)>
  6430. request_func) {
  6431. Headers headers;
  6432. headers.emplace("X-Custom-Header", "test-value");
  6433. std::string received_body;
  6434. auto res = request_func(
  6435. cli, "/content_receiver", headers, "content", "application/json",
  6436. [&](const char *data, size_t data_length) {
  6437. received_body.append(data, data_length);
  6438. return true;
  6439. },
  6440. nullptr);
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. EXPECT_EQ("content", received_body);
  6444. }
  6445. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6446. #ifdef CPPHTTPLIB_SSL_ENABLED
  6447. using ClientT = SSLClient;
  6448. #else
  6449. using ClientT = Client;
  6450. #endif
  6451. TestWithHeadersAndContentReceiver<ClientT>(
  6452. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6453. const std::string &body, const std::string &content_type,
  6454. ContentReceiver receiver, DownloadProgress progress) {
  6455. return cli.Post(path, headers, body, content_type, receiver, progress);
  6456. });
  6457. }
  6458. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6459. #ifdef CPPHTTPLIB_SSL_ENABLED
  6460. using ClientT = SSLClient;
  6461. #else
  6462. using ClientT = Client;
  6463. #endif
  6464. TestWithHeadersAndContentReceiver<ClientT>(
  6465. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6466. const std::string &body, const std::string &content_type,
  6467. ContentReceiver receiver, DownloadProgress progress) {
  6468. return cli.Put(path, headers, body, content_type, receiver, progress);
  6469. });
  6470. }
  6471. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6472. #ifdef CPPHTTPLIB_SSL_ENABLED
  6473. using ClientT = SSLClient;
  6474. #else
  6475. using ClientT = Client;
  6476. #endif
  6477. TestWithHeadersAndContentReceiver<ClientT>(
  6478. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6479. const std::string &body, const std::string &content_type,
  6480. ContentReceiver receiver, DownloadProgress progress) {
  6481. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6482. });
  6483. }
  6484. template <typename ClientType>
  6485. void TestWithHeadersAndContentReceiverWithProgress(
  6486. ClientType &cli,
  6487. std::function<Result(ClientType &, const std::string &, const Headers &,
  6488. const std::string &, const std::string &,
  6489. ContentReceiver, DownloadProgress)>
  6490. request_func) {
  6491. Headers headers;
  6492. headers.emplace("X-Test-Header", "progress-test");
  6493. std::string received_body;
  6494. auto progress_called = false;
  6495. auto res = request_func(
  6496. cli, "/content_receiver", headers, "content", "text/plain",
  6497. [&](const char *data, size_t data_length) {
  6498. received_body.append(data, data_length);
  6499. return true;
  6500. },
  6501. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6502. progress_called = true;
  6503. return true;
  6504. });
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. EXPECT_EQ(StatusCode::OK_200, res->status);
  6507. EXPECT_EQ("content", received_body);
  6508. EXPECT_TRUE(progress_called);
  6509. }
  6510. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6511. #ifdef CPPHTTPLIB_SSL_ENABLED
  6512. using ClientT = SSLClient;
  6513. #else
  6514. using ClientT = Client;
  6515. #endif
  6516. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6517. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6518. const std::string &body, const std::string &content_type,
  6519. ContentReceiver receiver, DownloadProgress progress) {
  6520. return cli.Post(path, headers, body, content_type, receiver, progress);
  6521. });
  6522. }
  6523. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6524. #ifdef CPPHTTPLIB_SSL_ENABLED
  6525. using ClientT = SSLClient;
  6526. #else
  6527. using ClientT = Client;
  6528. #endif
  6529. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6530. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6531. const std::string &body, const std::string &content_type,
  6532. ContentReceiver receiver, DownloadProgress progress) {
  6533. return cli.Put(path, headers, body, content_type, receiver, progress);
  6534. });
  6535. }
  6536. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6537. #ifdef CPPHTTPLIB_SSL_ENABLED
  6538. using ClientT = SSLClient;
  6539. #else
  6540. using ClientT = Client;
  6541. #endif
  6542. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6543. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6544. const std::string &body, const std::string &content_type,
  6545. ContentReceiver receiver, DownloadProgress progress) {
  6546. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6547. });
  6548. }
  6549. template <typename ClientType>
  6550. void TestWithHeadersAndContentReceiverError(
  6551. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6552. const Headers &, const std::string &,
  6553. const std::string &, ContentReceiver)>
  6554. request_func) {
  6555. Headers headers;
  6556. headers.emplace("X-Error-Test", "true");
  6557. std::string received_body;
  6558. auto receiver_failed = false;
  6559. auto res =
  6560. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6561. [&](const char *data, size_t data_length) {
  6562. received_body.append(data, data_length);
  6563. receiver_failed = true;
  6564. return false;
  6565. });
  6566. ASSERT_FALSE(res);
  6567. EXPECT_TRUE(receiver_failed);
  6568. }
  6569. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6570. #ifdef CPPHTTPLIB_SSL_ENABLED
  6571. using ClientT = SSLClient;
  6572. #else
  6573. using ClientT = Client;
  6574. #endif
  6575. TestWithHeadersAndContentReceiverError<ClientT>(
  6576. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6577. const std::string &body, const std::string &content_type,
  6578. ContentReceiver receiver) {
  6579. return cli.Post(path, headers, body, content_type, receiver);
  6580. });
  6581. }
  6582. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6583. #ifdef CPPHTTPLIB_SSL_ENABLED
  6584. using ClientT = SSLClient;
  6585. #else
  6586. using ClientT = Client;
  6587. #endif
  6588. TestWithHeadersAndContentReceiverError<ClientT>(
  6589. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6590. const std::string &body, const std::string &content_type,
  6591. ContentReceiver receiver) {
  6592. return cli.Put(path, headers, body, content_type, receiver);
  6593. });
  6594. }
  6595. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6596. #ifdef CPPHTTPLIB_SSL_ENABLED
  6597. using ClientT = SSLClient;
  6598. #else
  6599. using ClientT = Client;
  6600. #endif
  6601. TestWithHeadersAndContentReceiverError<ClientT>(
  6602. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6603. const std::string &body, const std::string &content_type,
  6604. ContentReceiver receiver) {
  6605. return cli.Patch(path, headers, body, content_type, receiver);
  6606. });
  6607. }
  6608. TEST_F(ServerTest, PostQueryStringAndBody) {
  6609. auto res =
  6610. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6612. ASSERT_EQ(StatusCode::OK_200, res->status);
  6613. }
  6614. TEST_F(ServerTest, HTTP2Magic) {
  6615. Request req;
  6616. req.method = "PRI";
  6617. req.path = "*";
  6618. req.body = "SM";
  6619. auto res = std::make_shared<Response>();
  6620. auto error = Error::Success;
  6621. auto ret = cli_.send(req, *res, error);
  6622. ASSERT_TRUE(ret);
  6623. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6624. }
  6625. TEST_F(ServerTest, KeepAlive) {
  6626. auto res = cli_.Get("/hi");
  6627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6628. EXPECT_EQ(StatusCode::OK_200, res->status);
  6629. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6630. EXPECT_EQ("Hello World!", res->body);
  6631. res = cli_.Get("/hi");
  6632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6633. EXPECT_EQ(StatusCode::OK_200, res->status);
  6634. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6635. EXPECT_EQ("Hello World!", res->body);
  6636. res = cli_.Get("/hi");
  6637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6638. EXPECT_EQ(StatusCode::OK_200, res->status);
  6639. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6640. EXPECT_EQ("Hello World!", res->body);
  6641. res = cli_.Get("/not-exist");
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6644. res = cli_.Post("/empty", "", "text/plain");
  6645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6646. EXPECT_EQ(StatusCode::OK_200, res->status);
  6647. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6648. EXPECT_EQ("empty", res->body);
  6649. EXPECT_EQ("close", res->get_header_value("Connection"));
  6650. res = cli_.Post(
  6651. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6652. "text/plain");
  6653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6654. EXPECT_EQ(StatusCode::OK_200, res->status);
  6655. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6656. EXPECT_EQ("empty", res->body);
  6657. cli_.set_keep_alive(false);
  6658. res = cli_.Get("/last-request");
  6659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6660. EXPECT_EQ(StatusCode::OK_200, res->status);
  6661. EXPECT_EQ("close", res->get_header_value("Connection"));
  6662. }
  6663. TEST_F(ServerTest, TooManyRedirect) {
  6664. cli_.set_follow_location(true);
  6665. auto res = cli_.Get("/redirect/0");
  6666. ASSERT_TRUE(!res);
  6667. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6668. }
  6669. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6670. Request req;
  6671. req.method = "FOOBAR";
  6672. req.path = "/hi";
  6673. cli_.set_keep_alive(true);
  6674. auto res = cli_.send(req);
  6675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6676. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6677. EXPECT_EQ("close", res->get_header_value("Connection"));
  6678. EXPECT_FALSE(cli_.is_socket_open());
  6679. }
  6680. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6681. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6682. TEST_F(ServerTest, Gzip) {
  6683. Headers headers;
  6684. headers.emplace("Accept-Encoding", "gzip, deflate");
  6685. auto res = cli_.Get("/compress", headers);
  6686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6687. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6688. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6689. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6690. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6691. "7890123456789012345678901234567890",
  6692. res->body);
  6693. EXPECT_EQ(StatusCode::OK_200, res->status);
  6694. }
  6695. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6696. Headers headers;
  6697. headers.emplace("Accept-Encoding", "gzip, deflate");
  6698. auto res = cli_.Get("/compress-with-charset", headers);
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6701. EXPECT_EQ("application/json; charset=utf-8",
  6702. res->get_header_value("Content-Type"));
  6703. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6704. "7890123456789012345678901234567890",
  6705. res->body);
  6706. EXPECT_EQ(StatusCode::OK_200, res->status);
  6707. }
  6708. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6709. Headers headers;
  6710. headers.emplace("Accept-Encoding", "");
  6711. auto res = cli_.Get("/compress", headers);
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6714. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6715. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6716. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6717. "7890123456789012345678901234567890",
  6718. res->body);
  6719. EXPECT_EQ(StatusCode::OK_200, res->status);
  6720. }
  6721. TEST_F(ServerTest, GzipWithContentReceiver) {
  6722. Headers headers;
  6723. headers.emplace("Accept-Encoding", "gzip, deflate");
  6724. std::string body;
  6725. auto res = cli_.Get("/compress", headers,
  6726. [&](const char *data, uint64_t data_length) {
  6727. EXPECT_EQ(100U, data_length);
  6728. body.append(data, data_length);
  6729. return true;
  6730. });
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6733. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6734. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6735. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6736. "7890123456789012345678901234567890",
  6737. body);
  6738. EXPECT_EQ(StatusCode::OK_200, res->status);
  6739. }
  6740. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6741. Headers headers;
  6742. headers.emplace("Accept-Encoding", "gzip, deflate");
  6743. cli_.set_decompress(false);
  6744. auto res = cli_.Get("/compress", headers);
  6745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6746. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6747. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6748. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6749. EXPECT_EQ(33U, res->body.size());
  6750. EXPECT_EQ(StatusCode::OK_200, res->status);
  6751. }
  6752. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6753. Headers headers;
  6754. headers.emplace("Accept-Encoding", "");
  6755. std::string body;
  6756. auto res = cli_.Get("/compress", headers,
  6757. [&](const char *data, uint64_t data_length) {
  6758. EXPECT_EQ(100U, data_length);
  6759. body.append(data, data_length);
  6760. return true;
  6761. });
  6762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6763. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6764. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6765. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6766. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6767. "7890123456789012345678901234567890",
  6768. body);
  6769. EXPECT_EQ(StatusCode::OK_200, res->status);
  6770. }
  6771. TEST_F(ServerTest, NoGzip) {
  6772. Headers headers;
  6773. headers.emplace("Accept-Encoding", "gzip, deflate");
  6774. auto res = cli_.Get("/nocompress", headers);
  6775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6776. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6777. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6778. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6779. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6780. "7890123456789012345678901234567890",
  6781. res->body);
  6782. EXPECT_EQ(StatusCode::OK_200, res->status);
  6783. }
  6784. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6785. Headers headers;
  6786. headers.emplace("Accept-Encoding", "gzip, deflate");
  6787. std::string body;
  6788. auto res = cli_.Get("/nocompress", headers,
  6789. [&](const char *data, uint64_t data_length) {
  6790. EXPECT_EQ(100U, data_length);
  6791. body.append(data, data_length);
  6792. return true;
  6793. });
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6796. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6797. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6798. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6799. "7890123456789012345678901234567890",
  6800. body);
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. }
  6803. TEST_F(ServerTest, MultipartFormDataGzip) {
  6804. UploadFormDataItems items = {
  6805. {"key1", "test", "", ""},
  6806. {"key2", "--abcdefg123", "", ""},
  6807. };
  6808. cli_.set_compress(true);
  6809. auto res = cli_.Post("/compress-multipart", items);
  6810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6811. EXPECT_EQ(StatusCode::OK_200, res->status);
  6812. }
  6813. #endif
  6814. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6815. TEST_F(ServerTest, Brotli) {
  6816. Headers headers;
  6817. headers.emplace("Accept-Encoding", "br");
  6818. auto res = cli_.Get("/compress", headers);
  6819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6820. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6821. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6822. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6823. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6824. "7890123456789012345678901234567890",
  6825. res->body);
  6826. EXPECT_EQ(StatusCode::OK_200, res->status);
  6827. }
  6828. #endif
  6829. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6830. TEST_F(ServerTest, Zstd) {
  6831. Headers headers;
  6832. headers.emplace("Accept-Encoding", "zstd");
  6833. auto res = cli_.Get("/compress", headers);
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6837. EXPECT_EQ("26", 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. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6844. Headers headers;
  6845. headers.emplace("Accept-Encoding", "");
  6846. auto res = cli_.Get("/compress", headers);
  6847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6848. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6849. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6850. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6851. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6852. "7890123456789012345678901234567890",
  6853. res->body);
  6854. EXPECT_EQ(StatusCode::OK_200, res->status);
  6855. }
  6856. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6857. Headers headers;
  6858. headers.emplace("Accept-Encoding", "zstd");
  6859. std::string body;
  6860. auto res = cli_.Get("/compress", headers,
  6861. [&](const char *data, uint64_t data_length) {
  6862. EXPECT_EQ(100U, data_length);
  6863. body.append(data, data_length);
  6864. return true;
  6865. });
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6868. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6869. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6870. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6871. "7890123456789012345678901234567890",
  6872. body);
  6873. EXPECT_EQ(StatusCode::OK_200, res->status);
  6874. }
  6875. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6876. Headers headers;
  6877. headers.emplace("Accept-Encoding", "zstd");
  6878. cli_.set_decompress(false);
  6879. auto res = cli_.Get("/compress", headers);
  6880. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6881. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6882. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6883. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6885. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6886. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6887. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6888. EXPECT_EQ(StatusCode::OK_200, res->status);
  6889. ASSERT_EQ(26U, res->body.size());
  6890. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6891. 0);
  6892. }
  6893. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6894. Headers headers;
  6895. headers.emplace("Accept-Encoding", "");
  6896. std::string body;
  6897. auto res = cli_.Get("/compress", headers,
  6898. [&](const char *data, uint64_t data_length) {
  6899. EXPECT_EQ(100U, data_length);
  6900. body.append(data, data_length);
  6901. return true;
  6902. });
  6903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6904. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6905. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6906. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6907. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6908. "7890123456789012345678901234567890",
  6909. body);
  6910. EXPECT_EQ(StatusCode::OK_200, res->status);
  6911. }
  6912. TEST_F(ServerTest, NoZstd) {
  6913. Headers headers;
  6914. headers.emplace("Accept-Encoding", "zstd");
  6915. auto res = cli_.Get("/nocompress", headers);
  6916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6917. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6918. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6919. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6920. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6921. "7890123456789012345678901234567890",
  6922. res->body);
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. }
  6925. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6926. Headers headers;
  6927. headers.emplace("Accept-Encoding", "zstd");
  6928. std::string body;
  6929. auto res = cli_.Get("/nocompress", headers,
  6930. [&](const char *data, uint64_t data_length) {
  6931. EXPECT_EQ(100U, data_length);
  6932. body.append(data, data_length);
  6933. return true;
  6934. });
  6935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6936. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6937. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6938. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6939. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6940. "7890123456789012345678901234567890",
  6941. body);
  6942. EXPECT_EQ(StatusCode::OK_200, res->status);
  6943. }
  6944. // TODO: How to enable zstd ??
  6945. TEST_F(ServerTest, MultipartFormDataZstd) {
  6946. UploadFormDataItems items = {
  6947. {"key1", "test", "", ""},
  6948. {"key2", "--abcdefg123", "", ""},
  6949. };
  6950. Headers headers;
  6951. headers.emplace("Accept-Encoding", "zstd");
  6952. cli_.set_compress(true);
  6953. auto res = cli_.Post("/compress-multipart", headers, items);
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. EXPECT_EQ(StatusCode::OK_200, res->status);
  6956. }
  6957. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6958. Headers headers;
  6959. headers.emplace("Accept-Encoding", "zstd");
  6960. cli_.set_compress(true);
  6961. auto res = cli_.Put(
  6962. "/put", headers, 3,
  6963. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6964. sink.os << "PUT";
  6965. return true;
  6966. },
  6967. "text/plain");
  6968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6969. EXPECT_EQ(StatusCode::OK_200, res->status);
  6970. EXPECT_EQ("PUT", res->body);
  6971. }
  6972. // Pre-compression logging tests
  6973. TEST_F(ServerTest, PreCompressionLogging) {
  6974. // Test data for compression (matches the actual /compress endpoint content)
  6975. const std::string test_content =
  6976. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6977. "3456789012345678901234567890";
  6978. // Variables to capture logging data
  6979. std::string pre_compression_body;
  6980. std::string pre_compression_content_type;
  6981. std::string pre_compression_content_encoding;
  6982. std::string post_compression_body;
  6983. std::string post_compression_content_type;
  6984. std::string post_compression_content_encoding;
  6985. // Set up pre-compression logger
  6986. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6987. const Response &res) {
  6988. pre_compression_body = res.body;
  6989. pre_compression_content_type = res.get_header_value("Content-Type");
  6990. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6991. });
  6992. // Set up post-compression logger
  6993. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6994. post_compression_body = res.body;
  6995. post_compression_content_type = res.get_header_value("Content-Type");
  6996. post_compression_content_encoding =
  6997. res.get_header_value("Content-Encoding");
  6998. });
  6999. // Test with gzip compression
  7000. Headers headers;
  7001. headers.emplace("Accept-Encoding", "gzip");
  7002. auto res = cli_.Get("/compress", headers);
  7003. // Verify response was compressed
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7007. // Verify pre-compression logger captured uncompressed content
  7008. EXPECT_EQ(test_content, pre_compression_body);
  7009. EXPECT_EQ("text/plain", pre_compression_content_type);
  7010. EXPECT_TRUE(pre_compression_content_encoding
  7011. .empty()); // No encoding header before compression
  7012. // Verify post-compression logger captured compressed content
  7013. EXPECT_NE(test_content,
  7014. post_compression_body); // Should be different after compression
  7015. EXPECT_EQ("text/plain", post_compression_content_type);
  7016. EXPECT_EQ("gzip", post_compression_content_encoding);
  7017. // Verify compressed content is smaller
  7018. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7019. }
  7020. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7021. const std::string test_content =
  7022. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7023. "3456789012345678901234567890";
  7024. std::string pre_compression_body;
  7025. std::string post_compression_body;
  7026. svr_.set_pre_compression_logger(
  7027. [&](const Request & /*req*/, const Response &res) {
  7028. pre_compression_body = res.body;
  7029. });
  7030. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7031. post_compression_body = res.body;
  7032. });
  7033. Headers headers;
  7034. headers.emplace("Accept-Encoding", "br");
  7035. auto res = cli_.Get("/compress", headers);
  7036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7037. EXPECT_EQ(StatusCode::OK_200, res->status);
  7038. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7039. // Verify pre-compression content is uncompressed
  7040. EXPECT_EQ(test_content, pre_compression_body);
  7041. // Verify post-compression content is compressed
  7042. EXPECT_NE(test_content, post_compression_body);
  7043. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7044. }
  7045. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7046. const std::string test_content =
  7047. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7048. "3456789012345678901234567890";
  7049. std::string pre_compression_body;
  7050. std::string post_compression_body;
  7051. svr_.set_pre_compression_logger(
  7052. [&](const Request & /*req*/, const Response &res) {
  7053. pre_compression_body = res.body;
  7054. });
  7055. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7056. post_compression_body = res.body;
  7057. });
  7058. // Request without compression (use /nocompress endpoint)
  7059. Headers headers;
  7060. auto res = cli_.Get("/nocompress", headers);
  7061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7062. EXPECT_EQ(StatusCode::OK_200, res->status);
  7063. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7064. // Pre-compression logger should not be called when no compression is applied
  7065. EXPECT_TRUE(
  7066. pre_compression_body.empty()); // Pre-compression logger not called
  7067. EXPECT_EQ(
  7068. test_content,
  7069. post_compression_body); // Post-compression logger captures final content
  7070. }
  7071. TEST_F(ServerTest, LoggerSeesContentLength) {
  7072. size_t logged_content_length = 0;
  7073. std::string logged_content_length_header;
  7074. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7075. logged_content_length = res.content_length_;
  7076. logged_content_length_header = res.get_header_value("Content-Length");
  7077. });
  7078. auto res = cli_.Get("/nocompress");
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::OK_200, res->status);
  7081. EXPECT_EQ(res->body.size(), logged_content_length);
  7082. EXPECT_EQ(std::to_string(logged_content_length),
  7083. logged_content_length_header);
  7084. }
  7085. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7086. const std::string test_content =
  7087. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7088. "3456789012345678901234567890";
  7089. std::string pre_compression_body;
  7090. bool pre_logger_called = false;
  7091. // Set only pre-compression logger
  7092. svr_.set_pre_compression_logger(
  7093. [&](const Request & /*req*/, const Response &res) {
  7094. pre_compression_body = res.body;
  7095. pre_logger_called = true;
  7096. });
  7097. Headers headers;
  7098. headers.emplace("Accept-Encoding", "gzip");
  7099. auto res = cli_.Get("/compress", headers);
  7100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7101. EXPECT_EQ(StatusCode::OK_200, res->status);
  7102. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7103. // Verify pre-compression logger was called
  7104. EXPECT_TRUE(pre_logger_called);
  7105. EXPECT_EQ(test_content, pre_compression_body);
  7106. }
  7107. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7108. {
  7109. // Test with Expect: 100-continue header - success case
  7110. // Server returns 100 Continue, client sends body, server returns 200 OK
  7111. Request req;
  7112. req.method = "POST";
  7113. req.path = "/post-large";
  7114. req.set_header("Expect", "100-continue");
  7115. req.body = LARGE_DATA;
  7116. Response res;
  7117. auto error = Error::Success;
  7118. cli_.set_keep_alive(true);
  7119. auto ret = cli_.send(req, res, error);
  7120. EXPECT_TRUE(ret);
  7121. EXPECT_EQ(StatusCode::OK_200, res.status);
  7122. EXPECT_EQ(LARGE_DATA, res.body);
  7123. }
  7124. {
  7125. // Test with Expect: 100-continue header - error case
  7126. // Client should not send the body when server returns an error
  7127. Request req;
  7128. req.method = "POST";
  7129. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7130. req.set_header("Expect", "100-continue");
  7131. req.body = LARGE_DATA;
  7132. Response res;
  7133. auto error = Error::Success;
  7134. auto start = std::chrono::high_resolution_clock::now();
  7135. cli_.set_keep_alive(true);
  7136. auto ret = cli_.send(req, res, error);
  7137. auto end = std::chrono::high_resolution_clock::now();
  7138. auto elapsed =
  7139. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7140. .count();
  7141. // With Expect: 100-continue, request completes successfully but with error
  7142. EXPECT_TRUE(ret);
  7143. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7144. EXPECT_EQ("close", res.get_header_value("Connection"));
  7145. EXPECT_FALSE(cli_.is_socket_open());
  7146. EXPECT_LE(elapsed, 2000);
  7147. }
  7148. {
  7149. // Send an extra GET request to ensure error recovery without hanging
  7150. Request req;
  7151. req.method = "GET";
  7152. req.path = "/hi";
  7153. auto start = std::chrono::high_resolution_clock::now();
  7154. auto res = cli_.send(req);
  7155. auto end = std::chrono::high_resolution_clock::now();
  7156. auto elapsed =
  7157. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7158. .count();
  7159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7160. EXPECT_EQ(StatusCode::OK_200, res->status);
  7161. EXPECT_EQ("Hello World!", res->body);
  7162. EXPECT_LE(elapsed, 500);
  7163. }
  7164. }
  7165. TEST(ZstdDecompressor, ChunkedDecompression) {
  7166. std::string data;
  7167. for (size_t i = 0; i < 32 * 1024; ++i) {
  7168. data.push_back(static_cast<char>('a' + i % 26));
  7169. }
  7170. std::string compressed_data;
  7171. {
  7172. httplib::detail::zstd_compressor compressor;
  7173. bool result = compressor.compress(
  7174. data.data(), data.size(),
  7175. /*last=*/true,
  7176. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7177. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7178. compressed_data_size);
  7179. return true;
  7180. });
  7181. ASSERT_TRUE(result);
  7182. }
  7183. std::string decompressed_data;
  7184. {
  7185. httplib::detail::zstd_decompressor decompressor;
  7186. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7187. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7188. size_t chunk_size = 130;
  7189. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7190. chunk_begin += chunk_size) {
  7191. size_t current_chunk_size =
  7192. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7193. bool result = decompressor.decompress(
  7194. compressed_data.data() + chunk_begin, current_chunk_size,
  7195. [&](const char *decompressed_data_chunk,
  7196. size_t decompressed_data_chunk_size) {
  7197. decompressed_data.insert(decompressed_data.size(),
  7198. decompressed_data_chunk,
  7199. decompressed_data_chunk_size);
  7200. return true;
  7201. });
  7202. ASSERT_TRUE(result);
  7203. }
  7204. }
  7205. ASSERT_EQ(data, decompressed_data);
  7206. }
  7207. TEST(ZstdDecompressor, Decompress) {
  7208. std::string original_text = "Compressed with ZSTD";
  7209. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7210. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7211. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7212. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7213. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7214. std::string decompressed_data;
  7215. {
  7216. httplib::detail::zstd_decompressor decompressor;
  7217. bool result = decompressor.decompress(
  7218. compressed_data.data(), compressed_data.size(),
  7219. [&](const char *decompressed_data_chunk,
  7220. size_t decompressed_data_chunk_size) {
  7221. decompressed_data.insert(decompressed_data.size(),
  7222. decompressed_data_chunk,
  7223. decompressed_data_chunk_size);
  7224. return true;
  7225. });
  7226. ASSERT_TRUE(result);
  7227. }
  7228. ASSERT_EQ(original_text, decompressed_data);
  7229. }
  7230. #endif
  7231. // Sends a raw request to a server listening at HOST:PORT.
  7232. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7233. std::string *resp = nullptr, int port = PORT) {
  7234. auto error = Error::Success;
  7235. auto client_sock = detail::create_client_socket(
  7236. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7237. /*connection_timeout_sec=*/5, 0,
  7238. /*read_timeout_sec=*/5, 0,
  7239. /*write_timeout_sec=*/5, 0, std::string(), error);
  7240. if (client_sock == INVALID_SOCKET) { return false; }
  7241. auto ret = detail::process_client_socket(
  7242. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7243. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7244. if (req.size() !=
  7245. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7246. return false;
  7247. }
  7248. char buf[512];
  7249. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7250. while (line_reader.getline()) {
  7251. if (resp) { *resp += line_reader.ptr(); }
  7252. }
  7253. return true;
  7254. });
  7255. detail::close_socket(client_sock);
  7256. return ret;
  7257. }
  7258. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7259. Server svr;
  7260. std::string header_value;
  7261. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7262. header_value = req.get_header_value("foo");
  7263. res.set_content("ok", "text/plain");
  7264. });
  7265. thread t = thread([&] { svr.listen(HOST, PORT); });
  7266. auto se = detail::scope_exit([&] {
  7267. svr.stop();
  7268. t.join();
  7269. ASSERT_FALSE(svr.is_running());
  7270. });
  7271. svr.wait_until_ready();
  7272. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7273. // like characters are not treated the same - use vertical tab and escape.
  7274. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7275. "foo: \t \v bar \x1B\t \r\n"
  7276. "Connection: close\r\n"
  7277. "\r\n";
  7278. std::string res;
  7279. ASSERT_TRUE(send_request(5, req, &res));
  7280. EXPECT_EQ(header_value, "");
  7281. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7282. }
  7283. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7284. Server svr;
  7285. std::string received;
  7286. svr.Get("/order", [&](const Request &req, Response &res) {
  7287. received = entries_to_string(req.headers);
  7288. res.set_content("ok", "text/plain");
  7289. });
  7290. auto port = svr.bind_to_any_port(HOST);
  7291. thread t = thread([&] { svr.listen_after_bind(); });
  7292. auto se = detail::scope_exit([&] {
  7293. svr.stop();
  7294. t.join();
  7295. ASSERT_FALSE(svr.is_running());
  7296. });
  7297. svr.wait_until_ready();
  7298. const std::string req = "GET /order HTTP/1.1\r\n"
  7299. "X-First: 1\r\n"
  7300. "X-Dup: a\r\n"
  7301. "X-Second: 2\r\n"
  7302. "X-Dup: b\r\n"
  7303. "Connection: close\r\n"
  7304. "\r\n";
  7305. std::string res;
  7306. ASSERT_TRUE(send_request(5, req, &res, port));
  7307. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7308. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7309. }
  7310. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7311. Server svr;
  7312. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7313. res.set_header("Set-Cookie", "first=1");
  7314. res.set_header("X-Between", "y");
  7315. res.set_header("Set-Cookie", "second=2");
  7316. res.set_content("ok", "text/plain");
  7317. });
  7318. auto port = svr.bind_to_any_port(HOST);
  7319. thread t = thread([&] { svr.listen_after_bind(); });
  7320. auto se = detail::scope_exit([&] {
  7321. svr.stop();
  7322. t.join();
  7323. ASSERT_FALSE(svr.is_running());
  7324. });
  7325. svr.wait_until_ready();
  7326. Client cli(HOST, port);
  7327. auto res = cli.Get("/cookies");
  7328. ASSERT_TRUE(res);
  7329. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7330. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7331. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7332. }
  7333. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7334. Server svr;
  7335. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7336. auto i = new int(0);
  7337. res.set_header("Trailer", "X-Safe, X-Reflected");
  7338. res.set_chunked_content_provider(
  7339. "text/plain",
  7340. [i](size_t /*offset*/, DataSink &sink) {
  7341. if (*i == 0) {
  7342. sink.os << "body";
  7343. } else {
  7344. Headers trailer;
  7345. // A valid trailer that must survive.
  7346. trailer.emplace("X-Safe", "safe");
  7347. // Attacker-controlled value carrying CR/LF (response splitting).
  7348. trailer.emplace("X-Reflected",
  7349. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7350. // Attacker-controlled name carrying CR/LF.
  7351. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7352. sink.done_with_trailer(trailer);
  7353. }
  7354. (*i)++;
  7355. return true;
  7356. },
  7357. [i](bool /*success*/) { delete i; });
  7358. });
  7359. thread t = thread([&] { svr.listen(HOST, PORT); });
  7360. auto se = detail::scope_exit([&] {
  7361. svr.stop();
  7362. t.join();
  7363. ASSERT_FALSE(svr.is_running());
  7364. });
  7365. svr.wait_until_ready();
  7366. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7367. "Host: " + HOST +
  7368. "\r\n"
  7369. "Connection: close\r\n"
  7370. "\r\n";
  7371. std::string res;
  7372. ASSERT_TRUE(send_request(5, req, &res));
  7373. // The injected fields must not appear anywhere in the raw response.
  7374. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7375. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7376. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7377. // Invalid trailers are dropped entirely, matching set_header().
  7378. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7379. // The valid trailer still passes through.
  7380. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7381. }
  7382. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7383. Server svr;
  7384. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7385. // res.headers is a public field an application can populate directly,
  7386. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7387. // A valid header that must survive.
  7388. res.headers.emplace("X-Safe", "safe");
  7389. // Attacker-controlled value carrying CR/LF (response splitting).
  7390. res.headers.emplace("X-Reflected",
  7391. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7392. // Attacker-controlled name carrying CR/LF.
  7393. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7394. res.set_content("body", "text/plain");
  7395. });
  7396. thread t = thread([&] { svr.listen(HOST, PORT); });
  7397. auto se = detail::scope_exit([&] {
  7398. svr.stop();
  7399. t.join();
  7400. ASSERT_FALSE(svr.is_running());
  7401. });
  7402. svr.wait_until_ready();
  7403. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7404. "Host: " + HOST +
  7405. "\r\n"
  7406. "Connection: close\r\n"
  7407. "\r\n";
  7408. std::string res;
  7409. ASSERT_TRUE(send_request(5, req, &res));
  7410. // The injected fields must not appear anywhere in the raw response.
  7411. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7412. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7413. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7414. // Invalid headers are dropped entirely, matching set_header().
  7415. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7416. // The valid header still passes through.
  7417. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7418. }
  7419. // Forward declaration: in split builds split.py strips `inline` and moves the
  7420. // definition into httplib.cc, so detail::write_request_line is not visible from
  7421. // the public httplib.h. Re-declaring it here lets the tests link against the
  7422. // symbol in both header-only and split builds.
  7423. namespace httplib {
  7424. namespace detail {
  7425. ssize_t write_request_line(Stream &strm, const std::string &method,
  7426. const std::string &path);
  7427. } // namespace detail
  7428. } // namespace httplib
  7429. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7430. // A well-formed target is written verbatim.
  7431. {
  7432. detail::BufferStream strm;
  7433. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7434. EXPECT_GT(n, 0);
  7435. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7436. }
  7437. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7438. // otherwise it splits the request line and injects a header or a whole
  7439. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7440. // when path encoding is disabled.
  7441. const std::string evil_targets[] = {
  7442. "/a\r\nInjected: pwned",
  7443. "/a\rInjected",
  7444. "/a\nInjected",
  7445. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7446. };
  7447. for (const auto &evil : evil_targets) {
  7448. detail::BufferStream strm;
  7449. auto n = detail::write_request_line(strm, "GET", evil);
  7450. EXPECT_LT(n, 0);
  7451. EXPECT_TRUE(strm.get_buffer().empty());
  7452. }
  7453. }
  7454. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7455. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7456. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7457. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7458. // client must fail cleanly with Error::Write instead of putting a
  7459. // request-line-less, header-injecting request on the wire.
  7460. Server svr;
  7461. svr.Get("/a", [](const Request &, Response &res) {
  7462. res.set_content("ok", "text/plain");
  7463. });
  7464. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7465. auto se = detail::scope_exit([&] {
  7466. svr.stop();
  7467. thread.join();
  7468. ASSERT_FALSE(svr.is_running());
  7469. });
  7470. svr.wait_until_ready();
  7471. {
  7472. Client cli(HOST, PORT);
  7473. cli.set_path_encode(false);
  7474. // The request is rejected before anything is written, so the connection
  7475. // stays silent and the subsequent response read would otherwise block for
  7476. // the full default read timeout. Shorten it -- the assertion is on the
  7477. // error, not the timeout.
  7478. cli.set_read_timeout(1, 0);
  7479. auto res = cli.Get("/a\r\nInjected: pwned");
  7480. EXPECT_FALSE(res);
  7481. EXPECT_EQ(Error::Write, res.error());
  7482. }
  7483. }
  7484. // Sends a raw request and verifies that there isn't a crash or exception.
  7485. static void test_raw_request(const std::string &req,
  7486. std::string *out = nullptr) {
  7487. Server svr;
  7488. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7489. res.set_content("ok", "text/plain");
  7490. });
  7491. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7492. res.set_content("ok", "text/plain");
  7493. });
  7494. svr.Get("/header_field_value_check",
  7495. [&](const Request & /*req*/, Response &res) {
  7496. res.set_content("ok", "text/plain");
  7497. });
  7498. // Server read timeout must be longer than the client read timeout for the
  7499. // bug to reproduce, probably to force the server to process a request
  7500. // without a trailing blank line.
  7501. const time_t client_read_timeout_sec = 1;
  7502. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7503. bool listen_thread_ok = false;
  7504. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7505. auto se = detail::scope_exit([&] {
  7506. svr.stop();
  7507. t.join();
  7508. ASSERT_FALSE(svr.is_running());
  7509. EXPECT_TRUE(listen_thread_ok);
  7510. });
  7511. svr.wait_until_ready();
  7512. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7513. }
  7514. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7515. // A certain header line causes an exception if the header property is parsed
  7516. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7517. test_raw_request(
  7518. "GET /hi HTTP/1.1\r\n"
  7519. " : "
  7520. " "
  7521. " ");
  7522. }
  7523. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7524. // A certain header line causes an exception if the header property *name* is
  7525. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7526. // greedy matcher and requires backtracking when there are a lot of ":"
  7527. // characters.
  7528. // This occurs with libc++ but not libstdc++.
  7529. test_raw_request(
  7530. "GET /hi HTTP/1.1\r\n"
  7531. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7532. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7533. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7534. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7535. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7536. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7537. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7538. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7539. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7540. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7541. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7542. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7543. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7544. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7545. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7546. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7547. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7548. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7549. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7550. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7551. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7552. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7553. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7554. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7555. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7556. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7557. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7558. "&&&%%%");
  7559. }
  7560. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7561. // Make sure this doesn't crash the server.
  7562. // In a previous version of the header line regex, the "\r" rendered the line
  7563. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7564. // a new position where the leading white space ended and the field value
  7565. // began.
  7566. // The crash occurs with libc++ but not libstdc++.
  7567. test_raw_request("GET /hi HTTP/1.1\r\n"
  7568. "a:" +
  7569. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7570. "\r\n"
  7571. "\r\n");
  7572. }
  7573. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7574. std::string out;
  7575. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7576. "Content-Type: text/plain\r\n"
  7577. "Transfer-Encoding: chunked\r\n"
  7578. "\r\n"
  7579. "nothex\r\n",
  7580. &out);
  7581. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7582. }
  7583. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7584. std::string out;
  7585. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7586. "Content-Type: text/plain\r\n"
  7587. "Transfer-Encoding: chunked\r\n"
  7588. "\r\n"
  7589. "3\r\n"
  7590. "xyz\r\n"
  7591. "NaN\r\n",
  7592. &out);
  7593. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7594. }
  7595. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7596. std::string out;
  7597. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7598. "Content-Type: text/plain\r\n"
  7599. "Transfer-Encoding: chunked\r\n"
  7600. "\r\n"
  7601. // Length is too large for 64 bits.
  7602. "1ffffffffffffffff\r\n"
  7603. "xyz\r\n",
  7604. &out);
  7605. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7606. }
  7607. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7608. test_raw_request("GET /hi HTTP/1.1\r\n"
  7609. "Content-Type: text/plain\r\n\r");
  7610. }
  7611. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7612. std::string out;
  7613. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7614. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7615. }
  7616. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7617. Server svr;
  7618. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7619. EXPECT_TRUE(!req.remote_addr.empty());
  7620. });
  7621. thread t = thread([&] { svr.listen(HOST, PORT); });
  7622. auto se = detail::scope_exit([&] {
  7623. svr.stop();
  7624. t.join();
  7625. ASSERT_FALSE(svr.is_running());
  7626. });
  7627. svr.wait_until_ready();
  7628. // Send an invalid request line to trigger Bad Request
  7629. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7630. std::string out;
  7631. ASSERT_TRUE(send_request(5, bad_req, &out));
  7632. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7633. }
  7634. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7635. std::string out;
  7636. std::string request(
  7637. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7638. test_raw_request(request, &out);
  7639. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7640. }
  7641. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7642. std::string out;
  7643. std::string request(
  7644. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7645. test_raw_request(request, &out);
  7646. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7647. }
  7648. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7649. std::string out;
  7650. std::string request(
  7651. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7652. test_raw_request(request, &out);
  7653. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7654. }
  7655. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7656. std::string out;
  7657. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7658. "Test: \r\n\r\n",
  7659. &out);
  7660. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7661. }
  7662. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7663. Server svr;
  7664. std::string x_custom;
  7665. std::string cookie;
  7666. std::string xff;
  7667. std::string x_unicode;
  7668. std::string x_iis;
  7669. svr.Get("/check", [&](const Request &req, Response &res) {
  7670. x_custom = req.get_header_value("X-Custom");
  7671. cookie = req.get_header_value("Cookie");
  7672. xff = req.get_header_value("X-Forwarded-For");
  7673. x_unicode = req.get_header_value("X-Unicode");
  7674. x_iis = req.get_header_value("X-IIS");
  7675. res.set_content("ok", "text/plain");
  7676. });
  7677. thread t = thread([&] { svr.listen(HOST, PORT); });
  7678. auto se = detail::scope_exit([&] {
  7679. svr.stop();
  7680. t.join();
  7681. ASSERT_FALSE(svr.is_running());
  7682. });
  7683. svr.wait_until_ready();
  7684. const std::string req = "GET /check HTTP/1.1\r\n"
  7685. "Host: localhost\r\n"
  7686. "X-Custom: a%0D%0AInjected: b\r\n"
  7687. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7688. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7689. "X-Unicode: %E3%81%82\r\n"
  7690. "X-IIS: %u00E9\r\n"
  7691. "Connection: close\r\n"
  7692. "\r\n";
  7693. std::string res;
  7694. ASSERT_TRUE(send_request(5, req, &res));
  7695. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7696. // Every value must be returned verbatim (wire form), with no decoding.
  7697. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7698. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7699. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7700. EXPECT_EQ("%E3%81%82", x_unicode);
  7701. EXPECT_EQ("%u00E9", x_iis);
  7702. }
  7703. // Applications that previously relied on automatic percent-decoding can
  7704. // reproduce the old behavior by explicitly calling decode_path_component()
  7705. // or, for RFC 3986 conformance, decode_uri_component().
  7706. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7707. Server svr;
  7708. std::string decoded;
  7709. svr.Get("/check", [&](const Request &req, Response &res) {
  7710. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7711. res.set_content("ok", "text/plain");
  7712. });
  7713. thread t = thread([&] { svr.listen(HOST, PORT); });
  7714. auto se = detail::scope_exit([&] {
  7715. svr.stop();
  7716. t.join();
  7717. ASSERT_FALSE(svr.is_running());
  7718. });
  7719. svr.wait_until_ready();
  7720. const std::string req = "GET /check HTTP/1.1\r\n"
  7721. "Host: localhost\r\n"
  7722. "X-Custom: hello%20world\r\n"
  7723. "Connection: close\r\n"
  7724. "\r\n";
  7725. std::string res;
  7726. ASSERT_TRUE(send_request(5, req, &res));
  7727. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7728. EXPECT_EQ("hello world", decoded);
  7729. }
  7730. // Regression test for #2033. Browsers send Referer values that include
  7731. // percent-encoded characters such as %0A inside the URL. Decoding the
  7732. // header value would either trip the post-decode CR/LF/NUL guard (the
  7733. // original bug, returning 400) or, after that guard was relaxed, silently
  7734. // store a literal LF — both unacceptable. The wire form must round-trip.
  7735. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7736. Server svr;
  7737. std::string referer;
  7738. svr.Get("/check", [&](const Request &req, Response &res) {
  7739. referer = req.get_header_value("Referer");
  7740. res.set_content("ok", "text/plain");
  7741. });
  7742. thread t = thread([&] { svr.listen(HOST, PORT); });
  7743. auto se = detail::scope_exit([&] {
  7744. svr.stop();
  7745. t.join();
  7746. ASSERT_FALSE(svr.is_running());
  7747. });
  7748. svr.wait_until_ready();
  7749. const std::string req = "GET /check HTTP/1.1\r\n"
  7750. "Host: localhost\r\n"
  7751. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7752. "Connection: close\r\n"
  7753. "\r\n";
  7754. std::string res;
  7755. ASSERT_TRUE(send_request(5, req, &res));
  7756. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7757. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7758. }
  7759. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7760. Server svr;
  7761. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7762. res.set_header("Cache-Control", "no-cache");
  7763. res.set_chunked_content_provider(
  7764. "text/event-stream", [](size_t offset, DataSink &sink) {
  7765. std::string s = "data:";
  7766. s += std::to_string(offset);
  7767. s += "\n\n";
  7768. auto ret = sink.write(s.data(), s.size());
  7769. EXPECT_TRUE(ret);
  7770. std::this_thread::sleep_for(std::chrono::seconds(1));
  7771. return true;
  7772. });
  7773. });
  7774. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7775. svr.wait_until_ready();
  7776. Client client(HOST, PORT);
  7777. const Headers headers = {{"Accept", "text/event-stream"}};
  7778. auto get_thread = std::thread([&client, &headers]() {
  7779. auto res = client.Get(
  7780. "/events", headers,
  7781. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7782. });
  7783. auto se = detail::scope_exit([&] {
  7784. svr.stop();
  7785. get_thread.join();
  7786. listen_thread.join();
  7787. ASSERT_FALSE(svr.is_running());
  7788. });
  7789. // Give GET time to get a few messages.
  7790. std::this_thread::sleep_for(std::chrono::seconds(2));
  7791. }
  7792. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7793. httplib::Server svr;
  7794. svr.Post("/hi",
  7795. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7796. res.status = StatusCode::OK_200;
  7797. });
  7798. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7799. svr.wait_until_ready();
  7800. Client cli(HOST, PORT);
  7801. auto res = cli.Post("/hi", "data", "text/plain");
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. EXPECT_EQ(StatusCode::OK_200, res->status);
  7804. svr.stop();
  7805. thread.join();
  7806. ASSERT_FALSE(svr.is_running());
  7807. res = cli.Post("/hi", "data", "text/plain");
  7808. ASSERT_FALSE(res);
  7809. }
  7810. TEST(ServerStopTest, ListenFailure) {
  7811. Server svr;
  7812. auto t = thread([&]() {
  7813. auto ret = svr.listen("????", PORT);
  7814. EXPECT_FALSE(ret);
  7815. });
  7816. svr.wait_until_ready();
  7817. svr.stop();
  7818. t.join();
  7819. }
  7820. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7821. TEST(ServerStopTest, Decommision) {
  7822. Server svr;
  7823. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7824. for (int i = 0; i < 4; i++) {
  7825. auto is_even = !(i % 2);
  7826. std::thread t{[&] {
  7827. try {
  7828. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7829. if (is_even) {
  7830. throw std::runtime_error("Some thing that happens to go wrong.");
  7831. }
  7832. svr.listen(HOST, PORT);
  7833. } catch (...) { svr.decommission(); }
  7834. }};
  7835. svr.wait_until_ready();
  7836. // Server is up
  7837. {
  7838. Client cli(HOST, PORT);
  7839. auto res = cli.Get("/hi");
  7840. if (is_even) {
  7841. EXPECT_FALSE(res);
  7842. } else {
  7843. EXPECT_TRUE(res);
  7844. EXPECT_EQ("hi...", res->body);
  7845. }
  7846. }
  7847. svr.stop();
  7848. t.join();
  7849. // Server is down...
  7850. {
  7851. Client cli(HOST, PORT);
  7852. auto res = cli.Get("/hi");
  7853. EXPECT_FALSE(res);
  7854. }
  7855. }
  7856. }
  7857. #endif
  7858. // Helper function for string body upload progress tests
  7859. template <typename SetupHandler, typename ClientCall>
  7860. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7861. ClientCall &&client_call,
  7862. const string &body) {
  7863. Server svr;
  7864. setup_handler(svr);
  7865. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7866. auto se = detail::scope_exit([&] {
  7867. svr.stop();
  7868. t.join();
  7869. });
  7870. svr.wait_until_ready();
  7871. Client cli(HOST, PORT);
  7872. vector<uint64_t> progress_values;
  7873. bool progress_called = false;
  7874. auto res =
  7875. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7876. progress_values.push_back(current);
  7877. progress_called = true;
  7878. return true;
  7879. });
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ(200, res->status);
  7882. EXPECT_TRUE(progress_called);
  7883. }
  7884. TEST(UploadProgressTest, PostStringBodyBasic) {
  7885. TestStringBodyUploadProgress(
  7886. [](Server &svr) {
  7887. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7888. res.set_content("received", "text/plain");
  7889. });
  7890. },
  7891. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7892. return cli.Post("/test", body, "text/plain", progress_callback);
  7893. },
  7894. "test data for upload progress");
  7895. }
  7896. TEST(UploadProgressTest, PutStringBodyBasic) {
  7897. TestStringBodyUploadProgress(
  7898. [](Server &svr) {
  7899. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7900. res.set_content("put received", "text/plain");
  7901. });
  7902. },
  7903. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7904. return cli.Put("/test", body, "text/plain", progress_callback);
  7905. },
  7906. "put test data for upload progress");
  7907. }
  7908. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7909. TestStringBodyUploadProgress(
  7910. [](Server &svr) {
  7911. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7912. res.set_content("patch received", "text/plain");
  7913. });
  7914. },
  7915. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7916. return cli.Patch("/test", body, "text/plain", progress_callback);
  7917. },
  7918. "patch test data for upload progress");
  7919. }
  7920. // Helper function for content provider upload progress tests
  7921. template <typename SetupHandler, typename ClientCall>
  7922. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7923. ClientCall &&client_call) {
  7924. Server svr;
  7925. setup_handler(svr);
  7926. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7927. auto se = detail::scope_exit([&] {
  7928. svr.stop();
  7929. t.join();
  7930. });
  7931. svr.wait_until_ready();
  7932. Client cli(HOST, PORT);
  7933. vector<uint64_t> progress_values;
  7934. auto res =
  7935. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7936. progress_values.push_back(current);
  7937. return true;
  7938. });
  7939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7940. EXPECT_EQ(200, res->status);
  7941. EXPECT_FALSE(progress_values.empty());
  7942. }
  7943. TEST(UploadProgressTest, PostContentProviderProgress) {
  7944. TestContentProviderUploadProgress(
  7945. [](Server &svr) {
  7946. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7947. res.set_content("provider received", "text/plain");
  7948. });
  7949. },
  7950. [](Client &cli, UploadProgress progress_callback) {
  7951. return cli.Post(
  7952. "/test", 10,
  7953. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7954. sink.os << "test data";
  7955. return true;
  7956. },
  7957. "text/plain", progress_callback);
  7958. });
  7959. }
  7960. // Helper function for multipart upload progress tests
  7961. template <typename SetupHandler, typename ClientCall>
  7962. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7963. ClientCall &&client_call,
  7964. const string &endpoint) {
  7965. Server svr;
  7966. setup_handler(svr);
  7967. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7968. auto se = detail::scope_exit([&] {
  7969. svr.stop();
  7970. t.join();
  7971. });
  7972. svr.wait_until_ready();
  7973. Client cli(HOST, PORT);
  7974. vector<uint64_t> progress_values;
  7975. UploadFormDataItems items = {
  7976. {"field1", "value1", "", ""},
  7977. {"field2", "longer value for progress tracking test", "", ""},
  7978. {"file1", "file content data for upload progress", "test.txt",
  7979. "text/plain"}};
  7980. auto res = client_call(cli, endpoint, items,
  7981. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7982. progress_values.push_back(current);
  7983. return true;
  7984. });
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ(200, res->status);
  7987. EXPECT_FALSE(progress_values.empty());
  7988. }
  7989. TEST(UploadProgressTest, PostMultipartProgress) {
  7990. TestMultipartUploadProgress(
  7991. [](Server &svr) {
  7992. svr.Post("/multipart", [](const Request &req, Response &res) {
  7993. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7994. res.set_content("multipart received", "text/plain");
  7995. });
  7996. },
  7997. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7998. UploadProgress progress_callback) {
  7999. return cli.Post(endpoint, items, progress_callback);
  8000. },
  8001. "/multipart");
  8002. }
  8003. // Helper function for basic download progress tests
  8004. template <typename SetupHandler, typename ClientCall>
  8005. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8006. ClientCall &&client_call, const string &endpoint,
  8007. size_t expected_content_size) {
  8008. Server svr;
  8009. setup_handler(svr);
  8010. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8011. auto se = detail::scope_exit([&] {
  8012. svr.stop();
  8013. t.join();
  8014. });
  8015. svr.wait_until_ready();
  8016. Client cli(HOST, PORT);
  8017. vector<uint64_t> progress_values;
  8018. auto res = client_call(cli, endpoint,
  8019. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8020. progress_values.push_back(current);
  8021. return true;
  8022. });
  8023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8024. EXPECT_EQ(200, res->status);
  8025. EXPECT_FALSE(progress_values.empty());
  8026. EXPECT_EQ(expected_content_size, res->body.size());
  8027. }
  8028. TEST(DownloadProgressTest, GetBasic) {
  8029. TestBasicDownloadProgress(
  8030. [](Server &svr) {
  8031. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8032. string content(1000, 'D');
  8033. res.set_content(content, "text/plain");
  8034. });
  8035. },
  8036. [](Client &cli, const string &endpoint,
  8037. DownloadProgress progress_callback) {
  8038. return cli.Get(endpoint, progress_callback);
  8039. },
  8040. "/download", 1000u);
  8041. }
  8042. // Helper function for content receiver download progress tests
  8043. template <typename SetupHandler, typename ClientCall>
  8044. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8045. ClientCall &&client_call,
  8046. const string &endpoint,
  8047. size_t expected_content_size) {
  8048. Server svr;
  8049. setup_handler(svr);
  8050. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8051. auto se = detail::scope_exit([&] {
  8052. svr.stop();
  8053. t.join();
  8054. });
  8055. svr.wait_until_ready();
  8056. Client cli(HOST, PORT);
  8057. vector<uint64_t> progress_values;
  8058. string received_body;
  8059. auto res = client_call(
  8060. cli, endpoint,
  8061. [&](const char *data, size_t data_length) -> bool {
  8062. received_body.append(data, data_length);
  8063. return true;
  8064. },
  8065. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8066. progress_values.push_back(current);
  8067. return true;
  8068. });
  8069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8070. EXPECT_EQ(200, res->status);
  8071. EXPECT_FALSE(progress_values.empty());
  8072. EXPECT_EQ(expected_content_size, received_body.size());
  8073. EXPECT_TRUE(res->body.empty());
  8074. }
  8075. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8076. TestContentReceiverDownloadProgress(
  8077. [](Server &svr) {
  8078. svr.Get("/download-receiver",
  8079. [](const Request & /*req*/, Response &res) {
  8080. string content(2000, 'R');
  8081. res.set_content(content, "text/plain");
  8082. });
  8083. },
  8084. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8085. DownloadProgress progress_callback) {
  8086. return cli.Get(endpoint, content_receiver, progress_callback);
  8087. },
  8088. "/download-receiver", 2000u);
  8089. }
  8090. TEST(StreamingTest, NoContentLengthStreaming) {
  8091. Server svr;
  8092. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8093. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8094. if (offset < 6) {
  8095. sink.os << (offset < 3 ? "a" : "b");
  8096. } else {
  8097. sink.done();
  8098. }
  8099. return true;
  8100. });
  8101. });
  8102. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8103. auto listen_se = detail::scope_exit([&] {
  8104. svr.stop();
  8105. listen_thread.join();
  8106. ASSERT_FALSE(svr.is_running());
  8107. });
  8108. svr.wait_until_ready();
  8109. Client client(HOST, PORT);
  8110. auto get_thread = std::thread([&client]() {
  8111. std::string s;
  8112. auto res =
  8113. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8114. s += std::string(data, len);
  8115. return true;
  8116. });
  8117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8118. EXPECT_EQ(StatusCode::OK_200, res->status);
  8119. EXPECT_EQ("aaabbb", s);
  8120. });
  8121. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8122. // Give GET time to get a few messages.
  8123. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8124. }
  8125. TEST(MountTest, Unmount) {
  8126. Server svr;
  8127. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8128. auto se = detail::scope_exit([&] {
  8129. svr.stop();
  8130. listen_thread.join();
  8131. ASSERT_FALSE(svr.is_running());
  8132. });
  8133. svr.wait_until_ready();
  8134. Client cli("localhost", PORT);
  8135. svr.set_mount_point("/mount2", "./www2");
  8136. auto res = cli.Get("/");
  8137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8138. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8139. res = cli.Get("/mount2/dir/test.html");
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ(StatusCode::OK_200, res->status);
  8142. svr.set_mount_point("/", "./www");
  8143. res = cli.Get("/dir/");
  8144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8145. EXPECT_EQ(StatusCode::OK_200, res->status);
  8146. svr.remove_mount_point("/");
  8147. res = cli.Get("/dir/");
  8148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8149. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8150. svr.remove_mount_point("/mount2");
  8151. res = cli.Get("/mount2/dir/test.html");
  8152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8153. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8154. }
  8155. TEST(MountTest, PathSegmentBoundary) {
  8156. Server svr;
  8157. svr.set_mount_point("/mount2", "./www2");
  8158. svr.set_mount_point("/", "./www");
  8159. auto port = svr.bind_to_any_port(HOST);
  8160. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8161. auto se = detail::scope_exit([&] {
  8162. svr.stop();
  8163. listen_thread.join();
  8164. ASSERT_FALSE(svr.is_running());
  8165. });
  8166. svr.wait_until_ready();
  8167. Client cli(HOST, port);
  8168. auto res = cli.Get("/mount2/dir/test.html");
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. EXPECT_EQ(StatusCode::OK_200, res->status);
  8171. // "/mount2" must not match part-way through a path segment.
  8172. res = cli.Get("/mount2dir/test.html");
  8173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8174. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8175. // A mount point ending in '/' keeps matching every path below it.
  8176. res = cli.Get("/dir/test.html");
  8177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8178. EXPECT_EQ(StatusCode::OK_200, res->status);
  8179. }
  8180. TEST(MountTest, Redicect) {
  8181. Server svr;
  8182. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8183. auto se = detail::scope_exit([&] {
  8184. svr.stop();
  8185. listen_thread.join();
  8186. ASSERT_FALSE(svr.is_running());
  8187. });
  8188. svr.set_mount_point("/", "./www");
  8189. svr.wait_until_ready();
  8190. Client cli("localhost", PORT);
  8191. auto res = cli.Get("/dir/");
  8192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. res = cli.Get("/dir");
  8195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8196. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8197. res = cli.Get("/file");
  8198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8199. EXPECT_EQ(StatusCode::OK_200, res->status);
  8200. res = cli.Get("/file/");
  8201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8202. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8203. cli.set_follow_location(true);
  8204. res = cli.Get("/dir");
  8205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8206. EXPECT_EQ(StatusCode::OK_200, res->status);
  8207. }
  8208. TEST(MountTest, MultibytesPathName) {
  8209. Server svr;
  8210. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8211. auto se = detail::scope_exit([&] {
  8212. svr.stop();
  8213. listen_thread.join();
  8214. ASSERT_FALSE(svr.is_running());
  8215. });
  8216. svr.set_mount_point("/", "./www");
  8217. svr.wait_until_ready();
  8218. Client cli("localhost", PORT);
  8219. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8221. EXPECT_EQ(StatusCode::OK_200, res->status);
  8222. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8223. }
  8224. #ifdef _WIN32
  8225. // Issue #2435: mmap::open() must succeed even when another handle holds
  8226. // the file open for writing (e.g. an active log file).
  8227. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8228. const char *path = "mmap_concurrent_writer_test.txt";
  8229. const char *content = "hello";
  8230. {
  8231. std::ofstream f(path, std::ios::binary);
  8232. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8233. }
  8234. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8235. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8236. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8237. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8238. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8239. detail::mmap m(path);
  8240. ASSERT_TRUE(m.is_open());
  8241. EXPECT_EQ(strlen(content), m.size());
  8242. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8243. }
  8244. #endif
  8245. #ifndef _WIN32
  8246. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8247. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8248. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8249. TEST(MmapTest, FailedMappingIsNotOpen) {
  8250. const char *path = "./mmap_failed_mapping_test_dir";
  8251. ASSERT_EQ(0, ::mkdir(path, 0755));
  8252. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8253. detail::mmap m(path);
  8254. EXPECT_FALSE(m.is_open());
  8255. EXPECT_EQ(0U, m.size());
  8256. EXPECT_NE(static_cast<const void *>(m.data()),
  8257. static_cast<const void *>(MAP_FAILED));
  8258. }
  8259. #endif
  8260. TEST(KeepAliveTest, ReadTimeout) {
  8261. Server svr;
  8262. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8263. std::this_thread::sleep_for(std::chrono::seconds(2));
  8264. res.set_content("a", "text/plain");
  8265. });
  8266. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8267. res.set_content("b", "text/plain");
  8268. });
  8269. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8270. auto se = detail::scope_exit([&] {
  8271. svr.stop();
  8272. listen_thread.join();
  8273. ASSERT_FALSE(svr.is_running());
  8274. });
  8275. svr.wait_until_ready();
  8276. Client cli("localhost", PORT);
  8277. cli.set_keep_alive(true);
  8278. cli.set_read_timeout(std::chrono::seconds(1));
  8279. auto resa = cli.Get("/a");
  8280. ASSERT_FALSE(resa);
  8281. EXPECT_EQ(Error::Read, resa.error());
  8282. auto resb = cli.Get("/b");
  8283. ASSERT_TRUE(resb);
  8284. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8285. EXPECT_EQ("b", resb->body);
  8286. }
  8287. TEST(KeepAliveTest, MaxCount) {
  8288. size_t keep_alive_max_count = 3;
  8289. Server svr;
  8290. svr.set_keep_alive_max_count(keep_alive_max_count);
  8291. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8292. res.set_content("Hello World!", "text/plain");
  8293. });
  8294. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8295. auto se = detail::scope_exit([&] {
  8296. svr.stop();
  8297. listen_thread.join();
  8298. ASSERT_FALSE(svr.is_running());
  8299. });
  8300. svr.wait_until_ready();
  8301. Client cli(HOST, PORT);
  8302. cli.set_keep_alive(true);
  8303. for (size_t i = 0; i < 5; i++) {
  8304. auto result = cli.Get("/hi");
  8305. ASSERT_TRUE(result);
  8306. EXPECT_EQ(StatusCode::OK_200, result->status);
  8307. if (i == keep_alive_max_count - 1) {
  8308. EXPECT_EQ("close", result->get_header_value("Connection"));
  8309. } else {
  8310. EXPECT_FALSE(result->has_header("Connection"));
  8311. }
  8312. }
  8313. }
  8314. TEST(KeepAliveTest, Issue1041) {
  8315. Server svr;
  8316. svr.set_keep_alive_timeout(3);
  8317. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8318. res.set_content("Hello World!", "text/plain");
  8319. });
  8320. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8321. auto se = detail::scope_exit([&] {
  8322. svr.stop();
  8323. listen_thread.join();
  8324. ASSERT_FALSE(svr.is_running());
  8325. });
  8326. svr.wait_until_ready();
  8327. Client cli(HOST, PORT);
  8328. cli.set_keep_alive(true);
  8329. auto result = cli.Get("/hi");
  8330. ASSERT_TRUE(result);
  8331. EXPECT_EQ(StatusCode::OK_200, result->status);
  8332. std::this_thread::sleep_for(std::chrono::seconds(5));
  8333. result = cli.Get("/hi");
  8334. ASSERT_TRUE(result);
  8335. EXPECT_EQ(StatusCode::OK_200, result->status);
  8336. }
  8337. TEST(KeepAliveTest, Issue1959) {
  8338. Server svr;
  8339. svr.set_keep_alive_timeout(5);
  8340. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8341. res.set_content("a", "text/plain");
  8342. });
  8343. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8344. auto se = detail::scope_exit([&] {
  8345. if (!svr.is_running()) return;
  8346. svr.stop();
  8347. listen_thread.join();
  8348. ASSERT_FALSE(svr.is_running());
  8349. });
  8350. svr.wait_until_ready();
  8351. Client cli("localhost", PORT);
  8352. cli.set_keep_alive(true);
  8353. using namespace std::chrono;
  8354. auto start = steady_clock::now();
  8355. cli.Get("/a");
  8356. svr.stop();
  8357. listen_thread.join();
  8358. auto end = steady_clock::now();
  8359. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8360. EXPECT_LT(elapsed, 5000);
  8361. }
  8362. #ifdef CPPHTTPLIB_SSL_ENABLED
  8363. TEST(KeepAliveTest, SSLClientReconnection) {
  8364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8365. ASSERT_TRUE(svr.is_valid());
  8366. svr.set_keep_alive_timeout(1);
  8367. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8368. res.set_content("Hello World!", "text/plain");
  8369. });
  8370. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8371. auto se = detail::scope_exit([&] {
  8372. svr.stop();
  8373. listen_thread.join();
  8374. ASSERT_FALSE(svr.is_running());
  8375. });
  8376. svr.wait_until_ready();
  8377. SSLClient cli(HOST, PORT);
  8378. cli.enable_server_certificate_verification(false);
  8379. cli.set_keep_alive(true);
  8380. auto result = cli.Get("/hi");
  8381. ASSERT_TRUE(result);
  8382. EXPECT_EQ(StatusCode::OK_200, result->status);
  8383. result = cli.Get("/hi");
  8384. ASSERT_TRUE(result);
  8385. EXPECT_EQ(StatusCode::OK_200, result->status);
  8386. std::this_thread::sleep_for(std::chrono::seconds(2));
  8387. // Recoonect
  8388. result = cli.Get("/hi");
  8389. ASSERT_TRUE(result);
  8390. EXPECT_EQ(StatusCode::OK_200, result->status);
  8391. result = cli.Get("/hi");
  8392. ASSERT_TRUE(result);
  8393. EXPECT_EQ(StatusCode::OK_200, result->status);
  8394. }
  8395. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8396. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8397. ASSERT_TRUE(svr.is_valid());
  8398. svr.set_keep_alive_timeout(1);
  8399. std::string content = "reconnect";
  8400. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8401. res.set_content("Hello World!", "text/plain");
  8402. });
  8403. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8404. auto se = detail::scope_exit([&] {
  8405. svr.stop();
  8406. listen_thread.join();
  8407. ASSERT_FALSE(svr.is_running());
  8408. });
  8409. svr.wait_until_ready();
  8410. SSLClient cli(HOST, PORT);
  8411. cli.enable_server_certificate_verification(false);
  8412. cli.set_keep_alive(true);
  8413. auto result = cli.Post(
  8414. "/hi", content.size(),
  8415. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8416. sink.write(content.c_str(), content.size());
  8417. return true;
  8418. },
  8419. "text/plain");
  8420. ASSERT_TRUE(result);
  8421. EXPECT_EQ(200, result->status);
  8422. std::this_thread::sleep_for(std::chrono::seconds(2));
  8423. // Recoonect
  8424. result = cli.Post(
  8425. "/hi", content.size(),
  8426. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8427. sink.write(content.c_str(), content.size());
  8428. return true;
  8429. },
  8430. "text/plain");
  8431. ASSERT_TRUE(result);
  8432. EXPECT_EQ(200, result->status);
  8433. result = cli.Post(
  8434. "/hi", content.size(),
  8435. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8436. sink.write(content.c_str(), content.size());
  8437. return true;
  8438. },
  8439. "text/plain");
  8440. ASSERT_TRUE(result);
  8441. EXPECT_EQ(200, result->status);
  8442. }
  8443. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8444. using namespace httplib::tls;
  8445. {
  8446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8447. ASSERT_TRUE(svr.is_valid());
  8448. svr.Get("/sni", [&](const Request &req, Response &res) {
  8449. std::string expected = req.sni();
  8450. EXPECT_EQ(expected, req.get_param_value("expected"));
  8451. res.set_content("ok", "text/plain");
  8452. });
  8453. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8454. auto se = detail::scope_exit([&] {
  8455. svr.stop();
  8456. listen_thread.join();
  8457. ASSERT_FALSE(svr.is_running());
  8458. });
  8459. svr.wait_until_ready();
  8460. {
  8461. SSLClient cli("localhost", PORT);
  8462. cli.enable_server_certificate_verification(false);
  8463. auto res = cli.Get("/sni?expected=localhost");
  8464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8465. }
  8466. {
  8467. SSLClient cli("::1", PORT);
  8468. cli.enable_server_certificate_verification(false);
  8469. auto res = cli.Get("/sni?expected=");
  8470. // NOTE: This may fail if the server is listening on IPv4 only
  8471. // (e.g., when localhost resolves to 127.0.0.1 only)
  8472. if (res) {
  8473. EXPECT_EQ(StatusCode::OK_200, res->status);
  8474. } else {
  8475. EXPECT_EQ(Error::Connection, res.error());
  8476. }
  8477. }
  8478. }
  8479. }
  8480. #endif
  8481. TEST(ClientProblemDetectionTest, ContentProvider) {
  8482. Server svr;
  8483. size_t content_length = 1024 * 1024;
  8484. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8485. res.set_content_provider(
  8486. content_length, "text/plain",
  8487. [&](size_t offset, size_t length, DataSink &sink) {
  8488. auto out_len = std::min(length, static_cast<size_t>(1024));
  8489. std::string out(out_len, '@');
  8490. sink.write(out.data(), out_len);
  8491. return offset < 4096;
  8492. },
  8493. [](bool success) { ASSERT_FALSE(success); });
  8494. });
  8495. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8496. res.set_content_provider(
  8497. 0, "text/plain",
  8498. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8499. EXPECT_TRUE(false);
  8500. return true;
  8501. },
  8502. [](bool success) { ASSERT_FALSE(success); });
  8503. });
  8504. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8505. auto se = detail::scope_exit([&] {
  8506. svr.stop();
  8507. listen_thread.join();
  8508. ASSERT_FALSE(svr.is_running());
  8509. });
  8510. svr.wait_until_ready();
  8511. Client cli("localhost", PORT);
  8512. {
  8513. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8514. size_t /*data_length*/) { return false; });
  8515. ASSERT_FALSE(res);
  8516. }
  8517. {
  8518. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8519. size_t /*data_length*/) { return false; });
  8520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8521. }
  8522. }
  8523. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8524. Server svr;
  8525. svr.set_error_handler([](Request const &, Response &res) -> void {
  8526. res.set_chunked_content_provider(
  8527. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8528. sink.os << "hello";
  8529. sink.os << "world";
  8530. sink.done();
  8531. return true;
  8532. });
  8533. });
  8534. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8535. auto se = detail::scope_exit([&] {
  8536. svr.stop();
  8537. listen_thread.join();
  8538. ASSERT_FALSE(svr.is_running());
  8539. });
  8540. svr.wait_until_ready();
  8541. Client cli("localhost", PORT);
  8542. auto res = cli.Get("/");
  8543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8544. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8545. EXPECT_EQ("helloworld", res->body);
  8546. }
  8547. TEST(LongPollingTest, ClientCloseDetection) {
  8548. Server svr;
  8549. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8550. res.set_chunked_content_provider(
  8551. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8552. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8553. sink.os << "hello";
  8554. auto count = 10;
  8555. while (count > 0 && sink.is_writable()) {
  8556. this_thread::sleep_for(chrono::milliseconds(10));
  8557. count--;
  8558. }
  8559. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8560. return true;
  8561. });
  8562. });
  8563. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8564. auto se = detail::scope_exit([&] {
  8565. svr.stop();
  8566. listen_thread.join();
  8567. ASSERT_FALSE(svr.is_running());
  8568. });
  8569. svr.wait_until_ready();
  8570. Client cli("localhost", PORT);
  8571. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8572. EXPECT_EQ("hello", string(data, data_length));
  8573. return false; // close the socket immediately.
  8574. });
  8575. ASSERT_FALSE(res);
  8576. }
  8577. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8578. Server svr;
  8579. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8580. res.set_chunked_content_provider(
  8581. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8582. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8583. sink.os << "hello";
  8584. EXPECT_TRUE(sink.os.good());
  8585. // Wait for the client to close the connection
  8586. auto count = 10;
  8587. while (count > 0 && sink.is_writable()) {
  8588. this_thread::sleep_for(chrono::milliseconds(10));
  8589. count--;
  8590. }
  8591. // After client disconnect, write repeatedly until the socket
  8592. // write actually fails (small writes may be absorbed by the
  8593. // kernel buffer)
  8594. std::string chunk(1024, 'x');
  8595. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8596. sink.os << chunk;
  8597. }
  8598. EXPECT_TRUE(sink.os.fail());
  8599. return true;
  8600. });
  8601. });
  8602. auto port = svr.bind_to_any_port("localhost");
  8603. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8604. auto se = detail::scope_exit([&] {
  8605. svr.stop();
  8606. listen_thread.join();
  8607. ASSERT_FALSE(svr.is_running());
  8608. });
  8609. svr.wait_until_ready();
  8610. Client cli("localhost", port);
  8611. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8612. EXPECT_EQ("hello", string(data, data_length));
  8613. return false; // close the socket immediately.
  8614. });
  8615. ASSERT_FALSE(res);
  8616. }
  8617. TEST(GetWithParametersTest, GetWithParameters) {
  8618. Server svr;
  8619. svr.Get("/", [&](const Request &req, Response &) {
  8620. EXPECT_EQ("world", req.get_param_value("hello"));
  8621. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8622. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8623. });
  8624. svr.Get("/params", [&](const Request &req, Response &) {
  8625. EXPECT_EQ("world", req.get_param_value("hello"));
  8626. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8627. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8628. });
  8629. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8630. EXPECT_EQ("resource-id", req.matches[1]);
  8631. EXPECT_EQ("foo", req.get_param_value("param1"));
  8632. EXPECT_EQ("bar", req.get_param_value("param2"));
  8633. });
  8634. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8635. EXPECT_EQ("user-id", req.path_params.at("id"));
  8636. EXPECT_EQ("foo", req.get_param_value("param1"));
  8637. EXPECT_EQ("bar", req.get_param_value("param2"));
  8638. });
  8639. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8640. auto se = detail::scope_exit([&] {
  8641. svr.stop();
  8642. listen_thread.join();
  8643. ASSERT_FALSE(svr.is_running());
  8644. });
  8645. svr.wait_until_ready();
  8646. {
  8647. Client cli(HOST, PORT);
  8648. Params params;
  8649. params.emplace("hello", "world");
  8650. params.emplace("hello2", "world2");
  8651. params.emplace("hello3", "world3");
  8652. auto res = cli.Get("/", params, Headers{});
  8653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8654. EXPECT_EQ(StatusCode::OK_200, res->status);
  8655. }
  8656. {
  8657. Client cli(HOST, PORT);
  8658. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8660. EXPECT_EQ(StatusCode::OK_200, res->status);
  8661. }
  8662. {
  8663. Client cli(HOST, PORT);
  8664. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8666. EXPECT_EQ(StatusCode::OK_200, res->status);
  8667. }
  8668. {
  8669. Client cli(HOST, PORT);
  8670. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8672. EXPECT_EQ(StatusCode::OK_200, res->status);
  8673. }
  8674. }
  8675. TEST(GetWithParametersTest, GetWithParameters2) {
  8676. Server svr;
  8677. svr.Get("/", [&](const Request &req, Response &res) {
  8678. auto text = req.get_param_value("hello");
  8679. res.set_content(text, "text/plain");
  8680. });
  8681. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8682. auto se = detail::scope_exit([&] {
  8683. svr.stop();
  8684. listen_thread.join();
  8685. ASSERT_FALSE(svr.is_running());
  8686. });
  8687. svr.wait_until_ready();
  8688. Client cli("localhost", PORT);
  8689. Params params;
  8690. params.emplace("hello", "world");
  8691. std::string body;
  8692. auto res = cli.Get("/", params, Headers{},
  8693. [&](const char *data, size_t data_length) {
  8694. body.append(data, data_length);
  8695. return true;
  8696. });
  8697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8698. EXPECT_EQ(StatusCode::OK_200, res->status);
  8699. EXPECT_EQ("world", body);
  8700. }
  8701. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8702. Server svr;
  8703. svr.Get("/search", [&](const Request &req, Response &res) {
  8704. auto q = req.get_param_value("q");
  8705. res.set_content(q, "text/plain");
  8706. });
  8707. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8708. auto se = detail::scope_exit([&] {
  8709. svr.stop();
  8710. listen_thread.join();
  8711. ASSERT_FALSE(svr.is_running());
  8712. });
  8713. svr.wait_until_ready();
  8714. Client cli("localhost", PORT);
  8715. // Verify that Get(path, params) works without requiring Headers argument
  8716. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8718. EXPECT_EQ(StatusCode::OK_200, res->status);
  8719. EXPECT_EQ("cpp-httplib", res->body);
  8720. }
  8721. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8722. auto host = "httpbingo.org";
  8723. auto path = std::string{"/range/32"};
  8724. #ifdef CPPHTTPLIB_SSL_ENABLED
  8725. SSLClient cli(host);
  8726. #else
  8727. Client cli(host);
  8728. #endif
  8729. cli.set_default_headers({make_range_header({{1, 10}})});
  8730. cli.set_connection_timeout(5);
  8731. {
  8732. auto res = cli.Get(path);
  8733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8734. EXPECT_EQ("bcdefghijk", res->body);
  8735. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8736. }
  8737. {
  8738. auto res = cli.Get(path);
  8739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8740. EXPECT_EQ("bcdefghijk", res->body);
  8741. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8742. }
  8743. }
  8744. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8745. Server svr;
  8746. svr.set_default_headers({{"Hello", "World"}});
  8747. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8748. res.set_content("ok", "text/plain");
  8749. });
  8750. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8751. auto se = detail::scope_exit([&] {
  8752. svr.stop();
  8753. listen_thread.join();
  8754. ASSERT_FALSE(svr.is_running());
  8755. });
  8756. svr.wait_until_ready();
  8757. Client cli("localhost", PORT);
  8758. auto res = cli.Get("/");
  8759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8760. EXPECT_EQ(StatusCode::OK_200, res->status);
  8761. EXPECT_EQ("ok", res->body);
  8762. EXPECT_EQ("World", res->get_header_value("Hello"));
  8763. }
  8764. #ifdef CPPHTTPLIB_SSL_ENABLED
  8765. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8766. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8767. ASSERT_TRUE(svr.is_valid());
  8768. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8769. std::this_thread::sleep_for(std::chrono::seconds(2));
  8770. res.set_content("a", "text/plain");
  8771. });
  8772. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8773. res.set_content("b", "text/plain");
  8774. });
  8775. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8776. auto se = detail::scope_exit([&] {
  8777. svr.stop();
  8778. listen_thread.join();
  8779. ASSERT_FALSE(svr.is_running());
  8780. });
  8781. svr.wait_until_ready();
  8782. SSLClient cli("localhost", PORT);
  8783. cli.enable_server_certificate_verification(false);
  8784. cli.set_keep_alive(true);
  8785. cli.set_read_timeout(std::chrono::seconds(1));
  8786. auto resa = cli.Get("/a");
  8787. ASSERT_TRUE(!resa);
  8788. EXPECT_EQ(Error::Read, resa.error());
  8789. auto resb = cli.Get("/b");
  8790. ASSERT_TRUE(resb);
  8791. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8792. EXPECT_EQ("b", resb->body);
  8793. }
  8794. #endif
  8795. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8796. protected:
  8797. ServerTestWithAI_PASSIVE()
  8798. : cli_(HOST, PORT)
  8799. #ifdef CPPHTTPLIB_SSL_ENABLED
  8800. ,
  8801. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8802. #endif
  8803. {
  8804. #ifdef CPPHTTPLIB_SSL_ENABLED
  8805. cli_.enable_server_certificate_verification(false);
  8806. #endif
  8807. }
  8808. virtual void SetUp() {
  8809. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8810. res.set_content("Hello World!", "text/plain");
  8811. });
  8812. t_ = thread(
  8813. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8814. svr_.wait_until_ready();
  8815. }
  8816. virtual void TearDown() {
  8817. svr_.stop();
  8818. t_.join();
  8819. }
  8820. #ifdef CPPHTTPLIB_SSL_ENABLED
  8821. SSLClient cli_;
  8822. SSLServer svr_;
  8823. #else
  8824. Client cli_;
  8825. Server svr_;
  8826. #endif
  8827. thread t_;
  8828. };
  8829. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8830. auto res = cli_.Get("/hi");
  8831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8832. EXPECT_EQ(StatusCode::OK_200, res->status);
  8833. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8834. EXPECT_EQ("Hello World!", res->body);
  8835. }
  8836. class ServerUpDownTest : public ::testing::Test {
  8837. protected:
  8838. ServerUpDownTest() : cli_(HOST, PORT) {}
  8839. virtual void SetUp() {
  8840. t_ = thread([&]() {
  8841. svr_.bind_to_any_port(HOST);
  8842. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8843. ASSERT_TRUE(svr_.listen_after_bind());
  8844. });
  8845. svr_.wait_until_ready();
  8846. }
  8847. virtual void TearDown() {
  8848. svr_.stop();
  8849. t_.join();
  8850. }
  8851. Client cli_;
  8852. Server svr_;
  8853. thread t_;
  8854. };
  8855. TEST_F(ServerUpDownTest, QuickStartStop) {
  8856. // Should not crash, especially when run with
  8857. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8858. }
  8859. class PayloadMaxLengthTest : public ::testing::Test {
  8860. protected:
  8861. PayloadMaxLengthTest()
  8862. : cli_(HOST, PORT)
  8863. #ifdef CPPHTTPLIB_SSL_ENABLED
  8864. ,
  8865. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8866. #endif
  8867. {
  8868. #ifdef CPPHTTPLIB_SSL_ENABLED
  8869. cli_.enable_server_certificate_verification(false);
  8870. #endif
  8871. }
  8872. virtual void SetUp() {
  8873. svr_.set_payload_max_length(8);
  8874. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8875. res.set_content("test", "text/plain");
  8876. });
  8877. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8878. svr_.wait_until_ready();
  8879. }
  8880. virtual void TearDown() {
  8881. svr_.stop();
  8882. t_.join();
  8883. }
  8884. #ifdef CPPHTTPLIB_SSL_ENABLED
  8885. SSLClient cli_;
  8886. SSLServer svr_;
  8887. #else
  8888. Client cli_;
  8889. Server svr_;
  8890. #endif
  8891. thread t_;
  8892. };
  8893. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8894. auto res = cli_.Post("/test", "123456789", "text/plain");
  8895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8896. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8897. res = cli_.Post("/test", "12345678", "text/plain");
  8898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. }
  8901. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8902. // Test chunked encoding with payload exceeding the 8-byte limit
  8903. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8904. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8906. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8907. }
  8908. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8909. // Test chunked encoding with payload within the 8-byte limit
  8910. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8911. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8913. EXPECT_EQ(StatusCode::OK_200, res->status);
  8914. }
  8915. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8916. // Test using send_request to send chunked data exceeding payload limit
  8917. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8918. "Host: " +
  8919. std::string(HOST) + ":" + std::to_string(PORT) +
  8920. "\r\n"
  8921. "Transfer-Encoding: chunked\r\n"
  8922. "Connection: close\r\n"
  8923. "\r\n"
  8924. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8925. "0123456789\r\n"
  8926. "0\r\n" // End chunk
  8927. "\r\n";
  8928. std::string response;
  8929. bool result = send_request(1, chunked_request, &response);
  8930. if (!result) {
  8931. // If send_request fails, it might be because the server closed the
  8932. // connection due to payload limit enforcement, which is acceptable
  8933. SUCCEED()
  8934. << "Server rejected oversized chunked request (connection closed)";
  8935. } else {
  8936. // If we got a response, check if it's an error response or connection was
  8937. // closed early Short response length indicates connection was closed due to
  8938. // payload limit
  8939. if (response.length() <= 10) {
  8940. SUCCEED() << "Server closed connection for oversized chunked request";
  8941. } else {
  8942. // Check for error status codes
  8943. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8944. response.find("Payload Too Large") != std::string::npos ||
  8945. response.find("400") != std::string::npos);
  8946. }
  8947. }
  8948. }
  8949. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8950. // Test request without Content-Length header exceeding payload limit
  8951. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8952. "Host: " +
  8953. std::string(HOST) + ":" +
  8954. std::to_string(PORT) +
  8955. "\r\n"
  8956. "Connection: close\r\n"
  8957. "\r\n";
  8958. // Add payload exceeding the 8-byte limit
  8959. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8960. request_without_content_length += large_payload;
  8961. std::string response;
  8962. bool result = send_request(1, request_without_content_length, &response);
  8963. if (!result) {
  8964. // If send_request fails, server likely closed connection due to payload
  8965. // limit
  8966. SUCCEED() << "Server rejected oversized request without Content-Length "
  8967. "(connection closed)";
  8968. } else {
  8969. // Check if server responded with error or closed connection early
  8970. if (response.length() <= 10) {
  8971. SUCCEED() << "Server closed connection for oversized request without "
  8972. "Content-Length";
  8973. } else {
  8974. // Check for error status codes
  8975. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8976. response.find("Payload Too Large") != std::string::npos ||
  8977. response.find("400") != std::string::npos);
  8978. }
  8979. }
  8980. }
  8981. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8982. // Test request without Content-Length header within payload limit
  8983. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8984. "Host: " +
  8985. std::string(HOST) + ":" +
  8986. std::to_string(PORT) +
  8987. "\r\n"
  8988. "Connection: close\r\n"
  8989. "\r\n";
  8990. // Add payload within the 8-byte limit
  8991. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8992. request_without_content_length += small_payload;
  8993. std::string response;
  8994. bool result = send_request(1, request_without_content_length, &response);
  8995. // For requests without Content-Length, the server may have different behavior
  8996. // The key is that it should not reject due to payload limit for small
  8997. // payloads
  8998. if (result) {
  8999. // Check for any HTTP response (success or error, but not connection closed)
  9000. if (response.length() > 10) {
  9001. SUCCEED()
  9002. << "Server processed request without Content-Length within limit";
  9003. } else {
  9004. // Short response might indicate connection closed, which is acceptable
  9005. SUCCEED() << "Server closed connection for request without "
  9006. "Content-Length (acceptable behavior)";
  9007. }
  9008. } else {
  9009. // Connection failure might be due to protocol requirements
  9010. SUCCEED() << "Connection issue with request without Content-Length "
  9011. "(environment-specific)";
  9012. }
  9013. }
  9014. class LargePayloadMaxLengthTest : public ::testing::Test {
  9015. protected:
  9016. LargePayloadMaxLengthTest()
  9017. : cli_(HOST, PORT)
  9018. #ifdef CPPHTTPLIB_SSL_ENABLED
  9019. ,
  9020. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9021. #endif
  9022. {
  9023. #ifdef CPPHTTPLIB_SSL_ENABLED
  9024. cli_.enable_server_certificate_verification(false);
  9025. #endif
  9026. }
  9027. virtual void SetUp() {
  9028. // Set 10MB payload limit
  9029. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9030. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9031. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9032. res.set_content("Large payload test", "text/plain");
  9033. });
  9034. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9035. svr_.wait_until_ready();
  9036. }
  9037. virtual void TearDown() {
  9038. svr_.stop();
  9039. t_.join();
  9040. }
  9041. #ifdef CPPHTTPLIB_SSL_ENABLED
  9042. SSLClient cli_;
  9043. SSLServer svr_;
  9044. #else
  9045. Client cli_;
  9046. Server svr_;
  9047. #endif
  9048. thread t_;
  9049. };
  9050. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9051. // Test chunked encoding with payload within 10MB limit
  9052. std::string medium_payload(5 * 1024 * 1024,
  9053. 'A'); // 5MB payload, within 10MB limit
  9054. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9056. EXPECT_EQ(StatusCode::OK_200, res->status);
  9057. }
  9058. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9059. // Test chunked encoding with payload exceeding 10MB limit
  9060. std::string large_payload(12 * 1024 * 1024,
  9061. 'B'); // 12MB payload, exceeds 10MB limit
  9062. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9063. // Server may either return 413 or close the connection
  9064. if (res) {
  9065. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9066. } else {
  9067. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9068. }
  9069. }
  9070. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9071. // Test request without Content-Length header within 10MB limit
  9072. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9073. "Host: " +
  9074. std::string(HOST) + ":" +
  9075. std::to_string(PORT) +
  9076. "\r\n"
  9077. "Connection: close\r\n"
  9078. "\r\n";
  9079. // Add 1MB payload (within 10MB limit)
  9080. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9081. request_without_content_length += medium_payload;
  9082. std::string response;
  9083. bool result = send_request(5, request_without_content_length, &response);
  9084. if (result) {
  9085. // Should get a proper HTTP response for payloads within limit
  9086. if (response.length() > 10) {
  9087. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9088. "10MB limit";
  9089. } else {
  9090. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9091. "Content-Length)";
  9092. }
  9093. } else {
  9094. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9095. }
  9096. }
  9097. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9098. // Test request without Content-Length header exceeding 10MB limit
  9099. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9100. "Host: " +
  9101. std::string(HOST) + ":" +
  9102. std::to_string(PORT) +
  9103. "\r\n"
  9104. "Connection: close\r\n"
  9105. "\r\n";
  9106. // Add 12MB payload (exceeds 10MB limit)
  9107. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9108. request_without_content_length += large_payload;
  9109. std::string response;
  9110. bool result = send_request(10, request_without_content_length, &response);
  9111. if (!result) {
  9112. // Server should close connection due to payload limit
  9113. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9114. "(connection closed)";
  9115. } else {
  9116. // Check for error response
  9117. if (response.length() <= 10) {
  9118. SUCCEED()
  9119. << "Server closed connection for 12MB request exceeding 10MB limit";
  9120. } else {
  9121. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9122. response.find("Payload Too Large") != std::string::npos ||
  9123. response.find("400") != std::string::npos);
  9124. }
  9125. }
  9126. }
  9127. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9128. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9129. // path.
  9130. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9131. Server svr;
  9132. const size_t LIMIT = 64 * 1024; // 64KB
  9133. svr.set_payload_max_length(LIMIT);
  9134. size_t total = 0;
  9135. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9136. const ContentReader &content_reader) {
  9137. content_reader([&](const char * /*data*/, size_t len) {
  9138. total += len;
  9139. return true;
  9140. });
  9141. res.status = 200;
  9142. res.set_content("stream_ok", "text/plain");
  9143. });
  9144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9145. auto se = detail::scope_exit([&] {
  9146. svr.stop();
  9147. thread.join();
  9148. ASSERT_FALSE(svr.is_running());
  9149. });
  9150. svr.wait_until_ready();
  9151. // Prepare 256KB raw data and gzip-compress it
  9152. std::string raw(256 * 1024, 'A');
  9153. std::string gz;
  9154. {
  9155. z_stream zs{};
  9156. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9157. Z_DEFAULT_STRATEGY);
  9158. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9159. zs.avail_in = static_cast<uInt>(raw.size());
  9160. char outbuf[4096];
  9161. int ret;
  9162. do {
  9163. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9164. zs.avail_out = sizeof(outbuf);
  9165. ret = deflate(&zs, Z_FINISH);
  9166. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9167. } while (ret != Z_STREAM_END);
  9168. deflateEnd(&zs);
  9169. }
  9170. Client cli(HOST, PORT);
  9171. cli.set_connection_timeout(std::chrono::seconds(5));
  9172. Headers headers = {{"Content-Encoding", "gzip"}};
  9173. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9174. "application/octet-stream");
  9175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9176. // Server must reject oversized decompressed payloads with 413.
  9177. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9178. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9179. EXPECT_LE(total, LIMIT);
  9180. }
  9181. #ifndef CPPHTTPLIB_SSL_ENABLED
  9182. // For a request with neither Content-Length nor Transfer-Encoding, the
  9183. // non-SSL raw-socket fallback in read_content_core() used to hand the
  9184. // compressed wire bytes straight to the ContentReader without ever routing
  9185. // them through the decompressor, so payload_max_length_ only bounded the
  9186. // compressed size on the wire, not the decompressed size.
  9187. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  9188. Server svr;
  9189. const size_t LIMIT = 64 * 1024; // 64KB
  9190. svr.set_payload_max_length(LIMIT);
  9191. size_t total = 0;
  9192. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9193. const ContentReader &content_reader) {
  9194. content_reader([&](const char * /*data*/, size_t len) {
  9195. total += len;
  9196. return true;
  9197. });
  9198. res.status = 200;
  9199. res.set_content("stream_ok", "text/plain");
  9200. });
  9201. auto port = svr.bind_to_any_port(HOST);
  9202. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9203. auto se = detail::scope_exit([&] {
  9204. svr.stop();
  9205. thread.join();
  9206. ASSERT_FALSE(svr.is_running());
  9207. });
  9208. svr.wait_until_ready();
  9209. // Prepare 256KB raw data and gzip-compress it, same payload as the
  9210. // StreamingGzipDecompression test above.
  9211. std::string raw(256 * 1024, 'A');
  9212. std::string gz;
  9213. {
  9214. httplib::detail::gzip_compressor compressor;
  9215. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  9216. [&](const char *chunk, size_t len) {
  9217. gz.append(chunk, len);
  9218. return true;
  9219. });
  9220. ASSERT_TRUE(result);
  9221. }
  9222. // Send the gzip body over raw TCP with neither Content-Length nor
  9223. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  9224. // kicks in.
  9225. std::string req = "POST /stream HTTP/1.1\r\n"
  9226. "Host: " +
  9227. std::string(HOST) + ":" + std::to_string(port) +
  9228. "\r\n"
  9229. "Content-Encoding: gzip\r\n"
  9230. "Connection: close\r\n"
  9231. "\r\n" +
  9232. gz;
  9233. std::string response;
  9234. ASSERT_TRUE(send_request(5, req, &response, port));
  9235. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9236. EXPECT_LE(total, LIMIT);
  9237. }
  9238. #endif
  9239. #endif
  9240. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9241. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9242. // the payload must be passed through untouched instead of being rejected.
  9243. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9244. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9245. Server svr;
  9246. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9247. res.set_content(body, "image/jpeg");
  9248. res.set_header("Content-Encoding", "UTF-8");
  9249. });
  9250. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9251. res.set_content(body, "image/jpeg");
  9252. res.set_header("Content-Encoding", "identity");
  9253. });
  9254. svr.Post("/echo", [](const Request &req, Response &res) {
  9255. res.set_content(req.body, "image/jpeg");
  9256. });
  9257. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9258. auto se = detail::scope_exit([&] {
  9259. svr.stop();
  9260. t.join();
  9261. ASSERT_FALSE(svr.is_running());
  9262. });
  9263. svr.wait_until_ready();
  9264. Client cli(HOST, PORT);
  9265. {
  9266. auto res = cli.Get("/image");
  9267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9268. EXPECT_EQ(StatusCode::OK_200, res->status);
  9269. EXPECT_EQ(body, res->body);
  9270. }
  9271. {
  9272. auto res = cli.Get("/identity");
  9273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9274. EXPECT_EQ(StatusCode::OK_200, res->status);
  9275. EXPECT_EQ(body, res->body);
  9276. }
  9277. {
  9278. // The same applies to a request body reaching the server.
  9279. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9280. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9282. EXPECT_EQ(StatusCode::OK_200, res->status);
  9283. EXPECT_EQ(body, res->body);
  9284. }
  9285. }
  9286. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9287. // gzip-encoded response even when the build has no zlib support.
  9288. static const char GZIPPED_HELLO_WORLD[] = {
  9289. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9290. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9291. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9292. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9293. // A content coding cpp-httplib recognizes but was not built with must be
  9294. // reported as such. Handing the still-compressed payload back to the caller
  9295. // would silently corrupt it.
  9296. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9297. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9298. Server svr;
  9299. // "image/jpeg" keeps the server from applying a content coding of its own,
  9300. // so the hand-crafted Content-Encoding below survives.
  9301. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9302. res.set_content(gzipped, "image/jpeg");
  9303. res.set_header("Content-Encoding", "gzip");
  9304. });
  9305. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9306. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9307. res.set_content(gzipped, "image/jpeg");
  9308. res.set_header("Content-Encoding", "GZIP");
  9309. });
  9310. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9311. auto se = detail::scope_exit([&] {
  9312. svr.stop();
  9313. t.join();
  9314. ASSERT_FALSE(svr.is_running());
  9315. });
  9316. svr.wait_until_ready();
  9317. Client cli(HOST, PORT);
  9318. {
  9319. auto res = cli.Get("/gzipped");
  9320. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9322. EXPECT_EQ("Hello World!", res->body);
  9323. #else
  9324. ASSERT_FALSE(res);
  9325. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9326. #endif
  9327. }
  9328. {
  9329. // open_stream() must behave the same way.
  9330. auto handle = cli.open_stream("GET", "/gzipped");
  9331. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9332. ASSERT_TRUE(handle.is_valid());
  9333. std::string received;
  9334. char buf[256];
  9335. ssize_t n;
  9336. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9337. received.append(buf, static_cast<size_t>(n));
  9338. }
  9339. EXPECT_EQ("Hello World!", received);
  9340. #else
  9341. EXPECT_FALSE(handle.is_valid());
  9342. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9343. #endif
  9344. }
  9345. {
  9346. // A differently-cased coding must not be mistaken for an unknown one, or
  9347. // the body would be handed back still compressed.
  9348. auto res = cli.Get("/gzipped-uppercase");
  9349. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9351. EXPECT_EQ("Hello World!", res->body);
  9352. #else
  9353. ASSERT_FALSE(res);
  9354. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9355. #endif
  9356. }
  9357. }
  9358. // Regression test for DoS vulnerability: a malicious server sending a response
  9359. // without Content-Length header must not cause unbounded memory consumption on
  9360. // the client side. The client should stop reading after a reasonable limit,
  9361. // similar to the server-side set_payload_max_length protection.
  9362. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9363. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9364. #ifndef _WIN32
  9365. signal(SIGPIPE, SIG_IGN);
  9366. #endif
  9367. auto server_thread = std::thread([] {
  9368. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9369. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9370. default_socket_options(srv);
  9371. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9372. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9373. sockaddr_in addr{};
  9374. addr.sin_family = AF_INET;
  9375. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9376. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9377. int opt = 1;
  9378. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9379. #ifdef _WIN32
  9380. reinterpret_cast<const char *>(&opt),
  9381. #else
  9382. &opt,
  9383. #endif
  9384. sizeof(opt));
  9385. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9386. ::listen(srv, 1);
  9387. sockaddr_in cli_addr{};
  9388. socklen_t cli_len = sizeof(cli_addr);
  9389. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9390. if (cli != INVALID_SOCKET) {
  9391. char buf[4096];
  9392. ::recv(cli, buf, sizeof(buf), 0);
  9393. // Malicious response: no Content-Length, no chunked encoding
  9394. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9395. "Connection: close\r\n"
  9396. "\r\n";
  9397. ::send(cli,
  9398. #ifdef _WIN32
  9399. static_cast<const char *>(response_header.c_str()),
  9400. static_cast<int>(response_header.size()),
  9401. #else
  9402. response_header.c_str(), response_header.size(),
  9403. #endif
  9404. 0);
  9405. // Send 10MB of data
  9406. std::string chunk(64 * 1024, 'A');
  9407. size_t total_sent = 0;
  9408. while (total_sent < MALICIOUS_DATA_SIZE) {
  9409. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9410. auto sent = ::send(cli,
  9411. #ifdef _WIN32
  9412. static_cast<const char *>(chunk.c_str()),
  9413. static_cast<int>(to_send),
  9414. #else
  9415. chunk.c_str(), to_send,
  9416. #endif
  9417. 0);
  9418. if (sent <= 0) break;
  9419. total_sent += static_cast<size_t>(sent);
  9420. }
  9421. detail::close_socket(cli);
  9422. }
  9423. detail::close_socket(srv);
  9424. });
  9425. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9426. size_t total_read = 0;
  9427. {
  9428. Client cli("127.0.0.1", PORT + 2);
  9429. cli.set_read_timeout(5, 0);
  9430. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9431. auto stream = cli.open_stream("GET", "/malicious");
  9432. ASSERT_TRUE(stream.is_valid());
  9433. char buffer[64 * 1024];
  9434. ssize_t n;
  9435. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9436. total_read += static_cast<size_t>(n);
  9437. }
  9438. } // StreamHandle and Client destroyed here, closing the socket
  9439. server_thread.join();
  9440. // With set_payload_max_length, the client must stop reading before consuming
  9441. // all 10MB. The read loop should be cut off at or near the configured limit.
  9442. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9443. << "Client read " << total_read << " bytes, exceeding the configured "
  9444. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9445. }
  9446. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9447. // the entire response body without truncation.
  9448. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9449. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9450. #ifndef _WIN32
  9451. signal(SIGPIPE, SIG_IGN);
  9452. #endif
  9453. auto server_thread = std::thread([] {
  9454. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9455. default_socket_options(srv);
  9456. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9457. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9458. sockaddr_in addr{};
  9459. addr.sin_family = AF_INET;
  9460. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9461. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9462. int opt = 1;
  9463. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9464. #ifdef _WIN32
  9465. reinterpret_cast<const char *>(&opt),
  9466. #else
  9467. &opt,
  9468. #endif
  9469. sizeof(opt));
  9470. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9471. ::listen(srv, 1);
  9472. sockaddr_in cli_addr{};
  9473. socklen_t cli_len = sizeof(cli_addr);
  9474. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9475. if (cli != INVALID_SOCKET) {
  9476. char buf[4096];
  9477. ::recv(cli, buf, sizeof(buf), 0);
  9478. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9479. "Connection: close\r\n"
  9480. "\r\n";
  9481. ::send(cli,
  9482. #ifdef _WIN32
  9483. static_cast<const char *>(response_header.c_str()),
  9484. static_cast<int>(response_header.size()),
  9485. #else
  9486. response_header.c_str(), response_header.size(),
  9487. #endif
  9488. 0);
  9489. std::string chunk(64 * 1024, 'A');
  9490. size_t total_sent = 0;
  9491. while (total_sent < DATA_SIZE) {
  9492. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9493. auto sent = ::send(cli,
  9494. #ifdef _WIN32
  9495. static_cast<const char *>(chunk.c_str()),
  9496. static_cast<int>(to_send),
  9497. #else
  9498. chunk.c_str(), to_send,
  9499. #endif
  9500. 0);
  9501. if (sent <= 0) break;
  9502. total_sent += static_cast<size_t>(sent);
  9503. }
  9504. #ifdef _WIN32
  9505. ::shutdown(cli, SD_SEND);
  9506. #else
  9507. ::shutdown(cli, SHUT_WR);
  9508. #endif
  9509. // Drain until the client closes its end, ensuring all data is delivered
  9510. char drain[1024];
  9511. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9512. detail::close_socket(cli);
  9513. }
  9514. detail::close_socket(srv);
  9515. });
  9516. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9517. size_t total_read = 0;
  9518. {
  9519. Client cli("127.0.0.1", PORT + 2);
  9520. cli.set_read_timeout(5, 0);
  9521. cli.set_payload_max_length(0); // 0 means no limit
  9522. auto stream = cli.open_stream("GET", "/data");
  9523. ASSERT_TRUE(stream.is_valid());
  9524. char buffer[64 * 1024];
  9525. ssize_t n;
  9526. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9527. total_read += static_cast<size_t>(n);
  9528. }
  9529. }
  9530. server_thread.join();
  9531. EXPECT_EQ(total_read, DATA_SIZE)
  9532. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9533. << " bytes without truncation, but only read " << total_read << " bytes.";
  9534. }
  9535. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9536. // enormous Content-Length must not cause the client to pre-allocate a huge
  9537. // response body buffer. The reservation is capped at payload_max_length_, and
  9538. // the read itself fails when the body exceeds the limit.
  9539. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9540. #ifndef _WIN32
  9541. signal(SIGPIPE, SIG_IGN);
  9542. #endif
  9543. auto server_thread = std::thread([] {
  9544. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9545. default_socket_options(srv);
  9546. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9547. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9548. sockaddr_in addr{};
  9549. addr.sin_family = AF_INET;
  9550. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9551. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9552. int opt = 1;
  9553. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9554. #ifdef _WIN32
  9555. reinterpret_cast<const char *>(&opt),
  9556. #else
  9557. &opt,
  9558. #endif
  9559. sizeof(opt));
  9560. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9561. ::listen(srv, 1);
  9562. sockaddr_in cli_addr{};
  9563. socklen_t cli_len = sizeof(cli_addr);
  9564. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9565. if (cli != INVALID_SOCKET) {
  9566. char buf[4096];
  9567. ::recv(cli, buf, sizeof(buf), 0);
  9568. // Malicious response: claim a 20GB body but send only a tiny payload.
  9569. std::string response = "HTTP/1.1 200 OK\r\n"
  9570. "Content-Length: 20000000000\r\n"
  9571. "\r\n"
  9572. "abc";
  9573. ::send(cli,
  9574. #ifdef _WIN32
  9575. static_cast<const char *>(response.c_str()),
  9576. static_cast<int>(response.size()),
  9577. #else
  9578. response.c_str(), response.size(),
  9579. #endif
  9580. 0);
  9581. detail::close_socket(cli);
  9582. }
  9583. detail::close_socket(srv);
  9584. });
  9585. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9586. {
  9587. Client cli("127.0.0.1", PORT + 2);
  9588. cli.set_read_timeout(5, 0);
  9589. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9590. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9591. // (server claims more bytes than payload_max_length permits), but it must
  9592. // not exhaust memory before getting there.
  9593. auto res = cli.Get("/malicious");
  9594. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9595. }
  9596. server_thread.join();
  9597. }
  9598. // Verify that content_receiver bypasses the default payload_max_length,
  9599. // allowing streaming downloads larger than 100MB without requiring an explicit
  9600. // set_payload_max_length call.
  9601. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9602. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9603. #ifndef _WIN32
  9604. signal(SIGPIPE, SIG_IGN);
  9605. #endif
  9606. auto server_thread = std::thread([] {
  9607. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9608. default_socket_options(srv);
  9609. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9610. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9611. sockaddr_in addr{};
  9612. addr.sin_family = AF_INET;
  9613. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9614. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9615. int opt = 1;
  9616. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9617. #ifdef _WIN32
  9618. reinterpret_cast<const char *>(&opt),
  9619. #else
  9620. &opt,
  9621. #endif
  9622. sizeof(opt));
  9623. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9624. ::listen(srv, 1);
  9625. sockaddr_in cli_addr{};
  9626. socklen_t cli_len = sizeof(cli_addr);
  9627. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9628. if (cli != INVALID_SOCKET) {
  9629. char buf[4096];
  9630. ::recv(cli, buf, sizeof(buf), 0);
  9631. // Response with Content-Length larger than default 100MB limit
  9632. auto content_length = std::to_string(DATA_SIZE);
  9633. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9634. "Content-Length: " +
  9635. content_length +
  9636. "\r\n"
  9637. "Connection: close\r\n"
  9638. "\r\n";
  9639. ::send(cli,
  9640. #ifdef _WIN32
  9641. static_cast<const char *>(response_header.c_str()),
  9642. static_cast<int>(response_header.size()),
  9643. #else
  9644. response_header.c_str(), response_header.size(),
  9645. #endif
  9646. 0);
  9647. std::string chunk(64 * 1024, 'A');
  9648. size_t total_sent = 0;
  9649. while (total_sent < DATA_SIZE) {
  9650. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9651. auto sent = ::send(cli,
  9652. #ifdef _WIN32
  9653. static_cast<const char *>(chunk.c_str()),
  9654. static_cast<int>(to_send),
  9655. #else
  9656. chunk.c_str(), to_send,
  9657. #endif
  9658. 0);
  9659. if (sent <= 0) break;
  9660. total_sent += static_cast<size_t>(sent);
  9661. }
  9662. detail::close_socket(cli);
  9663. }
  9664. detail::close_socket(srv);
  9665. });
  9666. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9667. size_t total_received = 0;
  9668. {
  9669. Client cli("127.0.0.1", PORT + 2);
  9670. cli.set_read_timeout(10, 0);
  9671. // Do NOT call set_payload_max_length — use the default 100MB limit
  9672. auto res =
  9673. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9674. total_received += data_length;
  9675. return true;
  9676. });
  9677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9678. EXPECT_EQ(StatusCode::OK_200, res->status);
  9679. }
  9680. server_thread.join();
  9681. EXPECT_EQ(total_received, DATA_SIZE)
  9682. << "With content_receiver, the client should read all " << DATA_SIZE
  9683. << " bytes despite the default 100MB payload_max_length, but only read "
  9684. << total_received << " bytes.";
  9685. }
  9686. // Verify that an explicit set_payload_max_length smaller than the response is
  9687. // enforced even when a content_receiver is used.
  9688. TEST(ClientVulnerabilityTest,
  9689. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9690. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9691. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9692. #ifndef _WIN32
  9693. signal(SIGPIPE, SIG_IGN);
  9694. #endif
  9695. auto server_thread = std::thread([] {
  9696. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9697. default_socket_options(srv);
  9698. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9699. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9700. sockaddr_in addr{};
  9701. addr.sin_family = AF_INET;
  9702. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9703. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9704. int opt = 1;
  9705. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9706. #ifdef _WIN32
  9707. reinterpret_cast<const char *>(&opt),
  9708. #else
  9709. &opt,
  9710. #endif
  9711. sizeof(opt));
  9712. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9713. ::listen(srv, 1);
  9714. sockaddr_in cli_addr{};
  9715. socklen_t cli_len = sizeof(cli_addr);
  9716. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9717. if (cli != INVALID_SOCKET) {
  9718. char buf[4096];
  9719. ::recv(cli, buf, sizeof(buf), 0);
  9720. auto content_length = std::to_string(DATA_SIZE);
  9721. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9722. "Content-Length: " +
  9723. content_length +
  9724. "\r\n"
  9725. "Connection: close\r\n"
  9726. "\r\n";
  9727. ::send(cli,
  9728. #ifdef _WIN32
  9729. static_cast<const char *>(response_header.c_str()),
  9730. static_cast<int>(response_header.size()),
  9731. #else
  9732. response_header.c_str(), response_header.size(),
  9733. #endif
  9734. 0);
  9735. std::string chunk(64 * 1024, 'A');
  9736. size_t total_sent = 0;
  9737. while (total_sent < DATA_SIZE) {
  9738. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9739. auto sent = ::send(cli,
  9740. #ifdef _WIN32
  9741. static_cast<const char *>(chunk.c_str()),
  9742. static_cast<int>(to_send),
  9743. #else
  9744. chunk.c_str(), to_send,
  9745. #endif
  9746. 0);
  9747. if (sent <= 0) break;
  9748. total_sent += static_cast<size_t>(sent);
  9749. }
  9750. detail::close_socket(cli);
  9751. }
  9752. detail::close_socket(srv);
  9753. });
  9754. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9755. size_t total_received = 0;
  9756. {
  9757. Client cli("127.0.0.1", PORT + 2);
  9758. cli.set_read_timeout(10, 0);
  9759. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9760. auto res =
  9761. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9762. total_received += data_length;
  9763. return true;
  9764. });
  9765. // Should fail because 200MB exceeds the explicit 150MB limit
  9766. EXPECT_FALSE(res);
  9767. }
  9768. server_thread.join();
  9769. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9770. << "Client with content_receiver should respect the explicit "
  9771. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9772. << total_received << " bytes.";
  9773. }
  9774. // Verify that an explicit set_payload_max_length larger than the response
  9775. // allows the content_receiver to read all data successfully.
  9776. TEST(ClientVulnerabilityTest,
  9777. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9778. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9779. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9780. #ifndef _WIN32
  9781. signal(SIGPIPE, SIG_IGN);
  9782. #endif
  9783. auto server_thread = std::thread([] {
  9784. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9785. default_socket_options(srv);
  9786. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9787. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9788. sockaddr_in addr{};
  9789. addr.sin_family = AF_INET;
  9790. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9791. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9792. int opt = 1;
  9793. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9794. #ifdef _WIN32
  9795. reinterpret_cast<const char *>(&opt),
  9796. #else
  9797. &opt,
  9798. #endif
  9799. sizeof(opt));
  9800. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9801. ::listen(srv, 1);
  9802. sockaddr_in cli_addr{};
  9803. socklen_t cli_len = sizeof(cli_addr);
  9804. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9805. if (cli != INVALID_SOCKET) {
  9806. char buf[4096];
  9807. ::recv(cli, buf, sizeof(buf), 0);
  9808. auto content_length = std::to_string(DATA_SIZE);
  9809. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9810. "Content-Length: " +
  9811. content_length +
  9812. "\r\n"
  9813. "Connection: close\r\n"
  9814. "\r\n";
  9815. ::send(cli,
  9816. #ifdef _WIN32
  9817. static_cast<const char *>(response_header.c_str()),
  9818. static_cast<int>(response_header.size()),
  9819. #else
  9820. response_header.c_str(), response_header.size(),
  9821. #endif
  9822. 0);
  9823. std::string chunk(64 * 1024, 'A');
  9824. size_t total_sent = 0;
  9825. while (total_sent < DATA_SIZE) {
  9826. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9827. auto sent = ::send(cli,
  9828. #ifdef _WIN32
  9829. static_cast<const char *>(chunk.c_str()),
  9830. static_cast<int>(to_send),
  9831. #else
  9832. chunk.c_str(), to_send,
  9833. #endif
  9834. 0);
  9835. if (sent <= 0) break;
  9836. total_sent += static_cast<size_t>(sent);
  9837. }
  9838. #ifdef _WIN32
  9839. ::shutdown(cli, SD_SEND);
  9840. #else
  9841. ::shutdown(cli, SHUT_WR);
  9842. #endif
  9843. char drain[1024];
  9844. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9845. detail::close_socket(cli);
  9846. }
  9847. detail::close_socket(srv);
  9848. });
  9849. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9850. size_t total_received = 0;
  9851. {
  9852. Client cli("127.0.0.1", PORT + 2);
  9853. cli.set_read_timeout(10, 0);
  9854. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9855. auto res =
  9856. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9857. total_received += data_length;
  9858. return true;
  9859. });
  9860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9861. EXPECT_EQ(StatusCode::OK_200, res->status);
  9862. }
  9863. server_thread.join();
  9864. EXPECT_EQ(total_received, DATA_SIZE)
  9865. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9866. << " bytes (larger than " << DATA_SIZE
  9867. << " bytes response), content_receiver should read all data, but only "
  9868. "read "
  9869. << total_received << " bytes.";
  9870. }
  9871. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9872. // Regression test for "zip bomb" attack on the client side: a malicious server
  9873. // sends a small gzip-compressed response that decompresses to a huge payload.
  9874. // The client must enforce payload_max_length on the decompressed size.
  9875. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9876. constexpr size_t DECOMPRESSED_SIZE =
  9877. 10 * 1024 * 1024; // 10MB after decompression
  9878. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9879. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9880. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9881. std::string compressed;
  9882. {
  9883. httplib::detail::gzip_compressor compressor;
  9884. bool ok =
  9885. compressor.compress(uncompressed.data(), uncompressed.size(),
  9886. /*last=*/true, [&](const char *buf, size_t len) {
  9887. compressed.append(buf, len);
  9888. return true;
  9889. });
  9890. ASSERT_TRUE(ok);
  9891. }
  9892. // Sanity: compressed data should be much smaller than the decompressed size
  9893. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9894. #ifndef _WIN32
  9895. signal(SIGPIPE, SIG_IGN);
  9896. #endif
  9897. // Set up the listening socket in the main thread so the server is guaranteed
  9898. // to be ready before the client connects (eliminates race condition).
  9899. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9900. default_socket_options(srv);
  9901. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9902. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9903. sockaddr_in addr{};
  9904. addr.sin_family = AF_INET;
  9905. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9906. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9907. int opt = 1;
  9908. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9909. #ifdef _WIN32
  9910. reinterpret_cast<const char *>(&opt),
  9911. #else
  9912. &opt,
  9913. #endif
  9914. sizeof(opt));
  9915. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9916. ASSERT_EQ(0, ::listen(srv, 1));
  9917. auto server_thread = std::thread([&compressed, srv] {
  9918. sockaddr_in cli_addr{};
  9919. socklen_t cli_len = sizeof(cli_addr);
  9920. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9921. if (cli != INVALID_SOCKET) {
  9922. // Read the full HTTP request (until \r\n\r\n)
  9923. char buf[4096];
  9924. size_t total = 0;
  9925. while (total < sizeof(buf)) {
  9926. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9927. if (n <= 0) break;
  9928. total += static_cast<size_t>(n);
  9929. // Check for end of headers
  9930. if (total >= 4) {
  9931. std::string req(buf, total);
  9932. if (req.find("\r\n\r\n") != std::string::npos) break;
  9933. }
  9934. }
  9935. // Malicious response: gzip-compressed body, no Content-Length
  9936. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9937. "Content-Encoding: gzip\r\n"
  9938. "Connection: close\r\n"
  9939. "\r\n";
  9940. ::send(cli,
  9941. #ifdef _WIN32
  9942. static_cast<const char *>(response_header.c_str()),
  9943. static_cast<int>(response_header.size()),
  9944. #else
  9945. response_header.c_str(), response_header.size(),
  9946. #endif
  9947. 0);
  9948. // Send the compressed payload (small on the wire, huge when decompressed)
  9949. size_t total_sent = 0;
  9950. while (total_sent < compressed.size()) {
  9951. auto to_send = std::min(compressed.size() - total_sent,
  9952. static_cast<size_t>(64 * 1024));
  9953. auto sent =
  9954. ::send(cli,
  9955. #ifdef _WIN32
  9956. static_cast<const char *>(compressed.c_str() + total_sent),
  9957. static_cast<int>(to_send),
  9958. #else
  9959. compressed.c_str() + total_sent, to_send,
  9960. #endif
  9961. 0);
  9962. if (sent <= 0) break;
  9963. total_sent += static_cast<size_t>(sent);
  9964. }
  9965. detail::close_socket(cli);
  9966. }
  9967. });
  9968. auto se = detail::scope_exit([&] {
  9969. detail::close_socket(srv);
  9970. server_thread.join();
  9971. });
  9972. size_t total_decompressed = 0;
  9973. {
  9974. Client cli("127.0.0.1", PORT + 3);
  9975. cli.set_read_timeout(5, 0);
  9976. cli.set_decompress(true);
  9977. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9978. auto stream = cli.open_stream("GET", "/zipbomb");
  9979. ASSERT_TRUE(stream.is_valid());
  9980. char buffer[64 * 1024];
  9981. ssize_t n;
  9982. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9983. total_decompressed += static_cast<size_t>(n);
  9984. }
  9985. }
  9986. // The decompressed size must be capped by payload_max_length. Without
  9987. // protection, the client would decompress the full 10MB from a tiny
  9988. // compressed payload, enabling a zip bomb DoS attack.
  9989. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9990. << "Client decompressed " << total_decompressed
  9991. << " bytes from a gzip response. The decompressed size should be "
  9992. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9993. }
  9994. #endif
  9995. TEST(HostAndPortPropertiesTest, NoSSL) {
  9996. httplib::Client cli("www.google.com", 1234);
  9997. ASSERT_EQ("www.google.com", cli.host());
  9998. ASSERT_EQ(1234, cli.port());
  9999. }
  10000. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  10001. httplib::Client cli("www.google.com:1234");
  10002. ASSERT_EQ("www.google.com", cli.host());
  10003. ASSERT_EQ(1234, cli.port());
  10004. }
  10005. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  10006. // Port number that overflows int — should not crash, client becomes invalid
  10007. httplib::Client cli("http://www.google.com:99999999999999999999");
  10008. ASSERT_FALSE(cli.is_valid());
  10009. }
  10010. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  10011. // Port 99999 exceeds valid range (1-65535) — should not crash
  10012. httplib::Client cli("http://www.google.com:99999");
  10013. ASSERT_FALSE(cli.is_valid());
  10014. }
  10015. #ifdef CPPHTTPLIB_SSL_ENABLED
  10016. TEST(HostAndPortPropertiesTest, SSL) {
  10017. httplib::SSLClient cli("www.google.com");
  10018. ASSERT_EQ("www.google.com", cli.host());
  10019. ASSERT_EQ(443, cli.port());
  10020. }
  10021. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  10022. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  10023. std::string cert;
  10024. read_file(CA_CERT_FILE, cert);
  10025. httplib::SSLClient httplib_client("www.google.com");
  10026. // Load CA store first time
  10027. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10028. // Load CA store second time (update)
  10029. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  10030. // Verify client is still valid and can make connections
  10031. httplib_client.enable_server_certificate_verification(true);
  10032. auto res = httplib_client.Get("/");
  10033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10034. // Google may return 200 or 301 depending on various factors
  10035. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  10036. res->status == StatusCode::MovedPermanently_301);
  10037. }
  10038. TEST(SSLClientTest, ServerNameIndication_Online) {
  10039. auto host = "httpbingo.org";
  10040. auto path = std::string{"/get"};
  10041. SSLClient cli(host, 443);
  10042. auto res = cli.Get(path);
  10043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10044. ASSERT_EQ(StatusCode::OK_200, res->status);
  10045. }
  10046. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  10047. // Use a site that will cause SSL verification failure due to self-signed cert
  10048. SSLClient cli("self-signed.badssl.com", 443);
  10049. cli.enable_server_certificate_verification(true);
  10050. auto res = cli.Get("/");
  10051. ASSERT_TRUE(!res);
  10052. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10053. // Verify backend error is captured for SSLServerVerification
  10054. // This occurs when certificate verification fails
  10055. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  10056. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  10057. EXPECT_NE(0UL, res.ssl_backend_error());
  10058. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10059. // For OpenSSL, ssl_error is 0 for verification errors
  10060. EXPECT_EQ(0, res.ssl_error());
  10061. #if !defined(_WIN32) || \
  10062. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10063. // On non-Windows or when Windows Schannel is disabled, the error comes
  10064. // from OpenSSL's verification
  10065. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10066. res.ssl_backend_error());
  10067. #endif
  10068. #endif
  10069. }
  10070. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10071. // Use a site where hostname doesn't match the certificate
  10072. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10073. SSLClient cli("wrong.host.badssl.com", 443);
  10074. cli.enable_server_certificate_verification(true);
  10075. cli.enable_server_hostname_verification(true);
  10076. auto res = cli.Get("/");
  10077. ASSERT_TRUE(!res);
  10078. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  10079. // Verify backend error is captured for hostname verification failure
  10080. EXPECT_NE(0UL, res.ssl_backend_error());
  10081. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10082. // For OpenSSL, ssl_error is 0 for verification errors
  10083. EXPECT_EQ(0, res.ssl_error());
  10084. #if !defined(_WIN32) || \
  10085. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10086. // On non-Windows or when Windows Schannel is disabled, the error comes
  10087. // from OpenSSL's hostname verification
  10088. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10089. res.ssl_backend_error());
  10090. #endif
  10091. #endif
  10092. }
  10093. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10094. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10095. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10096. SSLClient cli("www.google.com", 443);
  10097. cli.enable_server_certificate_verification(true);
  10098. auto res = cli.Get("/");
  10099. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10100. }
  10101. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10102. SSLClient cli("www.google.com", 443);
  10103. cli.enable_server_certificate_verification(true);
  10104. cli.enable_windows_certificate_verification(false);
  10105. auto res = cli.Get("/");
  10106. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10107. }
  10108. #endif
  10109. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10110. Client cli("https://google.com");
  10111. auto res = cli.Get("/");
  10112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10113. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10114. }
  10115. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10116. SSLClient cli("google.com");
  10117. cli.set_ca_cert_path(CA_CERT_FILE);
  10118. auto res = cli.Get("/");
  10119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10120. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10121. }
  10122. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10123. SSLClient cli("google.com");
  10124. cli.enable_server_certificate_verification(true);
  10125. cli.set_ca_cert_path("hello");
  10126. auto res = cli.Get("/");
  10127. ASSERT_TRUE(!res);
  10128. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10129. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10130. // should be set
  10131. EXPECT_EQ(0, res.ssl_error());
  10132. // Verify backend error is captured for SSLLoadingCerts
  10133. // This error occurs when loading CA certificates fails
  10134. EXPECT_NE(0UL, res.ssl_backend_error());
  10135. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10136. // OpenSSL specific error codes:
  10137. // > openssl errstr 0x80000002
  10138. // error:80000002:system library::No such file or directory
  10139. // > openssl errstr 0xA000126
  10140. // error:0A000126:SSL routines::unexpected eof while reading
  10141. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10142. res.ssl_backend_error() == 0xA000126);
  10143. #endif
  10144. }
  10145. TEST(SSLClientTest, ServerCertificateVerification4) {
  10146. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10147. ASSERT_TRUE(svr.is_valid());
  10148. svr.Get("/test", [&](const Request &, Response &res) {
  10149. res.set_content("test", "text/plain");
  10150. svr.stop();
  10151. ASSERT_TRUE(true);
  10152. });
  10153. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10154. auto se = detail::scope_exit([&] {
  10155. t.join();
  10156. ASSERT_FALSE(svr.is_running());
  10157. });
  10158. svr.wait_until_ready();
  10159. SSLClient cli("127.0.0.1", PORT);
  10160. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10161. cli.enable_server_certificate_verification(true);
  10162. cli.set_connection_timeout(30);
  10163. auto res = cli.Get("/test");
  10164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10165. ASSERT_EQ(StatusCode::OK_200, res->status);
  10166. }
  10167. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10168. std::string cert;
  10169. read_file(CA_CERT_FILE, cert);
  10170. SSLClient cli("google.com");
  10171. cli.load_ca_cert_store(cert.data(), cert.size());
  10172. const auto res = cli.Get("/");
  10173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10174. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10175. }
  10176. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10177. // clang-format off
  10178. static constexpr char cert[] =
  10179. "GlobalSign Root CA\n"
  10180. "==================\n"
  10181. "-----BEGIN CERTIFICATE-----\n"
  10182. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10183. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10184. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10185. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10186. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10187. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10188. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10189. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10190. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10191. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10192. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10193. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10194. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10195. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10196. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10197. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10198. "-----END CERTIFICATE-----\n";
  10199. // clang-format on
  10200. SSLClient cli("google.com");
  10201. cli.load_ca_cert_store(cert, sizeof(cert));
  10202. const auto res = cli.Get("/");
  10203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10204. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10205. }
  10206. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10207. SSLClient cli("www.youtube.com");
  10208. cli.set_ca_cert_path(CA_CERT_FILE);
  10209. cli.enable_server_certificate_verification(true);
  10210. cli.set_follow_location(true);
  10211. auto res = cli.Get("/");
  10212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10213. ASSERT_EQ(StatusCode::OK_200, res->status);
  10214. }
  10215. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10216. SSLClient cli("wWw.YouTube.Com");
  10217. cli.set_ca_cert_path(CA_CERT_FILE);
  10218. cli.enable_server_certificate_verification(true);
  10219. cli.enable_server_hostname_verification(true);
  10220. cli.set_follow_location(true);
  10221. auto res = cli.Get("/");
  10222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10223. ASSERT_EQ(StatusCode::OK_200, res->status);
  10224. }
  10225. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10226. SSLClient cli("gOoGlE.COm");
  10227. cli.enable_server_certificate_verification(true);
  10228. cli.enable_server_hostname_verification(true);
  10229. cli.set_follow_location(true);
  10230. auto res = cli.Get("/");
  10231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10232. ASSERT_EQ(StatusCode::OK_200, res->status);
  10233. }
  10234. TEST(SSLClientTest, Issue2004_Online) {
  10235. Client client("https://google.com");
  10236. client.set_follow_location(true);
  10237. auto res = client.Get("/");
  10238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10239. ASSERT_EQ(StatusCode::OK_200, res->status);
  10240. auto body = res->body;
  10241. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10242. }
  10243. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10244. // Create SSLClient with invalid cert/key to make is_valid() return false
  10245. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10246. "nonexistent_key.pem");
  10247. // is_valid() should be false due to cert loading failure
  10248. ASSERT_FALSE(cli.is_valid());
  10249. auto res = cli.Get("/");
  10250. ASSERT_FALSE(res);
  10251. EXPECT_EQ(Error::SSLConnection, res.error());
  10252. }
  10253. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10254. // Test for Issue #2251: SSL error not properly reported when client cert
  10255. // and key paths are swapped or mismatched
  10256. // This simulates the scenario where user accidentally swaps the cert and key
  10257. // files
  10258. // Using client cert file as private key and vice versa (completely wrong)
  10259. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10260. // Should fail validation due to cert/key mismatch
  10261. ASSERT_FALSE(cli.is_valid());
  10262. // Attempt to make a request should fail with proper error
  10263. auto res = cli.Get("/");
  10264. ASSERT_FALSE(res);
  10265. EXPECT_EQ(Error::SSLConnection, res.error());
  10266. // SSL error should be recorded in the Result object (this is the key fix for
  10267. // Issue #2251)
  10268. auto backend_error = res.ssl_backend_error();
  10269. EXPECT_NE(0u, backend_error);
  10270. }
  10271. // Tests cert/key mismatch detection at the TLS context level
  10272. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10273. // Test that using mismatched cert/key causes connection failure.
  10274. // We verify this at the SSLClient level rather than through internal
  10275. // TLS API functions.
  10276. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10277. cli.enable_server_certificate_verification(false);
  10278. cli.set_connection_timeout(2);
  10279. // The mismatch should cause a connection or handshake error
  10280. auto res = cli.Get("/test");
  10281. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10282. // Either way, the request should fail
  10283. EXPECT_FALSE(res);
  10284. }
  10285. #endif
  10286. #if 0
  10287. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10288. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10289. ASSERT_TRUE(cli != nullptr);
  10290. cli->set_address_family(AF_INET6);
  10291. cli->set_interface("en0");
  10292. auto res = cli->Get("/get");
  10293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10294. ASSERT_EQ(StatusCode::OK_200, res->status);
  10295. }
  10296. #endif
  10297. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10298. #ifdef CPPHTTPLIB_SSL_ENABLED
  10299. void ClientCertPresent(
  10300. const std::string &client_cert_file,
  10301. const std::string &client_private_key_file,
  10302. const std::string &client_encrypted_private_key_pass = std::string()) {
  10303. using namespace httplib::tls;
  10304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10305. CLIENT_CA_CERT_DIR);
  10306. ASSERT_TRUE(svr.is_valid());
  10307. svr.Get("/test", [&](const Request &req, Response &res) {
  10308. res.set_content("test", "text/plain");
  10309. auto cert = req.peer_cert();
  10310. ASSERT_TRUE(static_cast<bool>(cert));
  10311. std::string common_name = cert.subject_cn();
  10312. EXPECT_EQ("Common Name", common_name);
  10313. });
  10314. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10315. auto se = detail::scope_exit([&] {
  10316. svr.stop();
  10317. t.join();
  10318. ASSERT_FALSE(svr.is_running());
  10319. });
  10320. svr.wait_until_ready();
  10321. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10322. client_encrypted_private_key_pass);
  10323. cli.enable_server_certificate_verification(false);
  10324. cli.set_connection_timeout(30);
  10325. auto res = cli.Get("/test");
  10326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10327. ASSERT_EQ(StatusCode::OK_200, res->status);
  10328. }
  10329. TEST(SSLClientServerTest, ClientCertPresent) {
  10330. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10331. }
  10332. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10333. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10334. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10335. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10336. }
  10337. // PEM memory-based constructor tests (works with all TLS backends)
  10338. void PemMemoryClientCertPresent(
  10339. const std::string &client_cert_file,
  10340. const std::string &client_private_key_file,
  10341. const std::string &client_encrypted_private_key_pass = std::string()) {
  10342. // Read PEM files into memory
  10343. std::string server_cert_pem, server_key_pem;
  10344. std::string client_ca_pem;
  10345. std::string client_cert_pem, client_key_pem;
  10346. read_file(SERVER_CERT_FILE, server_cert_pem);
  10347. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10348. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10349. read_file(client_cert_file, client_cert_pem);
  10350. read_file(client_private_key_file, client_key_pem);
  10351. // Create server with PEM memory
  10352. SSLServer::PemMemory server_pem = {
  10353. server_cert_pem.c_str(),
  10354. server_cert_pem.size(),
  10355. server_key_pem.c_str(),
  10356. server_key_pem.size(),
  10357. client_ca_pem.c_str(),
  10358. client_ca_pem.size(),
  10359. nullptr // no password for server key
  10360. };
  10361. SSLServer svr(server_pem);
  10362. ASSERT_TRUE(svr.is_valid());
  10363. svr.Get("/test", [&](const Request &, Response &res) {
  10364. res.set_content("test", "text/plain");
  10365. });
  10366. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10367. auto se = detail::scope_exit([&] {
  10368. svr.stop();
  10369. t.join();
  10370. ASSERT_FALSE(svr.is_running());
  10371. });
  10372. svr.wait_until_ready();
  10373. // Create client with PEM memory
  10374. const char *password = client_encrypted_private_key_pass.empty()
  10375. ? nullptr
  10376. : client_encrypted_private_key_pass.c_str();
  10377. SSLClient::PemMemory client_pem = {
  10378. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10379. client_key_pem.size(), password};
  10380. SSLClient cli(HOST, PORT, client_pem);
  10381. cli.enable_server_certificate_verification(false);
  10382. cli.set_connection_timeout(30);
  10383. auto res = cli.Get("/test");
  10384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10385. ASSERT_EQ(StatusCode::OK_200, res->status);
  10386. }
  10387. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10388. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10389. }
  10390. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10391. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10392. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10393. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10394. }
  10395. TEST(SSLClientServerTest, ClientCertMissing) {
  10396. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10397. CLIENT_CA_CERT_DIR);
  10398. ASSERT_TRUE(svr.is_valid());
  10399. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10400. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10401. auto se = detail::scope_exit([&] {
  10402. svr.stop();
  10403. t.join();
  10404. ASSERT_FALSE(svr.is_running());
  10405. });
  10406. svr.wait_until_ready();
  10407. SSLClient cli(HOST, PORT);
  10408. cli.set_connection_timeout(30);
  10409. auto res = cli.Get("/test");
  10410. ASSERT_TRUE(!res);
  10411. // When client cert is missing and server requires it, connection fails
  10412. // Error type depends on backend implementation
  10413. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10414. res.error() == Error::SSLConnection);
  10415. // Verify backend error is captured
  10416. // Note: This test may have different error codes depending on the exact
  10417. // verification failure
  10418. EXPECT_NE(0UL, res.ssl_backend_error());
  10419. }
  10420. TEST(SSLClientServerTest, TrustDirOptional) {
  10421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10422. ASSERT_TRUE(svr.is_valid());
  10423. svr.Get("/test", [&](const Request &, Response &res) {
  10424. res.set_content("test", "text/plain");
  10425. });
  10426. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10427. auto se = detail::scope_exit([&] {
  10428. svr.stop();
  10429. t.join();
  10430. ASSERT_FALSE(svr.is_running());
  10431. });
  10432. svr.wait_until_ready();
  10433. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10434. cli.enable_server_certificate_verification(false);
  10435. cli.set_connection_timeout(30);
  10436. auto res = cli.Get("/test");
  10437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10438. ASSERT_EQ(StatusCode::OK_200, res->status);
  10439. }
  10440. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10441. class NoListenSSLServer : public SSLServer {
  10442. public:
  10443. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10444. const char *client_ca_cert_file_path,
  10445. const char *client_ca_cert_dir_path = nullptr)
  10446. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10447. client_ca_cert_dir_path),
  10448. stop_(false) {}
  10449. std::atomic_bool stop_;
  10450. private:
  10451. bool process_and_close_socket(socket_t /*sock*/) override {
  10452. // Don't create SSL context
  10453. while (!stop_.load()) {
  10454. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10455. }
  10456. return true;
  10457. }
  10458. };
  10459. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10460. CLIENT_CA_CERT_FILE);
  10461. ASSERT_TRUE(svr.is_valid());
  10462. svr.Get("/test", [&](const Request &, Response &res) {
  10463. res.set_content("test", "text/plain");
  10464. });
  10465. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10466. auto se = detail::scope_exit([&] {
  10467. svr.stop_ = true;
  10468. svr.stop();
  10469. t.join();
  10470. ASSERT_FALSE(svr.is_running());
  10471. });
  10472. svr.wait_until_ready();
  10473. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10474. cli.enable_server_certificate_verification(false);
  10475. cli.set_connection_timeout(1);
  10476. auto res = cli.Get("/test");
  10477. ASSERT_TRUE(!res);
  10478. EXPECT_EQ(Error::SSLConnection, res.error());
  10479. // Timeout results in WantRead error code (maps to backend-specific value)
  10480. EXPECT_NE(0, res.ssl_error());
  10481. }
  10482. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10483. // Test SSLServer with client certificate verification using the standard
  10484. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10485. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10486. CLIENT_CA_CERT_DIR);
  10487. ASSERT_TRUE(svr.is_valid());
  10488. svr.Get("/test", [&](const Request &req, Response &res) {
  10489. res.set_content("test", "text/plain");
  10490. auto cert = req.peer_cert();
  10491. ASSERT_TRUE(static_cast<bool>(cert));
  10492. auto common_name = cert.subject_cn();
  10493. EXPECT_EQ("Common Name", common_name);
  10494. });
  10495. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10496. auto se = detail::scope_exit([&] {
  10497. svr.stop();
  10498. t.join();
  10499. ASSERT_FALSE(svr.is_running());
  10500. });
  10501. svr.wait_until_ready();
  10502. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10503. cli.enable_server_certificate_verification(false);
  10504. cli.set_connection_timeout(30);
  10505. auto res = cli.Get("/test");
  10506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10507. ASSERT_EQ(StatusCode::OK_200, res->status);
  10508. }
  10509. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10510. // Verifies that wildcard matching and exact matching work consistently
  10511. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10512. using namespace httplib::tls;
  10513. // We need a running server to test against
  10514. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10515. ASSERT_TRUE(svr.is_valid());
  10516. svr.Get("/test", [](const Request &, Response &res) {
  10517. res.set_content("ok", "text/plain");
  10518. });
  10519. thread t([&]() { svr.listen(HOST, PORT); });
  10520. auto se = detail::scope_exit([&] {
  10521. svr.stop();
  10522. t.join();
  10523. });
  10524. svr.wait_until_ready();
  10525. bool verify_callback_called = false;
  10526. bool verify_result_wrong = false;
  10527. SSLClient cli(HOST, PORT);
  10528. cli.enable_server_certificate_verification(true);
  10529. cli.set_ca_cert_path(CA_CERT_FILE);
  10530. cli.set_connection_timeout(5);
  10531. // Note: Test certificate has CN="Common Name", not "localhost"
  10532. bool verify_result_cn = false;
  10533. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10534. verify_callback_called = true;
  10535. if (!ctx.cert) return false;
  10536. // Test 1: "Common Name" should match (our test server cert CN)
  10537. verify_result_cn = ctx.check_hostname("Common Name");
  10538. // Test 2: wrong hostname should not match
  10539. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10540. return true; // Accept for the purpose of this test
  10541. });
  10542. auto res = cli.Get("/test");
  10543. // The request may succeed or fail depending on cert configuration
  10544. // but the callback should have been called
  10545. ASSERT_TRUE(verify_callback_called)
  10546. << "Verify callback should have been called";
  10547. // CN="Common Name" should match our test certificate
  10548. //
  10549. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10550. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10551. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10552. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10553. // <openssl/base.h>, which is included transitively when
  10554. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10555. #if defined(OPENSSL_IS_BORINGSSL)
  10556. EXPECT_FALSE(verify_result_cn)
  10557. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10558. #else
  10559. EXPECT_TRUE(verify_result_cn)
  10560. << "verify_hostname should match 'Common Name' (certificate CN)";
  10561. #endif
  10562. // Wrong hostname should not match
  10563. EXPECT_FALSE(verify_result_wrong)
  10564. << "verify_hostname should not match 'wronghost.example.com'";
  10565. }
  10566. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10567. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10568. // X509_check_ip behavior and must hold for every backend.
  10569. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10570. using namespace httplib::tls;
  10571. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10572. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10573. ASSERT_TRUE(svr.is_valid());
  10574. svr.Get("/test", [](const Request &, Response &res) {
  10575. res.set_content("ok", "text/plain");
  10576. });
  10577. thread t([&]() { svr.listen(HOST, PORT); });
  10578. auto se = detail::scope_exit([&] {
  10579. svr.stop();
  10580. t.join();
  10581. });
  10582. svr.wait_until_ready();
  10583. bool verify_callback_called = false;
  10584. bool ip_matched_via_cn = true;
  10585. SSLClient cli(HOST, PORT);
  10586. cli.enable_server_certificate_verification(true);
  10587. cli.set_ca_cert_path(CA_CERT_FILE);
  10588. cli.set_connection_timeout(5);
  10589. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10590. verify_callback_called = true;
  10591. if (!ctx.cert) return false;
  10592. // The IP appears only in the CN, so it must NOT be accepted.
  10593. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10594. return true; // Accept for the purpose of this test
  10595. });
  10596. cli.Get("/test");
  10597. ASSERT_TRUE(verify_callback_called)
  10598. << "Verify callback should have been called";
  10599. EXPECT_FALSE(ip_matched_via_cn)
  10600. << "An IP host must not be authenticated via the certificate CN";
  10601. }
  10602. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10603. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10604. using namespace httplib::tls;
  10605. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10606. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10607. ASSERT_TRUE(svr.is_valid());
  10608. svr.Get("/test", [](const Request &, Response &res) {
  10609. res.set_content("ok", "text/plain");
  10610. });
  10611. thread t([&]() { svr.listen(HOST, PORT); });
  10612. auto se = detail::scope_exit([&] {
  10613. svr.stop();
  10614. t.join();
  10615. });
  10616. svr.wait_until_ready();
  10617. bool verify_callback_called = false;
  10618. bool san_matched = false;
  10619. bool wrong_ipv6_matched = true;
  10620. bool cn_ipv6_matched = true;
  10621. SSLClient cli(HOST, PORT);
  10622. cli.enable_server_certificate_verification(true);
  10623. cli.set_ca_cert_path(CA_CERT_FILE);
  10624. cli.set_connection_timeout(5);
  10625. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10626. verify_callback_called = true;
  10627. if (!ctx.cert) return false;
  10628. // Matches the IPv6 iPAddress SAN.
  10629. san_matched = ctx.check_hostname("2001:db8::1");
  10630. // A different IPv6 address must not match.
  10631. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10632. // "::1" lives only in the CN, so it must not be accepted.
  10633. cn_ipv6_matched = ctx.check_hostname("::1");
  10634. return true; // Accept for the purpose of this test
  10635. });
  10636. cli.Get("/test");
  10637. ASSERT_TRUE(verify_callback_called)
  10638. << "Verify callback should have been called";
  10639. EXPECT_TRUE(san_matched)
  10640. << "verify_hostname should match an IPv6 iPAddress SAN";
  10641. EXPECT_FALSE(wrong_ipv6_matched)
  10642. << "verify_hostname should not match a non-matching IPv6 address";
  10643. EXPECT_FALSE(cn_ipv6_matched)
  10644. << "An IPv6 host must not be authenticated via the certificate CN";
  10645. }
  10646. #endif
  10647. // mbedTLS-specific callback constructor test
  10648. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10649. #ifdef CPPHTTPLIB_SSL_ENABLED
  10650. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10652. ASSERT_TRUE(svr.is_valid());
  10653. // Set up a handler to verify client certificate is present
  10654. bool client_cert_verified = false;
  10655. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10656. // Verify that client certificate was provided
  10657. client_cert_verified = true;
  10658. res.set_content("success", "text/plain");
  10659. });
  10660. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10661. auto se = detail::scope_exit([&] {
  10662. svr.stop();
  10663. t.join();
  10664. ASSERT_FALSE(svr.is_running());
  10665. });
  10666. svr.wait_until_ready();
  10667. // Client with certificate
  10668. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10669. cli.enable_server_certificate_verification(false);
  10670. cli.set_connection_timeout(30);
  10671. auto res = cli.Get("/test");
  10672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10673. ASSERT_EQ(StatusCode::OK_200, res->status);
  10674. ASSERT_TRUE(client_cert_verified);
  10675. EXPECT_EQ("success", res->body);
  10676. }
  10677. #endif
  10678. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10679. // backends
  10680. #ifdef CPPHTTPLIB_SSL_ENABLED
  10681. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10682. using namespace httplib::tls;
  10683. // Test that when client CA cert file is provided,
  10684. // the server properly requests and validates client certificates
  10685. // Create a server with client authentication
  10686. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10687. ASSERT_TRUE(svr.is_valid());
  10688. bool handler_called = false;
  10689. svr.Get("/test", [&](const Request &req, Response &res) {
  10690. handler_called = true;
  10691. // Verify that a client certificate was provided
  10692. auto cert = req.peer_cert();
  10693. ASSERT_TRUE(static_cast<bool>(cert));
  10694. // Get the issuer name
  10695. std::string issuer_str = cert.issuer_name();
  10696. ASSERT_FALSE(issuer_str.empty());
  10697. // The client certificate should be issued by our test CA
  10698. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10699. res.set_content("authenticated", "text/plain");
  10700. });
  10701. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10702. auto se = detail::scope_exit([&] {
  10703. svr.stop();
  10704. t.join();
  10705. ASSERT_FALSE(svr.is_running());
  10706. });
  10707. svr.wait_until_ready();
  10708. // Connect with a client certificate issued by the CA
  10709. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10710. cli.enable_server_certificate_verification(false);
  10711. cli.set_connection_timeout(30);
  10712. auto res = cli.Get("/test");
  10713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10714. ASSERT_EQ(StatusCode::OK_200, res->status);
  10715. ASSERT_TRUE(handler_called);
  10716. EXPECT_EQ("authenticated", res->body);
  10717. }
  10718. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10719. using namespace httplib::tls;
  10720. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10721. ASSERT_TRUE(svr.is_valid());
  10722. svr.Get("/test", [](const Request &, Response &res) {
  10723. res.set_content("ok", "text/plain");
  10724. });
  10725. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10726. auto se = detail::scope_exit([&] {
  10727. svr.stop();
  10728. t.join();
  10729. });
  10730. svr.wait_until_ready();
  10731. SSLClient cli(HOST, PORT);
  10732. cli.enable_server_certificate_verification(false);
  10733. cli.set_connection_timeout(30);
  10734. bool cert_checked = false;
  10735. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10736. if (ctx.cert) {
  10737. auto sans = ctx.sans();
  10738. // Test certificate may or may not have SANs - just verify the API
  10739. // works If SANs exist, verify the types are valid
  10740. for (const auto &san : sans) {
  10741. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10742. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10743. san.type == SanType::OTHER);
  10744. EXPECT_FALSE(san.value.empty());
  10745. }
  10746. cert_checked = true;
  10747. }
  10748. return true;
  10749. });
  10750. auto res = cli.Get("/test");
  10751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10752. EXPECT_TRUE(cert_checked);
  10753. }
  10754. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10755. using namespace httplib::tls;
  10756. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10757. ASSERT_TRUE(svr.is_valid());
  10758. svr.Get("/test", [](const Request &, Response &res) {
  10759. res.set_content("ok", "text/plain");
  10760. });
  10761. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10762. auto se = detail::scope_exit([&] {
  10763. svr.stop();
  10764. t.join();
  10765. });
  10766. svr.wait_until_ready();
  10767. SSLClient cli(HOST, PORT);
  10768. cli.enable_server_certificate_verification(false);
  10769. cli.set_connection_timeout(30);
  10770. bool validity_checked = false;
  10771. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10772. if (ctx.cert) {
  10773. time_t not_before = 0, not_after = 0;
  10774. bool result = ctx.validity(not_before, not_after);
  10775. EXPECT_TRUE(result);
  10776. // Verify that not_before < now < not_after for a valid cert
  10777. time_t now = time(nullptr);
  10778. EXPECT_LT(not_before, now);
  10779. EXPECT_GT(not_after, now);
  10780. validity_checked = true;
  10781. }
  10782. return true;
  10783. });
  10784. auto res = cli.Get("/test");
  10785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10786. EXPECT_TRUE(validity_checked);
  10787. }
  10788. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10789. using namespace httplib::tls;
  10790. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10791. ASSERT_TRUE(svr.is_valid());
  10792. svr.Get("/test", [](const Request &, Response &res) {
  10793. res.set_content("ok", "text/plain");
  10794. });
  10795. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10796. auto se = detail::scope_exit([&] {
  10797. svr.stop();
  10798. t.join();
  10799. });
  10800. svr.wait_until_ready();
  10801. SSLClient cli(HOST, PORT);
  10802. cli.enable_server_certificate_verification(false);
  10803. cli.set_connection_timeout(30);
  10804. bool serial_checked = false;
  10805. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10806. if (ctx.cert) {
  10807. std::string serial = ctx.serial();
  10808. EXPECT_FALSE(serial.empty());
  10809. // Serial should be a hex string
  10810. for (char c : serial) {
  10811. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10812. (c >= 'a' && c <= 'f'));
  10813. }
  10814. serial_checked = true;
  10815. }
  10816. return true;
  10817. });
  10818. auto res = cli.Get("/test");
  10819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10820. EXPECT_TRUE(serial_checked);
  10821. }
  10822. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10823. // Test 1: Valid CA file - no error should be recorded
  10824. {
  10825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10826. CLIENT_CA_CERT_FILE);
  10827. ASSERT_TRUE(svr.is_valid());
  10828. // With valid setup, last_ssl_error should be 0
  10829. EXPECT_EQ(0, svr.ssl_last_error());
  10830. }
  10831. // Test 2: Invalid CA file content
  10832. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10833. {
  10834. // Create a temporary file with completely invalid content
  10835. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10836. {
  10837. std::ofstream ofs(temp_invalid_ca);
  10838. ofs << "This is not a certificate file at all\n";
  10839. ofs << "Just plain text content\n";
  10840. }
  10841. // Create server with invalid CA file
  10842. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10843. // Clean up temporary file
  10844. std::remove(temp_invalid_ca);
  10845. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10846. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10847. // Note: SSL_CTX_load_verify_locations typically fails first,
  10848. // but our error handling code path is still exercised
  10849. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10850. }
  10851. }
  10852. TEST(VerifyCallbackTest, VerifyContextFields) {
  10853. using namespace httplib::tls;
  10854. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10855. ASSERT_TRUE(svr.is_valid());
  10856. svr.Get("/test", [](const Request &, Response &res) {
  10857. res.set_content("ok", "text/plain");
  10858. });
  10859. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10860. auto se = detail::scope_exit([&] {
  10861. svr.stop();
  10862. t.join();
  10863. });
  10864. svr.wait_until_ready();
  10865. SSLClient cli(HOST, PORT);
  10866. cli.enable_server_certificate_verification(false);
  10867. cli.set_connection_timeout(30);
  10868. int callback_count = 0;
  10869. bool saw_leaf_cert = false;
  10870. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10871. if (ctx.cert) {
  10872. callback_count++;
  10873. // We should see at least one certificate (the leaf)
  10874. std::string cn = ctx.subject_cn();
  10875. if (!cn.empty()) { saw_leaf_cert = true; }
  10876. // Verify context fields are populated
  10877. EXPECT_NE(ctx.session, nullptr);
  10878. EXPECT_GE(ctx.depth, 0);
  10879. }
  10880. return true;
  10881. });
  10882. auto res = cli.Get("/test");
  10883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10884. EXPECT_GT(callback_count, 0);
  10885. EXPECT_TRUE(saw_leaf_cert);
  10886. }
  10887. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10888. using httplib::tls::TlsError;
  10889. // Test that verify_error_to_string returns empty for success
  10890. std::string success_str = TlsError::verify_error_to_string(0);
  10891. EXPECT_TRUE(success_str.empty());
  10892. // Test that verify_error_to_string returns non-empty for error codes
  10893. // Using a common error code (certificate expired)
  10894. std::string error_str =
  10895. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10896. EXPECT_FALSE(error_str.empty());
  10897. }
  10898. TEST(SessionVerifierTest, CertificateAccepted) {
  10899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10900. ASSERT_TRUE(svr.is_valid());
  10901. svr.Get("/test", [](const Request &, Response &res) {
  10902. res.set_content("ok", "text/plain");
  10903. });
  10904. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10905. auto se = detail::scope_exit([&] {
  10906. svr.stop();
  10907. t.join();
  10908. });
  10909. svr.wait_until_ready();
  10910. SSLClient cli(HOST, PORT);
  10911. cli.enable_server_certificate_verification(false);
  10912. cli.set_connection_timeout(30);
  10913. bool callback_called = false;
  10914. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10915. EXPECT_NE(session, nullptr);
  10916. callback_called = true;
  10917. return SSLVerifierResponse::CertificateAccepted;
  10918. });
  10919. auto res = cli.Get("/test");
  10920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10921. EXPECT_EQ(200, res->status);
  10922. EXPECT_TRUE(callback_called);
  10923. }
  10924. TEST(SessionVerifierTest, CertificateRejected) {
  10925. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10926. ASSERT_TRUE(svr.is_valid());
  10927. svr.Get("/test", [](const Request &, Response &res) {
  10928. res.set_content("ok", "text/plain");
  10929. });
  10930. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10931. auto se = detail::scope_exit([&] {
  10932. svr.stop();
  10933. t.join();
  10934. });
  10935. svr.wait_until_ready();
  10936. SSLClient cli(HOST, PORT);
  10937. cli.enable_server_certificate_verification(false);
  10938. cli.set_connection_timeout(30);
  10939. bool callback_called = false;
  10940. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10941. EXPECT_NE(session, nullptr);
  10942. callback_called = true;
  10943. return SSLVerifierResponse::CertificateRejected;
  10944. });
  10945. auto res = cli.Get("/test");
  10946. EXPECT_FALSE(res);
  10947. EXPECT_TRUE(callback_called);
  10948. }
  10949. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10950. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10951. ASSERT_TRUE(svr.is_valid());
  10952. svr.Get("/test", [](const Request &, Response &res) {
  10953. res.set_content("ok", "text/plain");
  10954. });
  10955. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10956. auto se = detail::scope_exit([&] {
  10957. svr.stop();
  10958. t.join();
  10959. });
  10960. svr.wait_until_ready();
  10961. // NoDecisionMade with verification disabled should succeed (no default check)
  10962. SSLClient cli(HOST, PORT);
  10963. cli.enable_server_certificate_verification(false);
  10964. cli.set_connection_timeout(30);
  10965. bool callback_called = false;
  10966. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10967. EXPECT_NE(session, nullptr);
  10968. callback_called = true;
  10969. return SSLVerifierResponse::NoDecisionMade;
  10970. });
  10971. auto res = cli.Get("/test");
  10972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10973. EXPECT_EQ(200, res->status);
  10974. EXPECT_TRUE(callback_called);
  10975. }
  10976. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10977. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10978. ASSERT_TRUE(svr.is_valid());
  10979. svr.Get("/test", [](const Request &, Response &res) {
  10980. res.set_content("ok", "text/plain");
  10981. });
  10982. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10983. auto se = detail::scope_exit([&] {
  10984. svr.stop();
  10985. t.join();
  10986. });
  10987. svr.wait_until_ready();
  10988. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10989. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10990. // so we only check that the request fails, not whether the callback was
  10991. // called.
  10992. SSLClient cli(HOST, PORT);
  10993. cli.enable_server_certificate_verification(true);
  10994. cli.set_connection_timeout(30);
  10995. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10996. EXPECT_NE(session, nullptr);
  10997. return SSLVerifierResponse::NoDecisionMade;
  10998. });
  10999. auto res = cli.Get("/test");
  11000. EXPECT_FALSE(res);
  11001. }
  11002. TEST(SSLClientServerTest, ClientCAListFromPem) {
  11003. // Test SSL server using PemMemory constructor with client CA certificates
  11004. // Read PEM files
  11005. std::string server_cert_pem, server_key_pem, client_ca_pem;
  11006. read_file(SERVER_CERT_FILE, server_cert_pem);
  11007. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11008. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11009. // Create SSLServer with PemMemory constructor including client CA
  11010. SSLServer::PemMemory server_pem = {
  11011. server_cert_pem.c_str(),
  11012. server_cert_pem.size(),
  11013. server_key_pem.c_str(),
  11014. server_key_pem.size(),
  11015. client_ca_pem.c_str(),
  11016. client_ca_pem.size(),
  11017. nullptr // no password for server key
  11018. };
  11019. SSLServer svr(server_pem);
  11020. ASSERT_TRUE(svr.is_valid());
  11021. // No SSL error should be recorded for valid setup
  11022. EXPECT_EQ(0, svr.ssl_last_error());
  11023. // Set up server endpoints
  11024. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  11025. res.set_content("ok", "text/plain");
  11026. });
  11027. // Start server in a thread
  11028. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  11029. svr.wait_until_ready();
  11030. // Connect with client certificate (using constructor with paths)
  11031. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11032. cli.enable_server_certificate_verification(false);
  11033. auto res = cli.Get("/test-pem-ca");
  11034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11035. EXPECT_EQ(200, res->status);
  11036. EXPECT_EQ("ok", res->body);
  11037. svr.stop();
  11038. server_thread.join();
  11039. }
  11040. #endif
  11041. #ifdef _WIN32
  11042. TEST(CleanupTest, WSACleanup) {
  11043. int ret = WSACleanup();
  11044. ASSERT_EQ(0, ret);
  11045. }
  11046. #endif
  11047. #ifndef CPPHTTPLIB_SSL_ENABLED
  11048. TEST(NoSSLSupport, SimpleInterface) {
  11049. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  11050. }
  11051. #endif
  11052. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11053. TEST(InvalidScheme, SimpleInterface) {
  11054. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11055. }
  11056. #endif
  11057. TEST(NoScheme, SimpleInterface) {
  11058. Client cli("yahoo.com:80");
  11059. ASSERT_TRUE(cli.is_valid());
  11060. }
  11061. TEST(SendAPI, SimpleInterface_Online) {
  11062. Client cli("http://yahoo.com");
  11063. Request req;
  11064. req.method = "GET";
  11065. req.path = "/";
  11066. auto res = cli.send(req);
  11067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11068. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11069. }
  11070. TEST(SendAPI, WithParamsInRequest) {
  11071. Server svr;
  11072. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11073. EXPECT_TRUE(req.has_param("test"));
  11074. EXPECT_EQ("test_value", req.get_param_value("test"));
  11075. });
  11076. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11077. auto se = detail::scope_exit([&] {
  11078. svr.stop();
  11079. t.join();
  11080. ASSERT_FALSE(svr.is_running());
  11081. });
  11082. svr.wait_until_ready();
  11083. Client cli(HOST, PORT);
  11084. {
  11085. Request req;
  11086. req.method = "GET";
  11087. req.path = "/";
  11088. req.params.emplace("test", "test_value");
  11089. auto res = cli.send(req);
  11090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11091. }
  11092. {
  11093. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11095. }
  11096. }
  11097. TEST(ClientImplMethods, GetSocketTest) {
  11098. httplib::Server svr;
  11099. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11100. res.status = StatusCode::OK_200;
  11101. });
  11102. auto port = svr.bind_to_any_port("127.0.0.1");
  11103. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11104. auto se = detail::scope_exit([&] {
  11105. svr.stop();
  11106. thread.join();
  11107. ASSERT_FALSE(svr.is_running());
  11108. });
  11109. svr.wait_until_ready();
  11110. {
  11111. httplib::Client cli("127.0.0.1", port);
  11112. cli.set_keep_alive(true);
  11113. // Use the behavior of cpp-httplib of opening the connection
  11114. // only when the first request happens. If that changes,
  11115. // this test would be obsolete.
  11116. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11117. // This also implicitly tests the server. But other tests would fail much
  11118. // earlier than this one to be considered.
  11119. auto res = cli.Get("/");
  11120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11121. EXPECT_EQ(StatusCode::OK_200, res->status);
  11122. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11123. }
  11124. }
  11125. #ifdef CPPHTTPLIB_SSL_ENABLED
  11126. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11127. Client cli("http://yahoo.com");
  11128. auto res = cli.Get("/");
  11129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11130. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11131. cli.set_follow_location(true);
  11132. res = cli.Get("/");
  11133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11134. EXPECT_EQ(StatusCode::OK_200, res->status);
  11135. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11136. }
  11137. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11138. Client cli("https://yahoo.com");
  11139. auto res = cli.Get("/");
  11140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11141. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11142. cli.set_follow_location(true);
  11143. res = cli.Get("/");
  11144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11145. EXPECT_EQ(StatusCode::OK_200, res->status);
  11146. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11147. }
  11148. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11149. Client cli("https://yahoo.com");
  11150. auto res = cli.Get("/");
  11151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11152. ASSERT_FALSE(!res);
  11153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11154. ASSERT_FALSE(res == nullptr);
  11155. ASSERT_TRUE(res != nullptr);
  11156. EXPECT_EQ(Error::Success, res.error());
  11157. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11158. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11159. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11160. cli.set_follow_location(true);
  11161. res = cli.Get("/");
  11162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11163. EXPECT_EQ(Error::Success, res.error());
  11164. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11165. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11166. EXPECT_EQ(StatusCode::OK_200, res->status);
  11167. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11168. }
  11169. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11170. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11171. Client cli("https://cdnjs.cloudflare.com");
  11172. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11173. Headers{{"Accept-Encoding", "br"}});
  11174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11175. EXPECT_EQ(StatusCode::OK_200, res->status);
  11176. EXPECT_EQ(287630U, res->body.size());
  11177. EXPECT_EQ("application/javascript; charset=utf-8",
  11178. res->get_header_value("Content-Type"));
  11179. }
  11180. #endif
  11181. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11182. #undef REDIR_HOST // Silence compiler warning
  11183. #define REDIR_HOST "https://httpbingo.org"
  11184. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11185. Client cli(REDIR_HOST);
  11186. cli.set_follow_location(true);
  11187. auto res =
  11188. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11190. EXPECT_EQ(StatusCode::OK_200, res->status);
  11191. }
  11192. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11193. Client cli(REDIR_HOST);
  11194. cli.set_follow_location(true);
  11195. Params params;
  11196. params.emplace("url", "http://example.com");
  11197. params.emplace("status_code", "302");
  11198. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11200. EXPECT_EQ(StatusCode::OK_200, res->status);
  11201. }
  11202. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11203. Client cli(REDIR_HOST);
  11204. cli.set_follow_location(true);
  11205. Params params;
  11206. params.emplace("url", "http://example.com");
  11207. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11209. EXPECT_EQ(StatusCode::OK_200, res->status);
  11210. }
  11211. TEST(HttpToHttpsRedirectTest, CertFile) {
  11212. auto ssl_port = PORT + 1;
  11213. Server svr;
  11214. ASSERT_TRUE(svr.is_valid());
  11215. svr.Get("/index", [&](const Request &, Response &res) {
  11216. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11217. "/index");
  11218. svr.stop();
  11219. });
  11220. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11221. ASSERT_TRUE(ssl_svr.is_valid());
  11222. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11223. res.set_content("test", "text/plain");
  11224. ssl_svr.stop();
  11225. });
  11226. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11227. thread t2 =
  11228. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11229. auto se = detail::scope_exit([&] {
  11230. t2.join();
  11231. t.join();
  11232. ASSERT_FALSE(svr.is_running());
  11233. });
  11234. svr.wait_until_ready();
  11235. ssl_svr.wait_until_ready();
  11236. Client cli("127.0.0.1", PORT);
  11237. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11238. cli.enable_server_certificate_verification(true);
  11239. cli.set_follow_location(true);
  11240. cli.set_connection_timeout(30);
  11241. auto res = cli.Get("/index");
  11242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11243. ASSERT_EQ(StatusCode::OK_200, res->status);
  11244. }
  11245. TEST(SSLClientRedirectTest, CertFile) {
  11246. auto ssl_port = PORT + 1;
  11247. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11248. ASSERT_TRUE(ssl_svr1.is_valid());
  11249. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11250. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11251. "/index");
  11252. ssl_svr1.stop();
  11253. });
  11254. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11255. ASSERT_TRUE(ssl_svr2.is_valid());
  11256. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11257. res.set_content("test", "text/plain");
  11258. ssl_svr2.stop();
  11259. });
  11260. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11261. thread t2 =
  11262. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11263. auto se = detail::scope_exit([&] {
  11264. t2.join();
  11265. t.join();
  11266. ASSERT_FALSE(ssl_svr1.is_running());
  11267. });
  11268. ssl_svr1.wait_until_ready();
  11269. ssl_svr2.wait_until_ready();
  11270. SSLClient cli("127.0.0.1", PORT);
  11271. std::string cert;
  11272. read_file(SERVER_CERT2_FILE, cert);
  11273. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11274. cli.enable_server_certificate_verification(true);
  11275. cli.set_follow_location(true);
  11276. cli.set_connection_timeout(30);
  11277. auto res = cli.Get("/index");
  11278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11279. ASSERT_EQ(StatusCode::OK_200, res->status);
  11280. }
  11281. #endif
  11282. #ifdef CPPHTTPLIB_SSL_ENABLED
  11283. // Test that set_ca_cert_store() skips system certs (consistent with
  11284. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11285. // should be trusted - system certs should NOT be loaded.
  11286. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11287. // Load a specific cert that is NOT a system CA cert
  11288. std::string cert;
  11289. read_file(SERVER_CERT2_FILE, cert);
  11290. SSLClient cli("google.com");
  11291. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11292. cli.enable_server_certificate_verification(true);
  11293. // This should FAIL because:
  11294. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11295. // 2. System certs should NOT be loaded when custom store is set
  11296. // If system certs WERE loaded, this would succeed
  11297. auto res = cli.Get("/");
  11298. ASSERT_FALSE(res);
  11299. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11300. }
  11301. // Same as above, but through the native store handle path. Regression test:
  11302. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11303. // merged system certs into the user-provided store.
  11304. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11305. std::string cert;
  11306. read_file(SERVER_CERT2_FILE, cert);
  11307. SSLClient cli("google.com");
  11308. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11309. cli.enable_server_certificate_verification(true);
  11310. auto res = cli.Get("/");
  11311. ASSERT_FALSE(res);
  11312. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11313. }
  11314. // A custom store set via the native handle must still verify a server whose
  11315. // cert it does contain.
  11316. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11317. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11318. ASSERT_TRUE(svr.is_valid());
  11319. svr.Get("/test", [&](const Request &, Response &res) {
  11320. res.set_content("test", "text/plain");
  11321. });
  11322. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11323. auto se = detail::scope_exit([&] {
  11324. svr.stop();
  11325. t.join();
  11326. ASSERT_FALSE(svr.is_running());
  11327. });
  11328. svr.wait_until_ready();
  11329. SSLClient cli("127.0.0.1", PORT);
  11330. std::string cert;
  11331. read_file(SERVER_CERT2_FILE, cert);
  11332. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11333. cli.enable_server_certificate_verification(true);
  11334. cli.set_connection_timeout(30);
  11335. auto res = cli.Get("/test");
  11336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11337. ASSERT_EQ(StatusCode::OK_200, res->status);
  11338. }
  11339. // CA certs loaded through the universal Client must be transferred to the
  11340. // client created internally for following an HTTPS redirect. Regression test:
  11341. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11342. // the CA data for redirect transfer.
  11343. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11344. auto ssl_port = PORT + 1;
  11345. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11346. ASSERT_TRUE(ssl_svr1.is_valid());
  11347. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11348. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11349. "/index");
  11350. });
  11351. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11352. ASSERT_TRUE(ssl_svr2.is_valid());
  11353. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11354. res.set_content("test", "text/plain");
  11355. });
  11356. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11357. thread t2 =
  11358. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11359. auto se = detail::scope_exit([&] {
  11360. ssl_svr2.stop();
  11361. ssl_svr1.stop();
  11362. t2.join();
  11363. t.join();
  11364. ASSERT_FALSE(ssl_svr1.is_running());
  11365. });
  11366. ssl_svr1.wait_until_ready();
  11367. ssl_svr2.wait_until_ready();
  11368. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11369. std::string cert;
  11370. read_file(SERVER_CERT2_FILE, cert);
  11371. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11372. cli.enable_server_certificate_verification(true);
  11373. cli.set_follow_location(true);
  11374. cli.set_connection_timeout(30);
  11375. auto res = cli.Get("/index");
  11376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11377. ASSERT_EQ(StatusCode::OK_200, res->status);
  11378. }
  11379. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11380. // so a host signed by a system CA verifies even though a custom CA is set
  11381. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11382. std::string cert;
  11383. read_file(SERVER_CERT2_FILE, cert);
  11384. SSLClient cli("google.com");
  11385. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11386. cli.enable_system_ca(true);
  11387. cli.enable_server_certificate_verification(true);
  11388. auto res = cli.Get("/");
  11389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11390. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11391. }
  11392. // The custom CA remains effective when combined with the system CA
  11393. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11394. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11395. ASSERT_TRUE(svr.is_valid());
  11396. svr.Get("/test", [&](const Request &, Response &res) {
  11397. res.set_content("test", "text/plain");
  11398. });
  11399. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11400. auto se = detail::scope_exit([&] {
  11401. svr.stop();
  11402. t.join();
  11403. ASSERT_FALSE(svr.is_running());
  11404. });
  11405. svr.wait_until_ready();
  11406. SSLClient cli("127.0.0.1", PORT);
  11407. std::string cert;
  11408. read_file(SERVER_CERT2_FILE, cert);
  11409. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11410. cli.enable_system_ca(true);
  11411. cli.enable_server_certificate_verification(true);
  11412. cli.set_connection_timeout(30);
  11413. auto res = cli.Get("/test");
  11414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11415. ASSERT_EQ(StatusCode::OK_200, res->status);
  11416. }
  11417. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11418. // skip chain verification entirely (only the certificate identity was
  11419. // checked), so a server presenting an untrusted certificate with a matching
  11420. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11421. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11422. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11423. ASSERT_TRUE(svr.is_valid());
  11424. svr.Get("/test", [&](const Request &, Response &res) {
  11425. res.set_content("test", "text/plain");
  11426. });
  11427. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11428. auto se = detail::scope_exit([&] {
  11429. svr.stop();
  11430. t.join();
  11431. ASSERT_FALSE(svr.is_running());
  11432. });
  11433. svr.wait_until_ready();
  11434. SSLClient cli("127.0.0.1", PORT);
  11435. std::string cert;
  11436. // A trusted CA that did not sign the server certificate. The server cert
  11437. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11438. // this connection.
  11439. read_file(CLIENT_CA_CERT_FILE, cert);
  11440. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11441. cli.enable_server_certificate_verification(true);
  11442. cli.set_connection_timeout(30);
  11443. auto res = cli.Get("/test");
  11444. ASSERT_FALSE(res);
  11445. }
  11446. // enable_system_ca(false) prevents system CA loading entirely
  11447. TEST(SSLClientTest, DisableSystemCa_Online) {
  11448. SSLClient cli("google.com");
  11449. cli.enable_system_ca(false);
  11450. cli.enable_server_certificate_verification(true);
  11451. auto res = cli.Get("/");
  11452. ASSERT_FALSE(res);
  11453. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11454. // itself when the CA chain is empty
  11455. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11456. res.error() == Error::SSLConnection);
  11457. }
  11458. // The universal Client forwards enable_system_ca()
  11459. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11460. std::string cert;
  11461. read_file(SERVER_CERT2_FILE, cert);
  11462. Client cli("https://google.com");
  11463. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11464. cli.enable_system_ca(true);
  11465. cli.enable_server_certificate_verification(true);
  11466. auto res = cli.Get("/");
  11467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11468. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11469. }
  11470. // The system CA policy must carry over to the client created internally for
  11471. // following a cross-host HTTPS redirect
  11472. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11473. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11474. ASSERT_TRUE(svr.is_valid());
  11475. svr.Get("/index", [&](const Request &, Response &res) {
  11476. res.set_redirect("https://www.google.com/");
  11477. });
  11478. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11479. auto se = detail::scope_exit([&] {
  11480. svr.stop();
  11481. t.join();
  11482. ASSERT_FALSE(svr.is_running());
  11483. });
  11484. svr.wait_until_ready();
  11485. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11486. std::string cert;
  11487. read_file(SERVER_CERT2_FILE, cert);
  11488. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11489. cli.enable_system_ca(true);
  11490. cli.enable_server_certificate_verification(true);
  11491. cli.set_follow_location(true);
  11492. cli.set_connection_timeout(30);
  11493. // Receiving any response proves the redirect client completed the TLS
  11494. // handshake with a system-CA-signed host
  11495. auto res = cli.Get("/index");
  11496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11497. }
  11498. TEST(MultipartFormDataTest, LargeData) {
  11499. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11500. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11501. const ContentReader &content_reader) {
  11502. if (req.is_multipart_form_data()) {
  11503. std::vector<FormData> items;
  11504. content_reader(
  11505. [&](const FormData &file) {
  11506. items.push_back(file);
  11507. return true;
  11508. },
  11509. [&](const char *data, size_t data_length) {
  11510. items.back().content.append(data, data_length);
  11511. return true;
  11512. });
  11513. EXPECT_TRUE(std::string(items[0].name) == "document");
  11514. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11515. EXPECT_TRUE(items[0].filename == "2MB_data");
  11516. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11517. EXPECT_TRUE(items[1].name == "hello");
  11518. EXPECT_TRUE(items[1].content == "world");
  11519. EXPECT_TRUE(items[1].filename == "");
  11520. EXPECT_TRUE(items[1].content_type == "");
  11521. } else {
  11522. std::string body;
  11523. content_reader([&](const char *data, size_t data_length) {
  11524. body.append(data, data_length);
  11525. return true;
  11526. });
  11527. }
  11528. });
  11529. auto port = svr.bind_to_any_port(HOST);
  11530. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11531. auto se = detail::scope_exit([&] {
  11532. svr.stop();
  11533. t.join();
  11534. ASSERT_FALSE(svr.is_running());
  11535. });
  11536. svr.wait_until_ready();
  11537. {
  11538. std::string data(1024 * 1024 * 2, '.');
  11539. std::stringstream buffer;
  11540. buffer << data;
  11541. SSLClient cli(HOST, port);
  11542. cli.enable_server_certificate_verification(false);
  11543. UploadFormDataItems items{
  11544. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11545. {"hello", "world", "", ""},
  11546. };
  11547. auto res = cli.Post("/post", items);
  11548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11549. ASSERT_EQ(StatusCode::OK_200, res->status);
  11550. }
  11551. }
  11552. TEST(MultipartFormDataTest, DataProviderItems) {
  11553. std::random_device seed_gen;
  11554. std::mt19937 random(seed_gen());
  11555. std::string rand1;
  11556. rand1.resize(1000);
  11557. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11558. std::string rand2;
  11559. rand2.resize(3000);
  11560. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11561. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11562. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11563. const ContentReader &content_reader) {
  11564. ASSERT_FALSE(req.is_multipart_form_data());
  11565. std::string body;
  11566. content_reader([&](const char *data, size_t data_length) {
  11567. body.append(data, data_length);
  11568. return true;
  11569. });
  11570. EXPECT_EQ(body, "");
  11571. });
  11572. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11573. const ContentReader &content_reader) {
  11574. ASSERT_TRUE(req.is_multipart_form_data());
  11575. std::vector<FormData> items;
  11576. content_reader(
  11577. [&](const FormData &file) {
  11578. items.push_back(file);
  11579. return true;
  11580. },
  11581. [&](const char *data, size_t data_length) {
  11582. items.back().content.append(data, data_length);
  11583. return true;
  11584. });
  11585. ASSERT_TRUE(items.size() == 2);
  11586. EXPECT_EQ(std::string(items[0].name), "name1");
  11587. EXPECT_EQ(items[0].content, "Testing123");
  11588. EXPECT_EQ(items[0].filename, "filename1");
  11589. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11590. EXPECT_EQ(items[1].name, "name2");
  11591. EXPECT_EQ(items[1].content, "Testing456");
  11592. EXPECT_EQ(items[1].filename, "");
  11593. EXPECT_EQ(items[1].content_type, "");
  11594. });
  11595. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11596. const ContentReader &content_reader) {
  11597. ASSERT_TRUE(req.is_multipart_form_data());
  11598. std::vector<FormData> items;
  11599. content_reader(
  11600. [&](const FormData &file) {
  11601. items.push_back(file);
  11602. return true;
  11603. },
  11604. [&](const char *data, size_t data_length) {
  11605. items.back().content.append(data, data_length);
  11606. return true;
  11607. });
  11608. ASSERT_TRUE(items.size() == 2);
  11609. EXPECT_EQ(items[0].name, "name3");
  11610. EXPECT_EQ(items[0].content, rand1);
  11611. EXPECT_EQ(items[0].filename, "filename3");
  11612. EXPECT_EQ(items[0].content_type, "");
  11613. EXPECT_EQ(items[1].name, "name4");
  11614. EXPECT_EQ(items[1].content, rand2);
  11615. EXPECT_EQ(items[1].filename, "filename4");
  11616. EXPECT_EQ(items[1].content_type, "");
  11617. });
  11618. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11619. const ContentReader &content_reader) {
  11620. ASSERT_TRUE(req.is_multipart_form_data());
  11621. std::vector<FormData> items;
  11622. content_reader(
  11623. [&](const FormData &file) {
  11624. items.push_back(file);
  11625. return true;
  11626. },
  11627. [&](const char *data, size_t data_length) {
  11628. items.back().content.append(data, data_length);
  11629. return true;
  11630. });
  11631. ASSERT_TRUE(items.size() == 4);
  11632. EXPECT_EQ(std::string(items[0].name), "name1");
  11633. EXPECT_EQ(items[0].content, "Testing123");
  11634. EXPECT_EQ(items[0].filename, "filename1");
  11635. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11636. EXPECT_EQ(items[1].name, "name2");
  11637. EXPECT_EQ(items[1].content, "Testing456");
  11638. EXPECT_EQ(items[1].filename, "");
  11639. EXPECT_EQ(items[1].content_type, "");
  11640. EXPECT_EQ(items[2].name, "name3");
  11641. EXPECT_EQ(items[2].content, rand1);
  11642. EXPECT_EQ(items[2].filename, "filename3");
  11643. EXPECT_EQ(items[2].content_type, "");
  11644. EXPECT_EQ(items[3].name, "name4");
  11645. EXPECT_EQ(items[3].content, rand2);
  11646. EXPECT_EQ(items[3].filename, "filename4");
  11647. EXPECT_EQ(items[3].content_type, "");
  11648. });
  11649. auto port = svr.bind_to_any_port("localhost");
  11650. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11651. auto se = detail::scope_exit([&] {
  11652. svr.stop();
  11653. t.join();
  11654. ASSERT_FALSE(svr.is_running());
  11655. });
  11656. svr.wait_until_ready();
  11657. {
  11658. SSLClient cli("localhost", port);
  11659. cli.enable_server_certificate_verification(false);
  11660. UploadFormDataItems items{
  11661. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11662. {"name2", "Testing456", "", ""}, // not a file
  11663. };
  11664. {
  11665. auto res = cli.Post("/post-none", {}, {}, {});
  11666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11667. ASSERT_EQ(StatusCode::OK_200, res->status);
  11668. }
  11669. FormDataProviderItems providers;
  11670. {
  11671. auto res =
  11672. cli.Post("/post-items", {}, items, providers); // empty providers
  11673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11674. ASSERT_EQ(StatusCode::OK_200, res->status);
  11675. }
  11676. providers.push_back({"name3",
  11677. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11678. // test the offset is given correctly at each step
  11679. if (!offset)
  11680. sink.os.write(rand1.data(), 30);
  11681. else if (offset == 30)
  11682. sink.os.write(rand1.data() + 30, 300);
  11683. else if (offset == 330)
  11684. sink.os.write(rand1.data() + 330, 670);
  11685. else if (offset == rand1.size())
  11686. sink.done();
  11687. return true;
  11688. },
  11689. "filename3",
  11690. {}});
  11691. providers.push_back({"name4",
  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(rand2.data(), 2000);
  11696. else if (offset == 2000)
  11697. sink.os.write(rand2.data() + 2000, 1);
  11698. else if (offset == 2001)
  11699. sink.os.write(rand2.data() + 2001, 999);
  11700. else if (offset == rand2.size())
  11701. sink.done();
  11702. return true;
  11703. },
  11704. "filename4",
  11705. {}});
  11706. {
  11707. auto res = cli.Post("/post-providers", {}, {}, providers);
  11708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11709. ASSERT_EQ(StatusCode::OK_200, res->status);
  11710. }
  11711. {
  11712. auto res = cli.Post("/post-both", {}, items, providers);
  11713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11714. ASSERT_EQ(StatusCode::OK_200, res->status);
  11715. }
  11716. }
  11717. }
  11718. TEST(MultipartFormDataTest, BadHeader) {
  11719. Server svr;
  11720. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11721. res.set_content("ok", "text/plain");
  11722. });
  11723. thread t = thread([&] { svr.listen(HOST, PORT); });
  11724. auto se = detail::scope_exit([&] {
  11725. svr.stop();
  11726. t.join();
  11727. ASSERT_FALSE(svr.is_running());
  11728. });
  11729. svr.wait_until_ready();
  11730. const std::string body =
  11731. "This is the preamble. It is to be ignored, though it\r\n"
  11732. "is a handy place for composition agents to include an\r\n"
  11733. "explanatory note to non-MIME conformant readers.\r\n"
  11734. "\r\n"
  11735. "\r\n"
  11736. "--simple boundary\r\n"
  11737. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11738. ": BAD...\r\n"
  11739. "\r\n"
  11740. "value1\r\n"
  11741. "--simple boundary\r\n"
  11742. "Content-Disposition: form-data; name=\"field2\"; "
  11743. "filename=\"example.txt\"\r\n"
  11744. "\r\n"
  11745. "value2\r\n"
  11746. "--simple boundary--\r\n"
  11747. "This is the epilogue. It is also to be ignored.\r\n";
  11748. std::string content_type =
  11749. R"(multipart/form-data; boundary="simple boundary")";
  11750. Client cli(HOST, PORT);
  11751. auto res = cli.Post("/post", body, content_type.c_str());
  11752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11753. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11754. }
  11755. TEST(MultipartFormDataTest, WithPreamble) {
  11756. Server svr;
  11757. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11758. res.set_content("ok", "text/plain");
  11759. });
  11760. thread t = thread([&] { svr.listen(HOST, PORT); });
  11761. auto se = detail::scope_exit([&] {
  11762. svr.stop();
  11763. t.join();
  11764. ASSERT_FALSE(svr.is_running());
  11765. });
  11766. svr.wait_until_ready();
  11767. const std::string body =
  11768. "This is the preamble. It is to be ignored, though it\r\n"
  11769. "is a handy place for composition agents to include an\r\n"
  11770. "explanatory note to non-MIME conformant readers.\r\n"
  11771. "\r\n"
  11772. "\r\n"
  11773. "--simple boundary\r\n"
  11774. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11775. "\r\n"
  11776. "value1\r\n"
  11777. "--simple boundary\r\n"
  11778. "Content-Disposition: form-data; name=\"field2\"; "
  11779. "filename=\"example.txt\"\r\n"
  11780. "\r\n"
  11781. "value2\r\n"
  11782. "--simple boundary--\r\n"
  11783. "This is the epilogue. It is also to be ignored.\r\n";
  11784. std::string content_type =
  11785. R"(multipart/form-data; boundary="simple boundary")";
  11786. Client cli(HOST, PORT);
  11787. auto res = cli.Post("/post", body, content_type.c_str());
  11788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11789. EXPECT_EQ(StatusCode::OK_200, res->status);
  11790. }
  11791. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11792. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11793. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11794. const ContentReader &content_reader) {
  11795. if (req.is_multipart_form_data()) {
  11796. std::vector<FormData> items;
  11797. content_reader(
  11798. [&](const FormData &file) {
  11799. items.push_back(file);
  11800. return true;
  11801. },
  11802. [&](const char *data, size_t data_length) {
  11803. items.back().content.append(data, data_length);
  11804. return true;
  11805. });
  11806. EXPECT_TRUE(std::string(items[0].name) == "document");
  11807. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11808. EXPECT_TRUE(items[0].filename == "2MB_data");
  11809. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11810. EXPECT_TRUE(items[1].name == "hello");
  11811. EXPECT_TRUE(items[1].content == "world");
  11812. EXPECT_TRUE(items[1].filename == "");
  11813. EXPECT_TRUE(items[1].content_type == "");
  11814. } else {
  11815. std::string body;
  11816. content_reader([&](const char *data, size_t data_length) {
  11817. body.append(data, data_length);
  11818. return true;
  11819. });
  11820. }
  11821. });
  11822. auto port = svr.bind_to_any_port("localhost");
  11823. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11824. auto se = detail::scope_exit([&] {
  11825. svr.stop();
  11826. t.join();
  11827. ASSERT_FALSE(svr.is_running());
  11828. });
  11829. svr.wait_until_ready();
  11830. {
  11831. std::string data(1024 * 1024 * 2, '.');
  11832. std::stringstream buffer;
  11833. buffer << data;
  11834. SSLClient cli("localhost", port);
  11835. cli.enable_server_certificate_verification(false);
  11836. UploadFormDataItems items{
  11837. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11838. {"hello", "world", "", ""},
  11839. };
  11840. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11842. ASSERT_EQ(StatusCode::OK_200, res->status);
  11843. }
  11844. }
  11845. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11846. std::string data(1024 * 1024 * 2, '&');
  11847. std::stringstream buffer;
  11848. buffer << data;
  11849. Client cli("https://localhost:8080");
  11850. UploadFormDataItems items{
  11851. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11852. {"hello", "world", "", ""},
  11853. };
  11854. for (const char &c : " \t\r\n") {
  11855. auto res =
  11856. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11857. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11858. ASSERT_FALSE(res);
  11859. }
  11860. }
  11861. TEST(MultipartFormDataTest, PutFormData) {
  11862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11863. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11864. const ContentReader &content_reader) {
  11865. if (req.is_multipart_form_data()) {
  11866. std::vector<FormData> items;
  11867. content_reader(
  11868. [&](const FormData &file) {
  11869. items.push_back(file);
  11870. return true;
  11871. },
  11872. [&](const char *data, size_t data_length) {
  11873. items.back().content.append(data, data_length);
  11874. return true;
  11875. });
  11876. EXPECT_TRUE(std::string(items[0].name) == "document");
  11877. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11878. EXPECT_TRUE(items[0].filename == "2MB_data");
  11879. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11880. EXPECT_TRUE(items[1].name == "hello");
  11881. EXPECT_TRUE(items[1].content == "world");
  11882. EXPECT_TRUE(items[1].filename == "");
  11883. EXPECT_TRUE(items[1].content_type == "");
  11884. } else {
  11885. std::string body;
  11886. content_reader([&](const char *data, size_t data_length) {
  11887. body.append(data, data_length);
  11888. return true;
  11889. });
  11890. }
  11891. });
  11892. auto port = svr.bind_to_any_port("localhost");
  11893. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11894. auto se = detail::scope_exit([&] {
  11895. svr.stop();
  11896. t.join();
  11897. ASSERT_FALSE(svr.is_running());
  11898. });
  11899. svr.wait_until_ready();
  11900. {
  11901. std::string data(1024 * 1024 * 2, '&');
  11902. std::stringstream buffer;
  11903. buffer << data;
  11904. SSLClient cli("localhost", port);
  11905. cli.enable_server_certificate_verification(false);
  11906. UploadFormDataItems items{
  11907. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11908. {"hello", "world", "", ""},
  11909. };
  11910. auto res = cli.Put("/put", items);
  11911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11912. ASSERT_EQ(StatusCode::OK_200, res->status);
  11913. }
  11914. }
  11915. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11916. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11917. svr.Put("/put_customboundary",
  11918. [&](const Request &req, const Response & /*res*/,
  11919. const ContentReader &content_reader) {
  11920. if (req.is_multipart_form_data()) {
  11921. std::vector<FormData> items;
  11922. content_reader(
  11923. [&](const FormData &file) {
  11924. items.push_back(file);
  11925. return true;
  11926. },
  11927. [&](const char *data, size_t data_length) {
  11928. items.back().content.append(data, data_length);
  11929. return true;
  11930. });
  11931. EXPECT_TRUE(std::string(items[0].name) == "document");
  11932. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11933. EXPECT_TRUE(items[0].filename == "2MB_data");
  11934. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11935. EXPECT_TRUE(items[1].name == "hello");
  11936. EXPECT_TRUE(items[1].content == "world");
  11937. EXPECT_TRUE(items[1].filename == "");
  11938. EXPECT_TRUE(items[1].content_type == "");
  11939. } else {
  11940. std::string body;
  11941. content_reader([&](const char *data, size_t data_length) {
  11942. body.append(data, data_length);
  11943. return true;
  11944. });
  11945. }
  11946. });
  11947. auto port = svr.bind_to_any_port("localhost");
  11948. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11949. auto se = detail::scope_exit([&] {
  11950. svr.stop();
  11951. t.join();
  11952. ASSERT_FALSE(svr.is_running());
  11953. });
  11954. svr.wait_until_ready();
  11955. {
  11956. std::string data(1024 * 1024 * 2, '&');
  11957. std::stringstream buffer;
  11958. buffer << data;
  11959. SSLClient cli("localhost", port);
  11960. cli.enable_server_certificate_verification(false);
  11961. UploadFormDataItems items{
  11962. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11963. {"hello", "world", "", ""},
  11964. };
  11965. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11967. ASSERT_EQ(StatusCode::OK_200, res->status);
  11968. }
  11969. }
  11970. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11971. std::string data(1024 * 1024 * 2, '&');
  11972. std::stringstream buffer;
  11973. buffer << data;
  11974. Client cli("https://localhost:8080");
  11975. cli.enable_server_certificate_verification(false);
  11976. UploadFormDataItems items{
  11977. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11978. {"hello", "world", "", ""},
  11979. };
  11980. for (const char &c : " \t\r\n") {
  11981. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11982. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11983. ASSERT_FALSE(res);
  11984. }
  11985. }
  11986. TEST(MultipartFormDataTest, AlternateFilename) {
  11987. auto handled = false;
  11988. Server svr;
  11989. svr.Post("/test", [&](const Request &req, Response &res) {
  11990. ASSERT_EQ(2u, req.form.files.size());
  11991. ASSERT_EQ(1u, req.form.fields.size());
  11992. // Test files
  11993. const auto &file1 = req.form.get_file("file1");
  11994. ASSERT_EQ("file1", file1.name);
  11995. ASSERT_EQ("A.txt", file1.filename);
  11996. ASSERT_EQ("text/plain", file1.content_type);
  11997. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11998. const auto &file2 = req.form.get_file("file2");
  11999. ASSERT_EQ("file2", file2.name);
  12000. ASSERT_EQ("a.html", file2.filename);
  12001. ASSERT_EQ("text/html", file2.content_type);
  12002. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  12003. file2.content);
  12004. // Test text field
  12005. const auto &text = req.form.get_field("text");
  12006. ASSERT_EQ("text default", text);
  12007. res.set_content("ok", "text/plain");
  12008. handled = true;
  12009. });
  12010. thread t = thread([&] { svr.listen(HOST, PORT); });
  12011. auto se = detail::scope_exit([&] {
  12012. svr.stop();
  12013. t.join();
  12014. ASSERT_FALSE(svr.is_running());
  12015. ASSERT_TRUE(handled);
  12016. });
  12017. svr.wait_until_ready();
  12018. auto req = "POST /test HTTP/1.1\r\n"
  12019. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12020. "Content-Length: 399\r\n"
  12021. "\r\n"
  12022. "----------\r\n"
  12023. "Content-Disposition: form-data; name=\"text\"\r\n"
  12024. "\r\n"
  12025. "text default\r\n"
  12026. "----------\r\n"
  12027. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  12028. "filename=\"a.txt\"; name=\"file1\"\r\n"
  12029. "Content-Type: text/plain\r\n"
  12030. "\r\n"
  12031. "Content of a.txt.\r\n"
  12032. "\r\n"
  12033. "----------\r\n"
  12034. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  12035. "\"a.html\"\r\n"
  12036. "Content-Type: text/html\r\n"
  12037. "\r\n"
  12038. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  12039. "\r\n"
  12040. "------------\r\n";
  12041. ASSERT_TRUE(send_request(1, req));
  12042. }
  12043. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  12044. auto handled = false;
  12045. Server svr;
  12046. svr.Post("/test", [&](const Request &req, Response &res) {
  12047. // Case-insensitive "utf-8''" prefix with a long value
  12048. const auto &file = req.form.get_file("file1");
  12049. ASSERT_EQ("file1", file.name);
  12050. // 8000 chars exercises both the Content-Disposition parser and the
  12051. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  12052. // Prior to the fix, std::regex_match on this header would cause O(N)
  12053. // stack recursion in libstdc++, leading to SIGSEGV.
  12054. std::string expected_filename(8000, 'A');
  12055. ASSERT_EQ(expected_filename, file.filename);
  12056. res.set_content("ok", "text/plain");
  12057. handled = true;
  12058. });
  12059. thread t = thread([&] { svr.listen(HOST, PORT); });
  12060. auto se = detail::scope_exit([&] {
  12061. svr.stop();
  12062. t.join();
  12063. ASSERT_FALSE(svr.is_running());
  12064. ASSERT_TRUE(handled);
  12065. });
  12066. svr.wait_until_ready();
  12067. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12068. // Regression test for GHSA-qq6v-r583-3h69
  12069. std::string long_filename(8000, 'A');
  12070. std::string body = "----------\r\n"
  12071. "Content-Disposition: form-data; name=\"file1\"; "
  12072. "filename*=\"Utf-8''" +
  12073. long_filename +
  12074. "\"\r\n"
  12075. "\r\n"
  12076. "hello\r\n"
  12077. "------------\r\n";
  12078. auto req = "POST /test HTTP/1.1\r\n"
  12079. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12080. "Content-Length: " +
  12081. std::to_string(body.size()) + "\r\n\r\n" + body;
  12082. ASSERT_TRUE(send_request(1, req));
  12083. }
  12084. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12085. auto handled = false;
  12086. Server svr;
  12087. svr.Post("/test", [&](const Request &req, Response &) {
  12088. ASSERT_EQ(2u, req.form.fields.size());
  12089. const auto &text1 = req.form.get_field("text1");
  12090. ASSERT_EQ("text1", text1);
  12091. const auto &text2 = req.form.get_field("text2");
  12092. ASSERT_EQ("text2", text2);
  12093. handled = true;
  12094. });
  12095. thread t = thread([&] { svr.listen(HOST, PORT); });
  12096. auto se = detail::scope_exit([&] {
  12097. svr.stop();
  12098. t.join();
  12099. ASSERT_FALSE(svr.is_running());
  12100. ASSERT_TRUE(handled);
  12101. });
  12102. svr.wait_until_ready();
  12103. auto req = "POST /test HTTP/1.1\r\n"
  12104. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12105. "Content-Length: 146\r\n"
  12106. "\r\n----------\r\n"
  12107. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12108. "\r\n"
  12109. "text1"
  12110. "\r\n----------\r\n"
  12111. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12112. "\r\n"
  12113. "text2"
  12114. "\r\n------------";
  12115. std::string response;
  12116. ASSERT_TRUE(send_request(1, req, &response));
  12117. ASSERT_EQ("200", response.substr(9, 3));
  12118. }
  12119. TEST(MultipartFormDataTest, ContentLength) {
  12120. auto handled = false;
  12121. Server svr;
  12122. svr.Post("/test", [&](const Request &req, Response &) {
  12123. ASSERT_EQ(2u, req.form.fields.size());
  12124. const auto &text1 = req.form.get_field("text1");
  12125. ASSERT_EQ("text1", text1);
  12126. const auto &text2 = req.form.get_field("text2");
  12127. ASSERT_EQ("text2", text2);
  12128. handled = true;
  12129. });
  12130. thread t = thread([&] { svr.listen(HOST, PORT); });
  12131. auto se = detail::scope_exit([&] {
  12132. svr.stop();
  12133. t.join();
  12134. ASSERT_FALSE(svr.is_running());
  12135. ASSERT_TRUE(handled);
  12136. });
  12137. svr.wait_until_ready();
  12138. auto req = "POST /test HTTP/1.1\r\n"
  12139. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12140. "Content-Length: 167\r\n"
  12141. "\r\n----------\r\n"
  12142. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12143. "Content-Length: 5\r\n"
  12144. "\r\n"
  12145. "text1"
  12146. "\r\n----------\r\n"
  12147. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12148. "\r\n"
  12149. "text2"
  12150. "\r\n------------\r\n";
  12151. std::string response;
  12152. ASSERT_TRUE(send_request(1, req, &response));
  12153. ASSERT_EQ("200", response.substr(9, 3));
  12154. }
  12155. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12156. auto handled = false;
  12157. Server svr;
  12158. svr.Post("/test", [&](const Request &req, Response &) {
  12159. ASSERT_EQ(2u, req.form.fields.size());
  12160. const auto &text1 = req.form.get_field("text1");
  12161. ASSERT_EQ("text1", text1);
  12162. // TODO: Add header access for text fields if needed
  12163. const auto &text2 = req.form.get_field("text2");
  12164. ASSERT_EQ("text2", text2);
  12165. // TODO: Header access for text fields needs to be implemented
  12166. // auto &headers = it->second.headers;
  12167. // ASSERT_EQ(3U, headers.size());
  12168. // auto custom_header = headers.find("x-whatever");
  12169. // ASSERT_TRUE(custom_header != headers.end());
  12170. // ASSERT_NE("customvalue", custom_header->second);
  12171. // ASSERT_EQ("CustomValue", custom_header->second);
  12172. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12173. handled = true;
  12174. });
  12175. thread t = thread([&] { svr.listen(HOST, PORT); });
  12176. auto se = detail::scope_exit([&] {
  12177. svr.stop();
  12178. t.join();
  12179. ASSERT_FALSE(svr.is_running());
  12180. ASSERT_TRUE(handled);
  12181. });
  12182. svr.wait_until_ready();
  12183. auto req = "POST /test HTTP/1.1\r\n"
  12184. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12185. "Content-Length: 232\r\n"
  12186. "\r\n----------\r\n"
  12187. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12188. "Content-Length: 5\r\n"
  12189. "X-Test: 1\r\n"
  12190. "\r\n"
  12191. "text1"
  12192. "\r\n----------\r\n"
  12193. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12194. "Content-Type: text/plain\r\n"
  12195. "X-Whatever: CustomValue\r\n"
  12196. "\r\n"
  12197. "text2"
  12198. "\r\n------------\r\n"
  12199. "That should be disregarded. Not even read";
  12200. std::string response;
  12201. ASSERT_TRUE(send_request(1, req, &response));
  12202. ASSERT_EQ("200", response.substr(9, 3));
  12203. }
  12204. TEST(MultipartFormDataTest, LargeHeader) {
  12205. auto handled = false;
  12206. Server svr;
  12207. svr.Post("/test", [&](const Request &req, Response &) {
  12208. ASSERT_EQ(1u, req.form.fields.size());
  12209. const auto &text = req.form.get_field("name1");
  12210. ASSERT_EQ("text1", text);
  12211. handled = true;
  12212. });
  12213. thread t = thread([&] { svr.listen(HOST, PORT); });
  12214. auto se = detail::scope_exit([&] {
  12215. svr.stop();
  12216. t.join();
  12217. ASSERT_FALSE(svr.is_running());
  12218. ASSERT_TRUE(handled);
  12219. });
  12220. svr.wait_until_ready();
  12221. auto boundary = std::string("cpp-httplib-multipart-data");
  12222. std::string content = "--" + boundary +
  12223. "\r\n"
  12224. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12225. "\r\n"
  12226. "text1\r\n"
  12227. "--" +
  12228. boundary + "--\r\n";
  12229. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12230. "Content-Type: multipart/form-data;boundary=" +
  12231. boundary +
  12232. "\r\n"
  12233. "Content-Length: " +
  12234. std::to_string(content.size()) +
  12235. "\r\n"
  12236. "Dummy-Header: ";
  12237. std::string header_suffix = "\r\n"
  12238. "\r\n";
  12239. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12240. size_t header_dummy_size =
  12241. read_buff_size -
  12242. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12243. auto header_dummy = std::string(header_dummy_size, '@');
  12244. auto req = header_prefix + header_dummy + header_suffix + content;
  12245. std::string response;
  12246. ASSERT_TRUE(send_request(1, req, &response));
  12247. ASSERT_EQ("200", response.substr(9, 3));
  12248. }
  12249. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12250. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12251. // (not chunked Transfer-Encoding) after the streaming refactor.
  12252. auto handled = false;
  12253. Server svr;
  12254. svr.Post("/upload", [&](const Request &req, Response &res) {
  12255. auto cl_it = req.headers.find("Content-Length");
  12256. EXPECT_TRUE(cl_it != req.headers.end());
  12257. auto te_it = req.headers.find("Transfer-Encoding");
  12258. EXPECT_TRUE(te_it == req.headers.end());
  12259. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12260. res.set_content("ok", "text/plain");
  12261. handled = true;
  12262. });
  12263. auto port = svr.bind_to_any_port(HOST);
  12264. auto t = thread([&] { svr.listen_after_bind(); });
  12265. auto se = detail::scope_exit([&] {
  12266. svr.stop();
  12267. t.join();
  12268. ASSERT_FALSE(svr.is_running());
  12269. ASSERT_TRUE(handled);
  12270. });
  12271. svr.wait_until_ready();
  12272. UploadFormDataItems items = {
  12273. {"field1", "hello", "", "text/plain"},
  12274. {"file1", "world", "test.txt", "application/octet-stream"},
  12275. };
  12276. Client cli(HOST, port);
  12277. auto res = cli.Post("/upload", {}, items);
  12278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12279. EXPECT_EQ(StatusCode::OK_200, res->status);
  12280. }
  12281. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12282. // Verify that make_multipart_content_provider coalesces many small segments
  12283. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12284. constexpr size_t kItemCount = 1000;
  12285. UploadFormDataItems items;
  12286. items.reserve(kItemCount);
  12287. for (size_t i = 0; i < kItemCount; i++) {
  12288. items.push_back(
  12289. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12290. }
  12291. const std::string boundary = "----test-boundary";
  12292. auto content_length = detail::get_multipart_content_length(items, boundary);
  12293. auto provider = detail::make_multipart_content_provider(items, boundary);
  12294. // Drive the provider the same way write_content_with_progress does
  12295. size_t write_count = 0;
  12296. size_t total_bytes = 0;
  12297. DataSink sink;
  12298. size_t offset = 0;
  12299. sink.write = [&](const char *d, size_t l) -> bool {
  12300. (void)d;
  12301. write_count++;
  12302. total_bytes += l;
  12303. offset += l;
  12304. return true;
  12305. };
  12306. sink.is_writable = []() -> bool { return true; };
  12307. while (offset < content_length) {
  12308. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12309. }
  12310. EXPECT_EQ(content_length, total_bytes);
  12311. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12312. // With buffering into 64KB blocks, write_count should be much smaller.
  12313. auto segment_count = 3 * kItemCount + 1;
  12314. EXPECT_LT(write_count, segment_count / 10);
  12315. }
  12316. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12317. // Integration test: send many UploadFormDataItems and verify the server
  12318. // receives all of them correctly (#2410).
  12319. constexpr size_t kItemCount = 500;
  12320. auto handled = false;
  12321. Server svr;
  12322. svr.Post("/upload", [&](const Request &req, Response &res) {
  12323. EXPECT_EQ(kItemCount, req.form.fields.size());
  12324. for (size_t i = 0; i < kItemCount; i++) {
  12325. auto key = "field" + std::to_string(i);
  12326. auto val = "value" + std::to_string(i);
  12327. auto it = req.form.fields.find(key);
  12328. if (it != req.form.fields.end()) {
  12329. EXPECT_EQ(val, it->second.content);
  12330. } else {
  12331. ADD_FAILURE() << "Missing field: " << key;
  12332. }
  12333. }
  12334. res.set_content("ok", "text/plain");
  12335. handled = true;
  12336. });
  12337. auto port = svr.bind_to_any_port(HOST);
  12338. auto t = thread([&] { svr.listen_after_bind(); });
  12339. auto se = detail::scope_exit([&] {
  12340. svr.stop();
  12341. t.join();
  12342. ASSERT_FALSE(svr.is_running());
  12343. ASSERT_TRUE(handled);
  12344. });
  12345. svr.wait_until_ready();
  12346. UploadFormDataItems items;
  12347. items.reserve(kItemCount);
  12348. for (size_t i = 0; i < kItemCount; i++) {
  12349. items.push_back(
  12350. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12351. }
  12352. Client cli(HOST, port);
  12353. auto res = cli.Post("/upload", items);
  12354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12355. EXPECT_EQ(StatusCode::OK_200, res->status);
  12356. }
  12357. TEST(MultipartFormDataTest, MakeFileProvider) {
  12358. // Verify make_file_provider sends a file's contents correctly.
  12359. const std::string file_content(4096, 'Z');
  12360. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12361. {
  12362. std::ofstream ofs(tmp_path, std::ios::binary);
  12363. ofs.write(file_content.data(),
  12364. static_cast<std::streamsize>(file_content.size()));
  12365. }
  12366. auto handled = false;
  12367. Server svr;
  12368. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12369. const ContentReader &content_reader) {
  12370. ASSERT_TRUE(req.is_multipart_form_data());
  12371. std::vector<FormData> items;
  12372. content_reader(
  12373. [&](const FormData &file) {
  12374. items.push_back(file);
  12375. return true;
  12376. },
  12377. [&](const char *data, size_t data_length) {
  12378. items.back().content.append(data, data_length);
  12379. return true;
  12380. });
  12381. ASSERT_EQ(1u, items.size());
  12382. EXPECT_EQ("myfile", items[0].name);
  12383. EXPECT_EQ("data.bin", items[0].filename);
  12384. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12385. EXPECT_EQ(file_content, items[0].content);
  12386. handled = true;
  12387. });
  12388. auto port = svr.bind_to_any_port(HOST);
  12389. auto t = thread([&] { svr.listen_after_bind(); });
  12390. auto se = detail::scope_exit([&] {
  12391. svr.stop();
  12392. t.join();
  12393. ASSERT_FALSE(svr.is_running());
  12394. ASSERT_TRUE(handled);
  12395. std::remove(tmp_path.c_str());
  12396. });
  12397. svr.wait_until_ready();
  12398. FormDataProviderItems providers;
  12399. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12400. "application/octet-stream"));
  12401. Client cli(HOST, port);
  12402. auto res = cli.Post("/upload", {}, {}, providers);
  12403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12404. EXPECT_EQ(StatusCode::OK_200, res->status);
  12405. }
  12406. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12407. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12408. // (100) headers is rejected with a 400 Bad Request response.
  12409. Server svr;
  12410. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12411. res.set_content("ok", "text/plain");
  12412. });
  12413. thread t = thread([&] { svr.listen(HOST, PORT); });
  12414. auto se = detail::scope_exit([&] {
  12415. svr.stop();
  12416. t.join();
  12417. ASSERT_FALSE(svr.is_running());
  12418. });
  12419. svr.wait_until_ready();
  12420. // Build a multipart part with 101 custom headers (exceeding
  12421. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12422. std::stringstream body;
  12423. body << "--simpleboundary\r\n"
  12424. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12425. for (int i = 0; i < 101; i++) {
  12426. body << "X-Custom-Header-" << i << ": value\r\n";
  12427. }
  12428. body << "\r\n"
  12429. << "value1\r\n"
  12430. << "--simpleboundary--\r\n";
  12431. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12432. Client cli(HOST, PORT);
  12433. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12435. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12436. }
  12437. TEST(MakeFileBodyTest, Basic) {
  12438. const std::string file_content(4096, 'Z');
  12439. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12440. {
  12441. std::ofstream ofs(tmp_path, std::ios::binary);
  12442. ofs.write(file_content.data(),
  12443. static_cast<std::streamsize>(file_content.size()));
  12444. }
  12445. auto handled = false;
  12446. Server svr;
  12447. svr.Post("/upload", [&](const Request &req, Response &res) {
  12448. EXPECT_EQ(file_content, req.body);
  12449. handled = true;
  12450. res.status = StatusCode::OK_200;
  12451. });
  12452. auto port = svr.bind_to_any_port(HOST);
  12453. auto t = thread([&] { svr.listen_after_bind(); });
  12454. auto se = detail::scope_exit([&] {
  12455. svr.stop();
  12456. t.join();
  12457. ASSERT_FALSE(svr.is_running());
  12458. ASSERT_TRUE(handled);
  12459. std::remove(tmp_path.c_str());
  12460. });
  12461. svr.wait_until_ready();
  12462. auto fb = make_file_body(tmp_path);
  12463. ASSERT_GT(fb.first, 0u);
  12464. Client cli(HOST, port);
  12465. auto res =
  12466. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12468. EXPECT_EQ(StatusCode::OK_200, res->status);
  12469. }
  12470. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12471. static constexpr unsigned int number_of_tasks{1000000};
  12472. std::atomic_uint count{0};
  12473. std::unique_ptr<TaskQueue> task_queue{
  12474. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12475. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12476. auto queued = task_queue->enqueue(
  12477. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12478. EXPECT_TRUE(queued);
  12479. }
  12480. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12481. task_queue->shutdown();
  12482. #else
  12483. EXPECT_NO_THROW(task_queue->shutdown());
  12484. #endif
  12485. EXPECT_EQ(number_of_tasks, count.load());
  12486. }
  12487. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12488. static constexpr unsigned int number_of_tasks{1000000};
  12489. static constexpr unsigned int qlimit{2};
  12490. unsigned int queued_count{0};
  12491. std::atomic_uint count{0};
  12492. std::unique_ptr<TaskQueue> task_queue{
  12493. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12494. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12495. if (task_queue->enqueue(
  12496. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12497. queued_count++;
  12498. }
  12499. }
  12500. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12501. task_queue->shutdown();
  12502. #else
  12503. EXPECT_NO_THROW(task_queue->shutdown());
  12504. #endif
  12505. EXPECT_EQ(queued_count, count.load());
  12506. EXPECT_TRUE(queued_count <= number_of_tasks);
  12507. EXPECT_TRUE(queued_count >= qlimit);
  12508. }
  12509. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12510. // Use a short idle timeout so a dynamic thread spawns, times out and
  12511. // exits during the test, and the pool keeps working afterwards.
  12512. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12513. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12514. /*idle_timeout_sec=*/1}};
  12515. std::atomic_uint count{0};
  12516. std::condition_variable cv;
  12517. std::mutex mtx;
  12518. bool release = false;
  12519. // Block the base thread so the second task spawns a dynamic thread.
  12520. EXPECT_TRUE(task_queue->enqueue([&] {
  12521. std::unique_lock<std::mutex> lock(mtx);
  12522. while (!release) {
  12523. cv.wait(lock);
  12524. }
  12525. count++;
  12526. }));
  12527. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12528. // Let the dynamic thread finish its task and exceed the idle timeout.
  12529. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12530. {
  12531. std::unique_lock<std::mutex> lock(mtx);
  12532. release = true;
  12533. }
  12534. cv.notify_all();
  12535. // The pool must still accept and run tasks after the dynamic thread exited.
  12536. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12537. task_queue->shutdown();
  12538. EXPECT_EQ(3u, count.load());
  12539. }
  12540. TEST(TaskQueueTest, MaxQueuedRequests) {
  12541. static constexpr unsigned int qlimit{3};
  12542. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12543. std::condition_variable sem_cv;
  12544. std::mutex sem_mtx;
  12545. int credits = 0;
  12546. bool queued;
  12547. /* Fill up the queue with tasks that will block until we give them credits to
  12548. * complete. */
  12549. for (unsigned int n = 0; n <= qlimit;) {
  12550. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12551. std::unique_lock<std::mutex> lock(sem_mtx);
  12552. while (credits <= 0) {
  12553. sem_cv.wait(lock);
  12554. }
  12555. /* Consume the credit and signal the test code if they are all gone. */
  12556. if (--credits == 0) { sem_cv.notify_one(); }
  12557. });
  12558. if (n < qlimit) {
  12559. /* The first qlimit enqueues must succeed. */
  12560. EXPECT_TRUE(queued);
  12561. } else {
  12562. /* The last one will succeed only when the worker thread
  12563. * starts and dequeues the first blocking task. Although
  12564. * not necessary for the correctness of this test, we sleep for
  12565. * a short while to avoid busy waiting. */
  12566. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12567. }
  12568. if (queued) { n++; }
  12569. }
  12570. /* Further enqueues must fail since the queue is full. */
  12571. for (auto i = 0; i < 4; i++) {
  12572. queued = task_queue->enqueue([] {});
  12573. EXPECT_FALSE(queued);
  12574. }
  12575. /* Give the credits to allow the previous tasks to complete. */
  12576. {
  12577. std::unique_lock<std::mutex> lock(sem_mtx);
  12578. credits += qlimit + 1;
  12579. }
  12580. sem_cv.notify_all();
  12581. /* Wait for all the credits to be consumed. */
  12582. {
  12583. std::unique_lock<std::mutex> lock(sem_mtx);
  12584. while (credits > 0) {
  12585. sem_cv.wait(lock);
  12586. }
  12587. }
  12588. /* Check that we are able again to enqueue at least qlimit tasks. */
  12589. for (unsigned int i = 0; i < qlimit; i++) {
  12590. queued = task_queue->enqueue([] {});
  12591. EXPECT_TRUE(queued);
  12592. }
  12593. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12594. task_queue->shutdown();
  12595. #else
  12596. EXPECT_NO_THROW(task_queue->shutdown());
  12597. #endif
  12598. }
  12599. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12600. Server svr;
  12601. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12602. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12603. });
  12604. svr.Get("/hello", [](const Request &req, Response &res) {
  12605. res.set_content(req.get_param_value("key"), "text/plain");
  12606. });
  12607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12608. auto se = detail::scope_exit([&] {
  12609. svr.stop();
  12610. thread.join();
  12611. ASSERT_FALSE(svr.is_running());
  12612. });
  12613. svr.wait_until_ready();
  12614. {
  12615. Client cli(HOST, PORT);
  12616. cli.set_follow_location(true);
  12617. auto res = cli.Get("/");
  12618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12619. EXPECT_EQ(StatusCode::OK_200, res->status);
  12620. EXPECT_EQ("val&key2=val2", res->body);
  12621. }
  12622. }
  12623. #endif
  12624. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12625. Server svr;
  12626. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12627. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12628. });
  12629. svr.Get("/hello", [](const Request &req, Response &res) {
  12630. res.set_content(req.get_param_value("key"), "text/plain");
  12631. });
  12632. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12633. auto se = detail::scope_exit([&] {
  12634. svr.stop();
  12635. thread.join();
  12636. ASSERT_FALSE(svr.is_running());
  12637. });
  12638. svr.wait_until_ready();
  12639. {
  12640. Client cli(HOST, PORT);
  12641. cli.set_follow_location(true);
  12642. auto res = cli.Get("/");
  12643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12644. EXPECT_EQ(StatusCode::OK_200, res->status);
  12645. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12646. }
  12647. }
  12648. TEST(RedirectTest, RedirectWithPlusInPath) {
  12649. Server svr;
  12650. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12651. res.set_redirect("/a+b");
  12652. });
  12653. // Route pattern uses regex; escape + as \\+
  12654. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12655. res.set_content(req.path, "text/plain");
  12656. });
  12657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12658. auto se = detail::scope_exit([&] {
  12659. svr.stop();
  12660. thread.join();
  12661. ASSERT_FALSE(svr.is_running());
  12662. });
  12663. svr.wait_until_ready();
  12664. {
  12665. Client cli(HOST, PORT);
  12666. cli.set_follow_location(true);
  12667. auto res = cli.Get("/");
  12668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12669. EXPECT_EQ(StatusCode::OK_200, res->status);
  12670. EXPECT_EQ("/a+b", res->body);
  12671. }
  12672. }
  12673. #ifdef CPPHTTPLIB_SSL_ENABLED
  12674. TEST(RedirectTest, Issue2185_Online) {
  12675. SSLClient client("github.com");
  12676. client.set_follow_location(true);
  12677. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12678. "Coollab-Windows.zip");
  12679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12680. EXPECT_EQ(StatusCode::OK_200, res->status);
  12681. EXPECT_EQ(9920427U, res->body.size());
  12682. }
  12683. #endif
  12684. TEST(VulnerabilityTest, CRLFInjection) {
  12685. Server svr;
  12686. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12687. res.set_content("Hello 1", "text/plain");
  12688. });
  12689. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12690. res.set_content("Hello 2", "text/plain");
  12691. });
  12692. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12693. res.set_content("Hello 3", "text/plain");
  12694. });
  12695. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12696. res.set_content("Hello 4", "text/plain");
  12697. });
  12698. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12699. for (const auto &x : req.headers) {
  12700. auto key = x.first;
  12701. EXPECT_STRNE("evil", key.c_str());
  12702. }
  12703. });
  12704. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12705. auto se = detail::scope_exit([&] {
  12706. svr.stop();
  12707. thread.join();
  12708. ASSERT_FALSE(svr.is_running());
  12709. });
  12710. svr.wait_until_ready();
  12711. {
  12712. Client cli(HOST, PORT);
  12713. cli.Post("/test1", "A=B",
  12714. "application/x-www-form-urlencoded\r\nevil: hello1");
  12715. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12716. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12717. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12718. }
  12719. }
  12720. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12721. auto server_thread = std::thread([] {
  12722. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12723. default_socket_options(srv);
  12724. sockaddr_in addr{};
  12725. addr.sin_family = AF_INET;
  12726. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12727. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12728. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12729. ::listen(srv, 1);
  12730. sockaddr_in cli_addr{};
  12731. socklen_t cli_len = sizeof(cli_addr);
  12732. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12733. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12734. std::string buf_all;
  12735. char buf[2048];
  12736. ssize_t n;
  12737. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12738. buf_all.append(buf, static_cast<size_t>(n));
  12739. size_t pos;
  12740. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12741. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12742. auto e = request_block.find("\r\n");
  12743. if (e != std::string::npos) {
  12744. auto request_line = request_block.substr(0, e);
  12745. std::string msg =
  12746. "CRLF injection detected in request line: '" + request_line + "'";
  12747. EXPECT_FALSE(true) << msg;
  12748. }
  12749. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12750. ::send(cli,
  12751. #ifdef _WIN32
  12752. static_cast<const char *>(resp.c_str()),
  12753. static_cast<int>(resp.size()),
  12754. #else
  12755. resp.c_str(), resp.size(),
  12756. #endif
  12757. 0);
  12758. buf_all.erase(0, pos + 4);
  12759. }
  12760. }
  12761. detail::close_socket(cli);
  12762. detail::close_socket(srv);
  12763. });
  12764. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12765. auto cli = Client("127.0.0.1", PORT + 1);
  12766. auto headers = Headers{
  12767. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12768. {"Connection", "keep-alive"}};
  12769. auto res = cli.Get("/hi", headers);
  12770. EXPECT_FALSE(res);
  12771. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12772. server_thread.join();
  12773. }
  12774. TEST(PathParamsTest, StaticMatch) {
  12775. const auto pattern = "/users/all";
  12776. detail::PathParamsMatcher matcher(pattern);
  12777. Request request;
  12778. request.path = "/users/all";
  12779. ASSERT_TRUE(matcher.match(request));
  12780. std::unordered_map<std::string, std::string> expected_params = {};
  12781. EXPECT_EQ(request.path_params, expected_params);
  12782. }
  12783. TEST(PathParamsTest, StaticMismatch) {
  12784. const auto pattern = "/users/all";
  12785. detail::PathParamsMatcher matcher(pattern);
  12786. Request request;
  12787. request.path = "/users/1";
  12788. ASSERT_FALSE(matcher.match(request));
  12789. }
  12790. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12791. const auto pattern = "/users/:id/subscriptions";
  12792. detail::PathParamsMatcher matcher(pattern);
  12793. Request request;
  12794. request.path = "/users/42/subscriptions";
  12795. ASSERT_TRUE(matcher.match(request));
  12796. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12797. EXPECT_EQ(request.path_params, expected_params);
  12798. }
  12799. TEST(PathParamsTest, SingleParamInTheEnd) {
  12800. const auto pattern = "/users/:id";
  12801. detail::PathParamsMatcher matcher(pattern);
  12802. Request request;
  12803. request.path = "/users/24";
  12804. ASSERT_TRUE(matcher.match(request));
  12805. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12806. EXPECT_EQ(request.path_params, expected_params);
  12807. }
  12808. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12809. const auto pattern = "/users/:id/";
  12810. detail::PathParamsMatcher matcher(pattern);
  12811. Request request;
  12812. request.path = "/users/42/";
  12813. ASSERT_TRUE(matcher.match(request));
  12814. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12815. EXPECT_EQ(request.path_params, expected_params);
  12816. }
  12817. TEST(PathParamsTest, EmptyParam) {
  12818. const auto pattern = "/users/:id/";
  12819. detail::PathParamsMatcher matcher(pattern);
  12820. Request request;
  12821. request.path = "/users//";
  12822. ASSERT_TRUE(matcher.match(request));
  12823. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12824. EXPECT_EQ(request.path_params, expected_params);
  12825. }
  12826. TEST(PathParamsTest, FragmentMismatch) {
  12827. const auto pattern = "/users/:id/";
  12828. detail::PathParamsMatcher matcher(pattern);
  12829. Request request;
  12830. request.path = "/admins/24/";
  12831. ASSERT_FALSE(matcher.match(request));
  12832. }
  12833. TEST(PathParamsTest, ExtraFragments) {
  12834. const auto pattern = "/users/:id";
  12835. detail::PathParamsMatcher matcher(pattern);
  12836. Request request;
  12837. request.path = "/users/42/subscriptions";
  12838. ASSERT_FALSE(matcher.match(request));
  12839. }
  12840. TEST(PathParamsTest, MissingTrailingParam) {
  12841. const auto pattern = "/users/:id";
  12842. detail::PathParamsMatcher matcher(pattern);
  12843. Request request;
  12844. request.path = "/users";
  12845. ASSERT_FALSE(matcher.match(request));
  12846. }
  12847. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12848. const auto pattern = "/users/:id/subscriptions";
  12849. detail::PathParamsMatcher matcher(pattern);
  12850. Request request;
  12851. request.path = "/users/subscriptions";
  12852. ASSERT_FALSE(matcher.match(request));
  12853. }
  12854. TEST(PathParamsTest, MultipleParams) {
  12855. const auto pattern = "/users/:userid/subscriptions/:subid";
  12856. detail::PathParamsMatcher matcher(pattern);
  12857. Request request;
  12858. request.path = "/users/42/subscriptions/2";
  12859. ASSERT_TRUE(matcher.match(request));
  12860. std::unordered_map<std::string, std::string> expected_params = {
  12861. {"userid", "42"}, {"subid", "2"}};
  12862. EXPECT_EQ(request.path_params, expected_params);
  12863. }
  12864. TEST(PathParamsTest, SequenceOfParams) {
  12865. const auto pattern = "/values/:x/:y/:z";
  12866. detail::PathParamsMatcher matcher(pattern);
  12867. Request request;
  12868. request.path = "/values/1/2/3";
  12869. ASSERT_TRUE(matcher.match(request));
  12870. std::unordered_map<std::string, std::string> expected_params = {
  12871. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12872. EXPECT_EQ(request.path_params, expected_params);
  12873. }
  12874. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12875. const auto pattern = "/prefix:suffix";
  12876. detail::PathParamsMatcher matcher(pattern);
  12877. Request request;
  12878. request.path = "/prefix:suffix";
  12879. ASSERT_TRUE(matcher.match(request));
  12880. const std::unordered_map<std::string, std::string> expected_params = {};
  12881. EXPECT_EQ(request.path_params, expected_params);
  12882. }
  12883. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  12884. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  12885. // calling thread's stack on a long enough path for a quantified pattern;
  12886. // RegexMatcher must refuse to run regex matching on paths beyond
  12887. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  12888. detail::RegexMatcher matcher("/files/(.*)");
  12889. Request within_limit;
  12890. within_limit.path = "/files/" + std::string(10, 'A');
  12891. EXPECT_TRUE(matcher.match(within_limit));
  12892. Request over_limit;
  12893. over_limit.path =
  12894. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  12895. EXPECT_FALSE(matcher.match(over_limit));
  12896. }
  12897. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  12898. Server svr;
  12899. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  12900. res.set_content("ok", "text/plain");
  12901. });
  12902. auto port = svr.bind_to_any_port(HOST);
  12903. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12904. auto se = detail::scope_exit([&] {
  12905. svr.stop();
  12906. thread.join();
  12907. ASSERT_FALSE(svr.is_running());
  12908. });
  12909. svr.wait_until_ready();
  12910. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  12911. // request URI limit; this used to be able to crash the process.
  12912. std::string path =
  12913. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  12914. std::string req = "GET " + path +
  12915. " HTTP/1.1\r\n"
  12916. "Host: " +
  12917. std::string(HOST) + ":" + std::to_string(port) +
  12918. "\r\n"
  12919. "Connection: close\r\n"
  12920. "\r\n";
  12921. std::string response;
  12922. ASSERT_TRUE(send_request(5, req, &response, port));
  12923. EXPECT_NE(std::string::npos, response.find("404"));
  12924. }
  12925. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  12926. Server svr;
  12927. auto handler = [](const Request & /*req*/, Response &res) {
  12928. res.set_content("hit", "text/plain");
  12929. };
  12930. // No regex metacharacter, so this one is compared literally
  12931. svr.Get("/literal/route", handler);
  12932. // '.' is a regex metacharacter, so this one must keep regex semantics
  12933. svr.Get("/a.c", handler);
  12934. auto port = svr.bind_to_any_port(HOST);
  12935. std::thread t([&]() { svr.listen_after_bind(); });
  12936. auto se = detail::scope_exit([&] {
  12937. svr.stop();
  12938. t.join();
  12939. ASSERT_FALSE(svr.is_running());
  12940. });
  12941. svr.wait_until_ready();
  12942. Client cli(HOST, port);
  12943. struct {
  12944. const char *path;
  12945. int status;
  12946. } cases[] = {
  12947. {"/literal/route", StatusCode::OK_200},
  12948. {"/literal/routes", StatusCode::NotFound_404},
  12949. {"/literal/rout", StatusCode::NotFound_404},
  12950. {"/abc", StatusCode::OK_200},
  12951. {"/a.c", StatusCode::OK_200},
  12952. };
  12953. for (const auto &x : cases) {
  12954. auto res = cli.Get(x.path);
  12955. ASSERT_TRUE(res) << x.path;
  12956. EXPECT_EQ(x.status, res->status) << x.path;
  12957. }
  12958. }
  12959. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  12960. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  12961. // from exhausting the stack, so it must only constrain routes that actually
  12962. // run a regular expression. A literal route is matched by comparison and
  12963. // stays usable at any length.
  12964. Server svr;
  12965. const std::string pattern =
  12966. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  12967. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  12968. res.set_content("hit", "text/plain");
  12969. });
  12970. auto port = svr.bind_to_any_port(HOST);
  12971. std::thread t([&]() { svr.listen_after_bind(); });
  12972. auto se = detail::scope_exit([&] {
  12973. svr.stop();
  12974. t.join();
  12975. ASSERT_FALSE(svr.is_running());
  12976. });
  12977. svr.wait_until_ready();
  12978. Client cli(HOST, port);
  12979. auto res = cli.Get(pattern);
  12980. ASSERT_TRUE(res);
  12981. EXPECT_EQ(StatusCode::OK_200, res->status);
  12982. }
  12983. TEST(ParseUrlTest, VariousPatterns) {
  12984. {
  12985. detail::UrlComponents uc;
  12986. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12987. EXPECT_EQ("http", uc.scheme);
  12988. EXPECT_EQ("example.com", uc.host);
  12989. EXPECT_EQ("8080", uc.port);
  12990. EXPECT_EQ("/path", uc.path);
  12991. EXPECT_EQ("?q=1", uc.query);
  12992. }
  12993. {
  12994. detail::UrlComponents uc;
  12995. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12996. EXPECT_EQ("https", uc.scheme);
  12997. EXPECT_EQ("example.com", uc.host);
  12998. EXPECT_TRUE(uc.port.empty());
  12999. EXPECT_EQ("/path", uc.path);
  13000. }
  13001. {
  13002. detail::UrlComponents uc;
  13003. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  13004. EXPECT_EQ("::1", uc.host);
  13005. EXPECT_EQ("8080", uc.port);
  13006. EXPECT_EQ("/path", uc.path);
  13007. }
  13008. {
  13009. detail::UrlComponents uc;
  13010. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  13011. }
  13012. {
  13013. // Bytes after the IPv6 literal must be a delimiter, not folded into
  13014. // the path while the connection still targets the bracketed host.
  13015. detail::UrlComponents uc;
  13016. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  13017. }
  13018. {
  13019. detail::UrlComponents uc;
  13020. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  13021. }
  13022. {
  13023. detail::UrlComponents uc;
  13024. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  13025. EXPECT_EQ("::1", uc.host);
  13026. EXPECT_TRUE(uc.port.empty());
  13027. EXPECT_EQ("/path", uc.path);
  13028. }
  13029. {
  13030. detail::UrlComponents uc;
  13031. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  13032. EXPECT_TRUE(uc.scheme.empty());
  13033. EXPECT_EQ("example.com", uc.host);
  13034. EXPECT_EQ("/path", uc.path);
  13035. EXPECT_EQ("?q=1", uc.query);
  13036. }
  13037. {
  13038. detail::UrlComponents uc;
  13039. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  13040. EXPECT_TRUE(uc.host.empty());
  13041. EXPECT_EQ("/path", uc.path);
  13042. EXPECT_EQ("?q=1", uc.query);
  13043. }
  13044. {
  13045. detail::UrlComponents uc;
  13046. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  13047. EXPECT_EQ("example.com", uc.host);
  13048. EXPECT_EQ("8080", uc.port);
  13049. }
  13050. {
  13051. // Unix socket path — must not be parsed as host
  13052. detail::UrlComponents uc;
  13053. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  13054. EXPECT_TRUE(uc.host.empty());
  13055. }
  13056. {
  13057. detail::UrlComponents uc;
  13058. ASSERT_TRUE(detail::parse_url("", uc));
  13059. EXPECT_TRUE(uc.host.empty());
  13060. EXPECT_TRUE(uc.path.empty());
  13061. }
  13062. {
  13063. detail::UrlComponents uc;
  13064. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  13065. }
  13066. {
  13067. detail::UrlComponents uc;
  13068. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  13069. }
  13070. {
  13071. // Accepted by parse_url; callers restrict to http/https
  13072. detail::UrlComponents uc;
  13073. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  13074. EXPECT_EQ("ftp", uc.scheme);
  13075. }
  13076. {
  13077. detail::UrlComponents uc;
  13078. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  13079. }
  13080. {
  13081. detail::UrlComponents uc;
  13082. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  13083. }
  13084. }
  13085. TEST(ParseUrlTest, FragmentHandling) {
  13086. {
  13087. detail::UrlComponents uc;
  13088. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  13089. EXPECT_EQ("/path", uc.path);
  13090. EXPECT_TRUE(uc.query.empty());
  13091. }
  13092. {
  13093. detail::UrlComponents uc;
  13094. ASSERT_TRUE(detail::parse_url("#frag", uc));
  13095. EXPECT_TRUE(uc.path.empty());
  13096. EXPECT_TRUE(uc.query.empty());
  13097. }
  13098. }
  13099. TEST(ParseUrlTest, UserinfoHandling) {
  13100. // Userinfo with @ but no colon — host includes @
  13101. detail::UrlComponents uc;
  13102. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  13103. EXPECT_EQ("user@host.com", uc.host);
  13104. EXPECT_EQ("/path", uc.path);
  13105. }
  13106. TEST(ParseUrlTest, IPv6EdgeCases) {
  13107. {
  13108. detail::UrlComponents uc;
  13109. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  13110. EXPECT_TRUE(uc.scheme.empty());
  13111. EXPECT_EQ("::1", uc.host);
  13112. EXPECT_EQ("8080", uc.port);
  13113. }
  13114. {
  13115. // Zone ID '%25' is not in [a-fA-F0-9:]
  13116. detail::UrlComponents uc;
  13117. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  13118. }
  13119. }
  13120. TEST(ParseUrlTest, SchemeEdgeCases) {
  13121. {
  13122. detail::UrlComponents uc;
  13123. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  13124. }
  13125. {
  13126. detail::UrlComponents uc;
  13127. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  13128. }
  13129. {
  13130. detail::UrlComponents uc;
  13131. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  13132. }
  13133. }
  13134. TEST(ParseUrlTest, PortEdgeCases) {
  13135. {
  13136. detail::UrlComponents uc;
  13137. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  13138. EXPECT_TRUE(uc.port.empty());
  13139. EXPECT_EQ("/path", uc.path);
  13140. }
  13141. {
  13142. // parse_url accepts any port string; validation is done by parse_port
  13143. detail::UrlComponents uc;
  13144. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  13145. EXPECT_EQ("abc", uc.port);
  13146. }
  13147. }
  13148. TEST(ParseUrlTest, WebSocketPatterns) {
  13149. {
  13150. detail::UrlComponents uc;
  13151. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  13152. EXPECT_EQ("ws", uc.scheme);
  13153. EXPECT_EQ("echo.example.com", uc.host);
  13154. EXPECT_EQ("8080", uc.port);
  13155. EXPECT_EQ("/ws", uc.path);
  13156. }
  13157. {
  13158. detail::UrlComponents uc;
  13159. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  13160. EXPECT_EQ("wss", uc.scheme);
  13161. EXPECT_EQ("echo.example.com", uc.host);
  13162. EXPECT_TRUE(uc.port.empty());
  13163. EXPECT_EQ("/ws", uc.path);
  13164. }
  13165. }
  13166. TEST(ParseUrlTest, QueryOnly) {
  13167. detail::UrlComponents uc;
  13168. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  13169. EXPECT_TRUE(uc.host.empty());
  13170. EXPECT_TRUE(uc.path.empty());
  13171. EXPECT_EQ("?q=1&r=2", uc.query);
  13172. }
  13173. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13174. detail::UrlComponents uc;
  13175. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13176. EXPECT_TRUE(uc.scheme.empty());
  13177. EXPECT_EQ("example.com", uc.host);
  13178. EXPECT_EQ("443", uc.port);
  13179. EXPECT_EQ("/path", uc.path);
  13180. }
  13181. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13182. // If ipv6 regex working, regex match codepath is taken.
  13183. // else port will default to 80 in Client impl
  13184. int clientImplMagicPort = 80;
  13185. int port = 4321;
  13186. // above ports must be different to avoid false negative
  13187. EXPECT_NE(clientImplMagicPort, port);
  13188. std::string ipV6TestURL = "http://[ff06::c3]";
  13189. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13190. CLIENT_PRIVATE_KEY_FILE);
  13191. EXPECT_EQ(cli.port(), port);
  13192. }
  13193. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13194. auto file_path = "./www/dir/index.html";
  13195. auto dir_path = "./www/dir";
  13196. detail::FileStat stat_file(file_path);
  13197. EXPECT_TRUE(stat_file.is_file());
  13198. EXPECT_FALSE(stat_file.is_dir());
  13199. detail::FileStat stat_dir(dir_path);
  13200. EXPECT_FALSE(stat_dir.is_file());
  13201. EXPECT_TRUE(stat_dir.is_dir());
  13202. }
  13203. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13204. // IPv4 with default HTTP port (80)
  13205. EXPECT_EQ("example.com",
  13206. detail::make_host_and_port_string("example.com", 80, false));
  13207. // IPv4 with default HTTPS port (443)
  13208. EXPECT_EQ("example.com",
  13209. detail::make_host_and_port_string("example.com", 443, true));
  13210. // IPv4 with non-default HTTP port
  13211. EXPECT_EQ("example.com:8080",
  13212. detail::make_host_and_port_string("example.com", 8080, false));
  13213. // IPv4 with non-default HTTPS port
  13214. EXPECT_EQ("example.com:8443",
  13215. detail::make_host_and_port_string("example.com", 8443, true));
  13216. // IPv6 with default HTTP port (80)
  13217. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13218. // IPv6 with default HTTPS port (443)
  13219. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13220. // IPv6 with non-default HTTP port
  13221. EXPECT_EQ("[::1]:8080",
  13222. detail::make_host_and_port_string("::1", 8080, false));
  13223. // IPv6 with non-default HTTPS port
  13224. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13225. // IPv6 full address with default port
  13226. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13227. detail::make_host_and_port_string(
  13228. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13229. // IPv6 full address with non-default port
  13230. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13231. detail::make_host_and_port_string(
  13232. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13233. // IPv6 localhost with non-default port
  13234. EXPECT_EQ("[::1]:3000",
  13235. detail::make_host_and_port_string("::1", 3000, false));
  13236. // IPv6 with zone ID (link-local address) with default port
  13237. EXPECT_EQ("[fe80::1%eth0]",
  13238. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13239. // IPv6 with zone ID (link-local address) with non-default port
  13240. EXPECT_EQ("[fe80::1%eth0]:8080",
  13241. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13242. // Edge case: Port 443 with is_ssl=false (should add port)
  13243. EXPECT_EQ("example.com:443",
  13244. detail::make_host_and_port_string("example.com", 443, false));
  13245. // Edge case: Port 80 with is_ssl=true (should add port)
  13246. EXPECT_EQ("example.com:80",
  13247. detail::make_host_and_port_string("example.com", 80, true));
  13248. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13249. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13250. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13251. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13252. // Security fix: Already bracketed IPv6 should not get double brackets
  13253. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13254. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13255. EXPECT_EQ("[::1]:8080",
  13256. detail::make_host_and_port_string("[::1]", 8080, false));
  13257. EXPECT_EQ("[2001:db8::1]:8080",
  13258. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13259. EXPECT_EQ("[fe80::1%eth0]",
  13260. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13261. EXPECT_EQ("[fe80::1%eth0]:8080",
  13262. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13263. // Edge case: Empty host (should return as-is)
  13264. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13265. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13266. // This is a known limitation but shouldn't crash
  13267. EXPECT_EQ("[host:name]",
  13268. detail::make_host_and_port_string("host:name", 80, false));
  13269. // Port number edge cases (no validation, but should not crash)
  13270. EXPECT_EQ("example.com:0",
  13271. detail::make_host_and_port_string("example.com", 0, false));
  13272. EXPECT_EQ("example.com:-1",
  13273. detail::make_host_and_port_string("example.com", -1, false));
  13274. EXPECT_EQ("example.com:65535",
  13275. detail::make_host_and_port_string("example.com", 65535, false));
  13276. EXPECT_EQ("example.com:65536",
  13277. detail::make_host_and_port_string("example.com", 65536, false));
  13278. }
  13279. #ifdef CPPHTTPLIB_SSL_ENABLED
  13280. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13281. httplib::SSLClient cli("roblox.com", 443);
  13282. cli.set_follow_location(true);
  13283. auto res = cli.Get("/");
  13284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13285. EXPECT_EQ(StatusCode::OK_200, res->status);
  13286. }
  13287. #endif
  13288. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13289. Server svr;
  13290. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13291. EXPECT_EQ(res.status, 400);
  13292. });
  13293. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13294. auto se = detail::scope_exit([&] {
  13295. svr.stop();
  13296. thread.join();
  13297. ASSERT_FALSE(svr.is_running());
  13298. });
  13299. svr.wait_until_ready();
  13300. Client cli(HOST, PORT);
  13301. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13302. }
  13303. TEST(InvalidHeaderCharsTest, is_field_name) {
  13304. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13305. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13306. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13307. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13308. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13309. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13310. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13311. EXPECT_FALSE(detail::fields::is_field_name(""));
  13312. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13313. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13314. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13315. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13316. }
  13317. TEST(InvalidHeaderCharsTest, is_field_value) {
  13318. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13319. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13320. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13321. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13322. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13323. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13324. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13325. EXPECT_TRUE(detail::fields::is_field_value(""));
  13326. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13327. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13328. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13329. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13330. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13331. }
  13332. TEST(InvalidHeaderCharsTest, OnServer) {
  13333. Server svr;
  13334. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13335. std::string header = "Not Set";
  13336. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13337. res.set_header(header, "value");
  13338. res.set_content("Page Content Page Content", "text/plain");
  13339. });
  13340. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13341. std::string header = "Not Set";
  13342. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13343. res.set_header("X-Test", header);
  13344. res.set_content("Page Content Page Content", "text/plain");
  13345. });
  13346. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13347. auto se = detail::scope_exit([&] {
  13348. svr.stop();
  13349. thread.join();
  13350. ASSERT_FALSE(svr.is_running());
  13351. });
  13352. svr.wait_until_ready();
  13353. Client cli(HOST, PORT);
  13354. {
  13355. auto res = cli.Get(
  13356. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13358. EXPECT_EQ("Page Content Page Content", res->body);
  13359. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13360. }
  13361. {
  13362. auto res = cli.Get(
  13363. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13365. EXPECT_EQ("Page Content Page Content", res->body);
  13366. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13367. }
  13368. }
  13369. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13370. auto handled = false;
  13371. Server svr;
  13372. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13373. thread t = thread([&] { svr.listen(HOST, PORT); });
  13374. auto se = detail::scope_exit([&] {
  13375. svr.stop();
  13376. t.join();
  13377. ASSERT_FALSE(svr.is_running());
  13378. ASSERT_FALSE(handled);
  13379. });
  13380. svr.wait_until_ready();
  13381. auto req = "POST /test HTTP/1.1\r\n"
  13382. "Content-Length: x\r\n"
  13383. "\r\n";
  13384. std::string response;
  13385. ASSERT_TRUE(send_request(1, req, &response));
  13386. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13387. response.substr(0, response.find("\r\n")));
  13388. }
  13389. #ifndef _WIN32
  13390. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13391. static constexpr char reject[] = "Unauthorized";
  13392. static constexpr char accept[] = "Upload accepted";
  13393. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13394. Server svr;
  13395. svr.set_expect_100_continue_handler(
  13396. [](const Request & /*req*/, Response &res) {
  13397. res.status = StatusCode::Unauthorized_401;
  13398. res.set_content(reject, "text/plain");
  13399. return res.status;
  13400. });
  13401. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13402. res.set_content(accept, "text/plain");
  13403. });
  13404. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13405. auto se = detail::scope_exit([&] {
  13406. svr.stop();
  13407. thread.join();
  13408. ASSERT_FALSE(svr.is_running());
  13409. });
  13410. svr.wait_until_ready();
  13411. {
  13412. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13413. curl_easy_init(), &curl_easy_cleanup};
  13414. ASSERT_NE(curl, nullptr);
  13415. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13416. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13417. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13418. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13419. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13420. &curl_slist_free_all};
  13421. ASSERT_NE(list, nullptr);
  13422. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13423. struct read_data {
  13424. size_t read_size;
  13425. size_t total_size;
  13426. } data = {0, total_size};
  13427. using read_callback_t =
  13428. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13429. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13430. void *userdata) -> size_t {
  13431. read_data *d = (read_data *)userdata;
  13432. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13433. std::fill_n(ptr, size * nmemb, 'A');
  13434. d->read_size += size * nmemb;
  13435. return size * nmemb;
  13436. };
  13437. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13438. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13439. std::vector<char> buffer;
  13440. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13441. using write_callback_t =
  13442. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13443. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13444. void *userdata) -> size_t {
  13445. std::vector<char> *buf = (std::vector<char> *)userdata;
  13446. buf->reserve(buf->size() + size * nmemb + 1);
  13447. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13448. return size * nmemb;
  13449. };
  13450. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13451. {
  13452. const auto res = curl_easy_perform(curl.get());
  13453. ASSERT_EQ(res, CURLE_OK);
  13454. }
  13455. {
  13456. auto response_code = long{};
  13457. const auto res =
  13458. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13459. ASSERT_EQ(res, CURLE_OK);
  13460. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13461. }
  13462. {
  13463. auto dl = curl_off_t{};
  13464. const auto res =
  13465. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13466. ASSERT_EQ(res, CURLE_OK);
  13467. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13468. }
  13469. {
  13470. buffer.push_back('\0');
  13471. ASSERT_STRCASEEQ(buffer.data(), reject);
  13472. }
  13473. }
  13474. }
  13475. #endif
  13476. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13477. // Regression test for #2458.
  13478. //
  13479. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13480. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13481. // ticket can make the client socket spuriously readable during the
  13482. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13483. // the client withholds the body and then blocks reading a response that never
  13484. // comes, failing with `Failed to read connection`.
  13485. //
  13486. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13487. // within the timeout. This raw OpenSSL server deliberately never sends
  13488. // `100 Continue`; the client must still deliver the body and receive 200.
  13489. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13490. signal(SIGPIPE, SIG_IGN);
  13491. const auto port = PORT + 4;
  13492. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13493. ASSERT_NE(srv, INVALID_SOCKET);
  13494. int opt = 1;
  13495. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13496. sockaddr_in addr{};
  13497. addr.sin_family = AF_INET;
  13498. addr.sin_port = htons(static_cast<uint16_t>(port));
  13499. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13500. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13501. ASSERT_EQ(0, ::listen(srv, 1));
  13502. std::atomic<size_t> server_body_bytes{0};
  13503. auto server_thread = std::thread([&] {
  13504. sockaddr_in cli_addr{};
  13505. socklen_t cli_len = sizeof(cli_addr);
  13506. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13507. if (cli == INVALID_SOCKET) { return; }
  13508. // Bound the lifetime of the server side so a buggy client (which never
  13509. // sends the body) cannot make this thread block forever on join.
  13510. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13511. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13512. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13513. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13514. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13515. SSL *ssl = SSL_new(ctx);
  13516. SSL_set_fd(ssl, static_cast<int>(cli));
  13517. if (SSL_accept(ssl) > 0) {
  13518. // Read the request headers. Reading here also flushes the TLS 1.3
  13519. // session tickets to the client. Deliberately do NOT send
  13520. // `100 Continue`.
  13521. std::string buf;
  13522. char tmp[1024];
  13523. while (buf.find("\r\n\r\n") == std::string::npos) {
  13524. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13525. if (n <= 0) { break; }
  13526. buf.append(tmp, static_cast<size_t>(n));
  13527. }
  13528. // A correct client sends the body now; count what arrives.
  13529. auto pos = buf.find("\r\n\r\n");
  13530. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13531. while (body < 4096) {
  13532. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13533. if (n <= 0) { break; }
  13534. body += static_cast<size_t>(n);
  13535. }
  13536. server_body_bytes = body;
  13537. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13538. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13539. SSL_shutdown(ssl);
  13540. }
  13541. SSL_free(ssl);
  13542. detail::close_socket(cli);
  13543. SSL_CTX_free(ctx);
  13544. });
  13545. auto se = detail::scope_exit([&] {
  13546. server_thread.join();
  13547. detail::close_socket(srv);
  13548. });
  13549. SSLClient cli("127.0.0.1", port);
  13550. cli.enable_server_certificate_verification(false);
  13551. cli.set_connection_timeout(5, 0);
  13552. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13553. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13554. std::string body(4096, 'A');
  13555. auto res = cli.Put("/api/test", body, "application/json");
  13556. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13557. EXPECT_EQ(StatusCode::OK_200, res->status);
  13558. EXPECT_EQ(body.size(), server_body_bytes.load());
  13559. }
  13560. #endif
  13561. template <typename S, typename C>
  13562. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13563. svr.Get("/stream", [&](const Request &, Response &res) {
  13564. auto data = new std::string("01234567890123456789");
  13565. res.set_content_provider(
  13566. data->size(), "text/plain",
  13567. [&, data](size_t offset, size_t length, DataSink &sink) {
  13568. const size_t DATA_CHUNK_SIZE = 4;
  13569. const auto &d = *data;
  13570. std::this_thread::sleep_for(std::chrono::seconds(1));
  13571. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13572. return true;
  13573. },
  13574. [data](bool success) {
  13575. EXPECT_FALSE(success);
  13576. delete data;
  13577. });
  13578. });
  13579. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13580. auto i = new size_t(0);
  13581. res.set_content_provider(
  13582. "text/plain",
  13583. [i](size_t, DataSink &sink) {
  13584. if (*i < 5) {
  13585. std::this_thread::sleep_for(std::chrono::seconds(1));
  13586. sink.write("abcd", 4);
  13587. (*i)++;
  13588. } else {
  13589. sink.done();
  13590. }
  13591. return true;
  13592. },
  13593. [i](bool success) {
  13594. EXPECT_FALSE(success);
  13595. delete i;
  13596. });
  13597. });
  13598. svr.Get("/chunked", [&](const Request &, Response &res) {
  13599. auto i = new size_t(0);
  13600. res.set_chunked_content_provider(
  13601. "text/plain",
  13602. [i](size_t, DataSink &sink) {
  13603. if (*i < 5) {
  13604. std::this_thread::sleep_for(std::chrono::seconds(1));
  13605. sink.os << "abcd";
  13606. (*i)++;
  13607. } else {
  13608. sink.done();
  13609. }
  13610. return true;
  13611. },
  13612. [i](bool success) {
  13613. EXPECT_FALSE(success);
  13614. delete i;
  13615. });
  13616. });
  13617. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13618. auto se = detail::scope_exit([&] {
  13619. svr.stop();
  13620. listen_thread.join();
  13621. ASSERT_FALSE(svr.is_running());
  13622. });
  13623. svr.wait_until_ready();
  13624. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13625. {
  13626. auto start = std::chrono::steady_clock::now();
  13627. auto res = cli.Get("/stream");
  13628. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13629. std::chrono::steady_clock::now() - start)
  13630. .count();
  13631. ASSERT_FALSE(res);
  13632. EXPECT_EQ(Error::Read, res.error());
  13633. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13634. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13635. }
  13636. {
  13637. auto start = std::chrono::steady_clock::now();
  13638. auto res = cli.Get("/stream_without_length");
  13639. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13640. std::chrono::steady_clock::now() - start)
  13641. .count();
  13642. ASSERT_FALSE(res);
  13643. EXPECT_EQ(Error::Read, res.error());
  13644. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13645. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13646. }
  13647. {
  13648. auto start = std::chrono::steady_clock::now();
  13649. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13650. EXPECT_EQ("abcd", string(data, data_length));
  13651. return true;
  13652. });
  13653. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13654. std::chrono::steady_clock::now() - start)
  13655. .count();
  13656. ASSERT_FALSE(res);
  13657. EXPECT_EQ(Error::Read, res.error());
  13658. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13659. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13660. }
  13661. }
  13662. TEST(MaxTimeoutTest, ContentStream) {
  13663. time_t timeout = 2000;
  13664. time_t threshold = 200;
  13665. Server svr;
  13666. Client cli("localhost", PORT);
  13667. max_timeout_test(svr, cli, timeout, threshold);
  13668. }
  13669. #ifdef CPPHTTPLIB_SSL_ENABLED
  13670. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13671. time_t timeout = 2000;
  13672. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13674. SSLClient cli("localhost", PORT);
  13675. cli.enable_server_certificate_verification(false);
  13676. max_timeout_test(svr, cli, timeout, threshold);
  13677. }
  13678. #endif
  13679. class EventDispatcher {
  13680. public:
  13681. EventDispatcher() {}
  13682. bool wait_event(DataSink *sink) {
  13683. unique_lock<mutex> lk(m_);
  13684. int id = id_;
  13685. // Wait with timeout to prevent hanging if client disconnects
  13686. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13687. [&] { return cid_ == id; })) {
  13688. return false; // Timeout occurred
  13689. }
  13690. sink->write(message_.data(), message_.size());
  13691. return true;
  13692. }
  13693. void send_event(const string &message) {
  13694. lock_guard<mutex> lk(m_);
  13695. cid_ = id_++;
  13696. message_ = message;
  13697. cv_.notify_all();
  13698. }
  13699. private:
  13700. mutex m_;
  13701. condition_variable cv_;
  13702. atomic_int id_{0};
  13703. atomic_int cid_{-1};
  13704. string message_;
  13705. };
  13706. TEST(ClientInThreadTest, Issue2068) {
  13707. EventDispatcher ed;
  13708. Server svr;
  13709. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13710. res.set_chunked_content_provider("text/event-stream",
  13711. [&](size_t /*offset*/, DataSink &sink) {
  13712. return ed.wait_event(&sink);
  13713. });
  13714. });
  13715. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13716. svr.wait_until_ready();
  13717. thread event_thread([&] {
  13718. int id = 0;
  13719. while (svr.is_running()) {
  13720. this_thread::sleep_for(chrono::milliseconds(500));
  13721. std::stringstream ss;
  13722. ss << "data: " << id << "\n\n";
  13723. ed.send_event(ss.str());
  13724. id++;
  13725. }
  13726. });
  13727. auto se = detail::scope_exit([&] {
  13728. svr.stop();
  13729. listen_thread.join();
  13730. event_thread.join();
  13731. ASSERT_FALSE(svr.is_running());
  13732. });
  13733. {
  13734. auto client = detail::make_unique<Client>(HOST, PORT);
  13735. client->set_read_timeout(std::chrono::minutes(10));
  13736. std::atomic<bool> stop{false};
  13737. std::thread t([&] {
  13738. client->Get("/event1",
  13739. [&](const char *, size_t) -> bool { return !stop; });
  13740. });
  13741. std::this_thread::sleep_for(std::chrono::seconds(2));
  13742. stop = true;
  13743. client->stop();
  13744. t.join();
  13745. // Reset client after thread has finished
  13746. client.reset();
  13747. }
  13748. }
  13749. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13750. auto handled = false;
  13751. Server svr;
  13752. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13753. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13754. auto se = detail::scope_exit([&] {
  13755. svr.stop();
  13756. t.join();
  13757. ASSERT_FALSE(svr.is_running());
  13758. ASSERT_FALSE(handled);
  13759. });
  13760. svr.wait_until_ready();
  13761. // Two Content-Length headers with different values — must be rejected
  13762. auto req = "POST /test HTTP/1.1\r\n"
  13763. "Content-Length: 5\r\n"
  13764. "Content-Length: 10\r\n"
  13765. "\r\n"
  13766. "hello";
  13767. std::string response;
  13768. ASSERT_TRUE(send_request(1, req, &response));
  13769. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13770. response.substr(0, response.find("\r\n")));
  13771. }
  13772. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13773. auto handled = false;
  13774. Server svr;
  13775. svr.Post("/test", [&](const Request &, Response &res) {
  13776. handled = true;
  13777. res.set_content("ok", "text/plain");
  13778. });
  13779. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13780. auto se = detail::scope_exit([&] {
  13781. svr.stop();
  13782. t.join();
  13783. ASSERT_FALSE(svr.is_running());
  13784. ASSERT_TRUE(handled);
  13785. });
  13786. svr.wait_until_ready();
  13787. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13788. auto req = "POST /test HTTP/1.1\r\n"
  13789. "Content-Length: 5\r\n"
  13790. "Content-Length: 5\r\n"
  13791. "\r\n"
  13792. "hello";
  13793. std::string response;
  13794. ASSERT_TRUE(send_request(1, req, &response));
  13795. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13796. }
  13797. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13798. Server svr;
  13799. svr.Get("/", [](const Request &req, Response &res) {
  13800. EXPECT_EQ(2U, req.trailers.size());
  13801. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13802. // Denied
  13803. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13804. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13805. // Accepted
  13806. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13807. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13808. EXPECT_TRUE(req.has_trailer("X-World"));
  13809. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13810. res.set_content("ok", "text/plain");
  13811. });
  13812. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13813. auto se = detail::scope_exit([&] {
  13814. svr.stop();
  13815. t.join();
  13816. ASSERT_FALSE(svr.is_running());
  13817. });
  13818. svr.wait_until_ready();
  13819. const std::string req = "GET / HTTP/1.1\r\n"
  13820. "Transfer-Encoding: chunked\r\n"
  13821. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13822. "\r\n"
  13823. "0\r\n"
  13824. "Content-Length: 10\r\n"
  13825. "Host: internal.local\r\n"
  13826. "Content-Type: malicious/content\r\n"
  13827. "Cookie: any\r\n"
  13828. "Set-Cookie: any\r\n"
  13829. "X-Forwarded-For: attacker.com\r\n"
  13830. "X-Real-Ip: 1.1.1.1\r\n"
  13831. "X-Hello: hello\r\n"
  13832. "X-World: world\r\n"
  13833. "\r\n";
  13834. std::string res;
  13835. ASSERT_TRUE(send_request(1, req, &res));
  13836. }
  13837. // A direct client that is not listed in trusted_proxies must not be able to
  13838. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13839. // the peer address on the actual TCP connection determines whether the
  13840. // header is honored.
  13841. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13842. Server svr;
  13843. // Deliberately does NOT include the loopback address the test client
  13844. // actually connects from, so the direct connection is not a trusted proxy.
  13845. svr.set_trusted_proxies({"203.0.113.66"});
  13846. std::string observed_remote_addr;
  13847. svr.Get("/ip", [&](const Request &req, Response &res) {
  13848. observed_remote_addr = req.remote_addr;
  13849. res.set_content("ok", "text/plain");
  13850. });
  13851. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13852. auto se = detail::scope_exit([&] {
  13853. svr.stop();
  13854. t.join();
  13855. ASSERT_FALSE(svr.is_running());
  13856. });
  13857. svr.wait_until_ready();
  13858. Client cli(HOST, PORT);
  13859. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13861. EXPECT_EQ(StatusCode::OK_200, res->status);
  13862. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13863. // ignored entirely and the real connection-level address retained.
  13864. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13865. observed_remote_addr == "127.0.0.1");
  13866. }
  13867. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13868. Server svr;
  13869. std::string observed_remote_addr;
  13870. std::string observed_xff;
  13871. svr.Get("/ip", [&](const Request &req, Response &res) {
  13872. observed_remote_addr = req.remote_addr;
  13873. observed_xff = req.get_header_value("X-Forwarded-For");
  13874. res.set_content("ok", "text/plain");
  13875. });
  13876. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13877. auto se = detail::scope_exit([&] {
  13878. svr.stop();
  13879. t.join();
  13880. ASSERT_FALSE(svr.is_running());
  13881. });
  13882. svr.wait_until_ready();
  13883. Client cli(HOST, PORT);
  13884. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13886. EXPECT_EQ(StatusCode::OK_200, res->status);
  13887. EXPECT_EQ(observed_xff, "203.0.113.66");
  13888. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13889. observed_remote_addr == "127.0.0.1");
  13890. }
  13891. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13892. Server svr;
  13893. svr.set_trusted_proxies({"203.0.113.66"});
  13894. std::string observed_remote_addr;
  13895. std::string observed_xff;
  13896. svr.Get("/ip", [&](const Request &req, Response &res) {
  13897. observed_remote_addr = req.remote_addr;
  13898. observed_xff = req.get_header_value("X-Forwarded-For");
  13899. res.set_content("ok", "text/plain");
  13900. });
  13901. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13902. auto se = detail::scope_exit([&] {
  13903. svr.stop();
  13904. t.join();
  13905. ASSERT_FALSE(svr.is_running());
  13906. });
  13907. svr.wait_until_ready();
  13908. Client cli(HOST, PORT);
  13909. auto res = cli.Get("/ip");
  13910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13911. EXPECT_EQ(StatusCode::OK_200, res->status);
  13912. EXPECT_EQ(observed_xff, "");
  13913. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13914. observed_remote_addr == "127.0.0.1");
  13915. }
  13916. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13917. Server svr;
  13918. // Include the loopback address the test client actually connects from, so
  13919. // the direct connection itself is recognized as the trusted proxy hop.
  13920. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13921. std::string observed_remote_addr;
  13922. std::string observed_xff;
  13923. svr.Get("/ip", [&](const Request &req, Response &res) {
  13924. observed_remote_addr = req.remote_addr;
  13925. observed_xff = req.get_header_value("X-Forwarded-For");
  13926. res.set_content("ok", "text/plain");
  13927. });
  13928. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13929. auto se = detail::scope_exit([&] {
  13930. svr.stop();
  13931. t.join();
  13932. ASSERT_FALSE(svr.is_running());
  13933. });
  13934. svr.wait_until_ready();
  13935. Client cli(HOST, PORT);
  13936. auto res = cli.Get(
  13937. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13939. EXPECT_EQ(StatusCode::OK_200, res->status);
  13940. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13941. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13942. }
  13943. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13944. Server svr;
  13945. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13946. std::string observed_remote_addr;
  13947. std::string observed_xff;
  13948. svr.Get("/ip", [&](const Request &req, Response &res) {
  13949. observed_remote_addr = req.remote_addr;
  13950. observed_xff = req.get_header_value("X-Forwarded-For");
  13951. res.set_content("ok", "text/plain");
  13952. });
  13953. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13954. auto se = detail::scope_exit([&] {
  13955. svr.stop();
  13956. t.join();
  13957. ASSERT_FALSE(svr.is_running());
  13958. });
  13959. svr.wait_until_ready();
  13960. Client cli(HOST, PORT);
  13961. auto res = cli.Get(
  13962. "/ip",
  13963. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13965. EXPECT_EQ(StatusCode::OK_200, res->status);
  13966. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13967. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13968. }
  13969. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13970. Server svr;
  13971. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13972. std::string observed_remote_addr;
  13973. std::string observed_xff;
  13974. svr.Get("/ip", [&](const Request &req, Response &res) {
  13975. observed_remote_addr = req.remote_addr;
  13976. observed_xff = req.get_header_value("X-Forwarded-For");
  13977. res.set_content("ok", "text/plain");
  13978. });
  13979. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13980. auto se = detail::scope_exit([&] {
  13981. svr.stop();
  13982. t.join();
  13983. ASSERT_FALSE(svr.is_running());
  13984. });
  13985. svr.wait_until_ready();
  13986. Client cli(HOST, PORT);
  13987. auto res = cli.Get(
  13988. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13990. EXPECT_EQ(StatusCode::OK_200, res->status);
  13991. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13992. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13993. // and must not be selected.
  13994. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13995. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13996. }
  13997. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13998. Server svr;
  13999. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  14000. std::string observed_remote_addr;
  14001. svr.Get("/ip", [&](const Request &req, Response &res) {
  14002. observed_remote_addr = req.remote_addr;
  14003. res.set_content("ok", "text/plain");
  14004. });
  14005. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14006. auto se = detail::scope_exit([&] {
  14007. svr.stop();
  14008. t.join();
  14009. ASSERT_FALSE(svr.is_running());
  14010. });
  14011. svr.wait_until_ready();
  14012. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  14013. // a forged address and the trusted proxy's own address; the forged value must
  14014. // not win over the address the trusted proxy actually recorded.
  14015. Client cli(HOST, PORT);
  14016. auto res = cli.Get(
  14017. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  14018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14019. EXPECT_EQ(StatusCode::OK_200, res->status);
  14020. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  14021. }
  14022. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  14023. Server svr;
  14024. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14025. std::string observed_remote_addr;
  14026. std::string observed_xff;
  14027. svr.Get("/ip", [&](const Request &req, Response &res) {
  14028. observed_remote_addr = req.remote_addr;
  14029. observed_xff = req.get_header_value("X-Forwarded-For");
  14030. res.set_content("ok", "text/plain");
  14031. });
  14032. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14033. auto se = detail::scope_exit([&] {
  14034. svr.stop();
  14035. t.join();
  14036. ASSERT_FALSE(svr.is_running());
  14037. });
  14038. svr.wait_until_ready();
  14039. Client cli(HOST, PORT);
  14040. auto res = cli.Get(
  14041. "/ip",
  14042. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  14043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14044. EXPECT_EQ(StatusCode::OK_200, res->status);
  14045. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  14046. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14047. }
  14048. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  14049. Server svr;
  14050. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  14051. std::string observed_remote_addr;
  14052. std::string observed_xff;
  14053. svr.Get("/ip", [&](const Request &req, Response &res) {
  14054. observed_remote_addr = req.remote_addr;
  14055. observed_xff = req.get_header_value("X-Forwarded-For");
  14056. res.set_content("ok", "text/plain");
  14057. });
  14058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14059. auto se = detail::scope_exit([&] {
  14060. svr.stop();
  14061. t.join();
  14062. ASSERT_FALSE(svr.is_running());
  14063. });
  14064. svr.wait_until_ready();
  14065. std::string raw_req =
  14066. "GET /ip HTTP/1.1\r\n"
  14067. "Host: localhost\r\n"
  14068. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  14069. "Connection: close\r\n"
  14070. "\r\n";
  14071. std::string out;
  14072. ASSERT_TRUE(send_request(5, raw_req, &out));
  14073. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14074. // Header parser trims surrounding whitespace of the header value
  14075. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  14076. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  14077. }
  14078. // An X-Forwarded-For header whose value parses to zero IP segments must not
  14079. // crash the server (it used to call front() on an empty vector inside
  14080. // get_client_ip). The connection-level remote address must be retained instead.
  14081. static void run_malformed_xff_test(const std::string &xff_value) {
  14082. Server svr;
  14083. svr.set_trusted_proxies({"192.0.2.45"});
  14084. std::string observed_remote_addr;
  14085. svr.Get("/ip", [&](const Request &req, Response &res) {
  14086. observed_remote_addr = req.remote_addr;
  14087. res.set_content("ok", "text/plain");
  14088. });
  14089. int port = 0;
  14090. thread t = thread([&]() {
  14091. port = svr.bind_to_any_port(HOST);
  14092. svr.listen_after_bind();
  14093. });
  14094. auto se = detail::scope_exit([&] {
  14095. svr.stop();
  14096. t.join();
  14097. ASSERT_FALSE(svr.is_running());
  14098. });
  14099. svr.wait_until_ready();
  14100. Client cli(HOST, port);
  14101. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  14102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14103. EXPECT_EQ(StatusCode::OK_200, res->status);
  14104. EXPECT_TRUE(observed_remote_addr == "::1" ||
  14105. observed_remote_addr == "127.0.0.1");
  14106. }
  14107. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  14108. run_malformed_xff_test("");
  14109. }
  14110. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  14111. run_malformed_xff_test(",");
  14112. }
  14113. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  14114. run_malformed_xff_test(", , ,");
  14115. }
  14116. #ifndef _WIN32
  14117. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  14118. Server svr;
  14119. svr.Post("/post", [&](const Request &req, Response &res) {
  14120. res.set_content(req.body, "text/plain");
  14121. });
  14122. svr.Put("/put", [&](const Request &req, Response &res) {
  14123. res.set_content(req.body, "text/plain");
  14124. });
  14125. svr.Patch("/patch", [&](const Request &req, Response &res) {
  14126. res.set_content(req.body, "text/plain");
  14127. });
  14128. svr.Delete("/delete", [&](const Request &req, Response &res) {
  14129. res.set_content(req.body, "text/plain");
  14130. });
  14131. thread t = thread([&]() { svr.listen(HOST, PORT); });
  14132. auto se = detail::scope_exit([&] {
  14133. svr.stop();
  14134. t.join();
  14135. ASSERT_FALSE(svr.is_running());
  14136. });
  14137. svr.wait_until_ready();
  14138. std::string resp;
  14139. // POST without Content-Length
  14140. ASSERT_TRUE(send_request(5,
  14141. "POST /post HTTP/1.1\r\n"
  14142. "Host: localhost\r\n"
  14143. "Connection: close\r\n"
  14144. "\r\n",
  14145. &resp));
  14146. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14147. // PUT without Content-Length
  14148. resp.clear();
  14149. ASSERT_TRUE(send_request(5,
  14150. "PUT /put HTTP/1.1\r\n"
  14151. "Host: localhost\r\n"
  14152. "Connection: close\r\n"
  14153. "\r\n",
  14154. &resp));
  14155. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14156. // PATCH without Content-Length
  14157. resp.clear();
  14158. ASSERT_TRUE(send_request(5,
  14159. "PATCH /patch HTTP/1.1\r\n"
  14160. "Host: localhost\r\n"
  14161. "Connection: close\r\n"
  14162. "\r\n",
  14163. &resp));
  14164. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14165. // DELETE without Content-Length
  14166. resp.clear();
  14167. ASSERT_TRUE(send_request(5,
  14168. "DELETE /delete HTTP/1.1\r\n"
  14169. "Host: localhost\r\n"
  14170. "Connection: close\r\n"
  14171. "\r\n",
  14172. &resp));
  14173. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14174. }
  14175. #endif
  14176. //==============================================================================
  14177. // open_stream() Tests
  14178. //==============================================================================
  14179. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  14180. std::string result;
  14181. char buf[8192];
  14182. ssize_t n;
  14183. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14184. result.append(buf, static_cast<size_t>(n));
  14185. }
  14186. return result;
  14187. }
  14188. // Mock stream for unit tests
  14189. class MockStream : public Stream {
  14190. public:
  14191. std::string data;
  14192. size_t pos = 0;
  14193. ssize_t error_after = -1; // -1 = no error
  14194. explicit MockStream(const std::string &d, ssize_t err = -1)
  14195. : data(d), error_after(err) {}
  14196. bool is_readable() const override { return true; }
  14197. bool wait_readable() const override { return true; }
  14198. bool wait_writable() const override { return true; }
  14199. ssize_t read(char *ptr, size_t size) override {
  14200. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  14201. if (pos >= data.size()) return 0;
  14202. size_t limit =
  14203. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  14204. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  14205. std::memcpy(ptr, data.data() + pos, to_read);
  14206. pos += to_read;
  14207. return static_cast<ssize_t>(to_read);
  14208. }
  14209. ssize_t write(const char *, size_t) override { return -1; }
  14210. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  14211. ip = "127.0.0.1";
  14212. port = 0;
  14213. }
  14214. void get_local_ip_and_port(std::string &ip, int &port) const override {
  14215. ip = "127.0.0.1";
  14216. port = 0;
  14217. }
  14218. socket_t socket() const override { return INVALID_SOCKET; }
  14219. time_t duration() const override { return 0; }
  14220. };
  14221. TEST(StreamHandleTest, Basic) {
  14222. ClientImpl::StreamHandle handle;
  14223. EXPECT_FALSE(handle.is_valid());
  14224. handle.response = detail::make_unique<Response>();
  14225. handle.error = Error::Connection;
  14226. EXPECT_FALSE(handle.is_valid());
  14227. handle.error = Error::Success;
  14228. EXPECT_TRUE(handle.is_valid());
  14229. }
  14230. TEST(BodyReaderTest, Basic) {
  14231. MockStream stream("Hello, World!");
  14232. detail::BodyReader reader;
  14233. reader.stream = &stream;
  14234. reader.content_length = 13;
  14235. char buf[32];
  14236. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  14237. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  14238. EXPECT_TRUE(reader.eof);
  14239. }
  14240. TEST(BodyReaderTest, NoStream) {
  14241. detail::BodyReader reader;
  14242. char buf[32];
  14243. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14244. EXPECT_EQ(Error::Connection, reader.last_error);
  14245. }
  14246. TEST(BodyReaderTest, Error) {
  14247. MockStream stream("Hello, World!", 5);
  14248. detail::BodyReader reader;
  14249. reader.stream = &stream;
  14250. reader.content_length = 13;
  14251. char buf[32];
  14252. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  14253. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14254. EXPECT_EQ(Error::Read, reader.last_error);
  14255. }
  14256. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  14257. // Mock-based StreamHandle tests relying on private internals are removed.
  14258. class OpenStreamTest : public ::testing::Test {
  14259. protected:
  14260. void SetUp() override {
  14261. svr_.Get("/hello", [](const Request &, Response &res) {
  14262. res.set_content("Hello World!", "text/plain");
  14263. });
  14264. svr_.Get("/large", [](const Request &, Response &res) {
  14265. res.set_content(std::string(10000, 'X'), "text/plain");
  14266. });
  14267. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  14268. res.set_content("Hello World!", "image/jpeg");
  14269. res.set_header("Content-Encoding", "UTF-8");
  14270. });
  14271. svr_.Get("/chunked", [](const Request &, Response &res) {
  14272. res.set_chunked_content_provider("text/plain",
  14273. [](size_t offset, DataSink &sink) {
  14274. if (offset < 15) {
  14275. sink.write("chunk", 5);
  14276. return true;
  14277. }
  14278. sink.done();
  14279. return true;
  14280. });
  14281. });
  14282. svr_.Get("/compressible", [](const Request &, Response &res) {
  14283. res.set_chunked_content_provider("text/plain", [](size_t offset,
  14284. DataSink &sink) {
  14285. if (offset < 100 * 1024) {
  14286. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  14287. sink.write(chunk.data(), chunk.size());
  14288. return true;
  14289. }
  14290. sink.done();
  14291. return true;
  14292. });
  14293. });
  14294. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  14295. [](const Request & /*req*/, Response &res) {
  14296. auto i = new int(0);
  14297. res.set_header("Trailer", "Content-Length, X-Allowed");
  14298. res.set_chunked_content_provider(
  14299. "text/plain",
  14300. [i](size_t /*offset*/, DataSink &sink) {
  14301. switch (*i) {
  14302. case 0: sink.os << "123"; break;
  14303. case 1: sink.os << "456"; break;
  14304. case 2: sink.os << "789"; break;
  14305. case 3: {
  14306. sink.done_with_trailer(
  14307. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  14308. } break;
  14309. }
  14310. (*i)++;
  14311. return true;
  14312. },
  14313. [i](bool success) {
  14314. EXPECT_TRUE(success);
  14315. delete i;
  14316. });
  14317. });
  14318. // Echo headers endpoint for header-related tests
  14319. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  14320. std::string body;
  14321. for (const auto &h : req.headers) {
  14322. body.append(h.first);
  14323. body.push_back(':');
  14324. body.append(h.second);
  14325. body.push_back('\n');
  14326. }
  14327. res.set_content(body, "text/plain");
  14328. });
  14329. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  14330. std::string body;
  14331. for (const auto &h : req.headers) {
  14332. body.append(h.first);
  14333. body.push_back(':');
  14334. body.append(h.second);
  14335. body.push_back('\n');
  14336. }
  14337. res.set_content(body, "text/plain");
  14338. });
  14339. port_ = svr_.bind_to_any_port("127.0.0.1");
  14340. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14341. svr_.wait_until_ready();
  14342. }
  14343. void TearDown() override {
  14344. svr_.stop();
  14345. if (thread_.joinable()) thread_.join();
  14346. }
  14347. Server svr_;
  14348. std::thread thread_;
  14349. int port_ = 0;
  14350. };
  14351. TEST_F(OpenStreamTest, Basic) {
  14352. Client cli("127.0.0.1", port_);
  14353. auto handle = cli.open_stream("GET", "/hello");
  14354. EXPECT_TRUE(handle.is_valid());
  14355. EXPECT_EQ("Hello World!", read_all(handle));
  14356. }
  14357. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  14358. Client cli("127.0.0.1", port_);
  14359. auto handle = cli.open_stream("GET", "/unknown-encoding");
  14360. ASSERT_TRUE(handle.is_valid());
  14361. EXPECT_EQ("Hello World!", read_all(handle));
  14362. }
  14363. TEST_F(OpenStreamTest, SmallBuffer) {
  14364. Client cli("127.0.0.1", port_);
  14365. auto handle = cli.open_stream("GET", "/hello");
  14366. std::string result;
  14367. char buf[4];
  14368. ssize_t n;
  14369. while ((n = handle.read(buf, sizeof(buf))) > 0)
  14370. result.append(buf, static_cast<size_t>(n));
  14371. EXPECT_EQ("Hello World!", result);
  14372. }
  14373. TEST_F(OpenStreamTest, DefaultHeaders) {
  14374. Client cli("127.0.0.1", port_);
  14375. // open_stream GET should include Host, User-Agent and Accept-Encoding
  14376. {
  14377. auto handle = cli.open_stream("GET", "/echo-headers");
  14378. ASSERT_TRUE(handle.is_valid());
  14379. auto body = read_all(handle);
  14380. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  14381. std::string::npos);
  14382. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  14383. std::string::npos);
  14384. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  14385. }
  14386. // open_stream POST with body and no explicit content_type should NOT add
  14387. // text/plain Content-Type (behavior differs from non-streaming path), but
  14388. // should include Content-Length
  14389. {
  14390. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14391. ASSERT_TRUE(handle.is_valid());
  14392. auto body = read_all(handle);
  14393. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14394. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14395. }
  14396. // open_stream POST with explicit Content-Type should preserve it
  14397. {
  14398. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14399. {{"Content-Type", "application/custom"}},
  14400. "{}", "application/custom");
  14401. ASSERT_TRUE(handle.is_valid());
  14402. auto body = read_all(handle);
  14403. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14404. }
  14405. // User-specified User-Agent must not be overwritten for stream API
  14406. {
  14407. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14408. {{"User-Agent", "MyAgent/1.2"}});
  14409. ASSERT_TRUE(handle.is_valid());
  14410. auto body = read_all(handle);
  14411. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14412. }
  14413. }
  14414. TEST_F(OpenStreamTest, Large) {
  14415. Client cli("127.0.0.1", port_);
  14416. auto handle = cli.open_stream("GET", "/large");
  14417. EXPECT_EQ(10000u, read_all(handle).size());
  14418. }
  14419. TEST_F(OpenStreamTest, ConnectionError) {
  14420. Client cli("127.0.0.1", 9999);
  14421. auto handle = cli.open_stream("GET", "/hello");
  14422. EXPECT_FALSE(handle.is_valid());
  14423. }
  14424. TEST_F(OpenStreamTest, Chunked) {
  14425. Client cli("127.0.0.1", port_);
  14426. auto handle = cli.open_stream("GET", "/chunked");
  14427. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14428. "Transfer-Encoding") == "chunked");
  14429. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14430. }
  14431. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14432. Client cli("127.0.0.1", port_);
  14433. auto handle =
  14434. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14435. ASSERT_TRUE(handle.is_valid());
  14436. // Consume body to allow trailers to be received/parsed
  14437. auto body = read_all(handle);
  14438. // Explicitly parse trailers (ensure trailers are available for assertion)
  14439. handle.parse_trailers_if_needed();
  14440. EXPECT_EQ(std::string("123456789"), body);
  14441. // The response should include a Trailer header declaring both names
  14442. ASSERT_TRUE(handle.response);
  14443. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14444. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14445. handle.response->get_header_value("Trailer"));
  14446. // Prohibited trailer must not be present
  14447. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14448. // Allowed trailer should be present
  14449. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14450. EXPECT_EQ(std::string("yes"),
  14451. handle.response->get_trailer_value("X-Allowed"));
  14452. // Verify trailers are NOT present as regular headers
  14453. EXPECT_EQ(std::string(""),
  14454. handle.response->get_header_value("Content-Length"));
  14455. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14456. }
  14457. static std::thread serve_single_response(std::promise<int> &port_promise,
  14458. const std::string &response) {
  14459. return std::thread([&port_promise, response] {
  14460. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14461. default_socket_options(srv);
  14462. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14463. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14464. sockaddr_in addr{};
  14465. addr.sin_family = AF_INET;
  14466. addr.sin_port = htons(0); // Let OS assign a free port
  14467. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14468. int opt = 1;
  14469. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14470. #ifdef _WIN32
  14471. reinterpret_cast<const char *>(&opt),
  14472. #else
  14473. &opt,
  14474. #endif
  14475. sizeof(opt));
  14476. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  14477. ::listen(srv, 1) != 0) {
  14478. port_promise.set_value(-1);
  14479. detail::close_socket(srv);
  14480. return;
  14481. }
  14482. socklen_t addr_len = sizeof(addr);
  14483. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  14484. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  14485. sockaddr_in cli_addr{};
  14486. socklen_t cli_len = sizeof(cli_addr);
  14487. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14488. if (cli != INVALID_SOCKET) {
  14489. // Read the complete HTTP request (until the blank line that terminates
  14490. // headers) before sending the response. If the server closes the socket
  14491. // while the client's request data is still unread in the kernel receive
  14492. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  14493. // connection on both sides: it discards the client's receive buffer
  14494. // (which already holds our response) and causes any in-progress write on
  14495. // the client to fail with ECONNRESET. Reading all request data first
  14496. // ensures close() emits a graceful FIN.
  14497. {
  14498. char rbuf[256];
  14499. std::string req;
  14500. while (req.find("\r\n\r\n") == std::string::npos) {
  14501. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  14502. if (n <= 0) { break; }
  14503. req.append(rbuf, static_cast<size_t>(n));
  14504. }
  14505. }
  14506. ::send(cli,
  14507. #ifdef _WIN32
  14508. static_cast<const char *>(response.c_str()),
  14509. static_cast<int>(response.size()),
  14510. #else
  14511. response.c_str(), response.size(),
  14512. #endif
  14513. 0);
  14514. detail::close_socket(cli);
  14515. }
  14516. detail::close_socket(srv);
  14517. });
  14518. }
  14519. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  14520. #ifndef _WIN32
  14521. signal(SIGPIPE, SIG_IGN);
  14522. #endif
  14523. std::promise<int> port_promise;
  14524. auto port_future = port_promise.get_future();
  14525. auto server_thread =
  14526. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  14527. "Content-Type: text/plain\r\n"
  14528. "Content-Length: not-a-number\r\n"
  14529. "Connection: close\r\n"
  14530. "\r\n"
  14531. "hello");
  14532. auto port = port_future.get();
  14533. ASSERT_GT(port, 0);
  14534. Client cli("127.0.0.1", port);
  14535. auto handle = cli.open_stream("GET", "/");
  14536. EXPECT_FALSE(handle.is_valid());
  14537. server_thread.join();
  14538. }
  14539. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14540. #ifndef _WIN32
  14541. signal(SIGPIPE, SIG_IGN);
  14542. #endif
  14543. std::promise<int> port_promise;
  14544. auto port_future = port_promise.get_future();
  14545. auto server_thread = serve_single_response(
  14546. port_promise, "HTTP/1.1 200 OK\r\n"
  14547. "Content-Type: text/plain\r\n"
  14548. "Content-Length: 99999999999999999999999999\r\n"
  14549. "Connection: close\r\n"
  14550. "\r\n"
  14551. "hello");
  14552. auto port = port_future.get();
  14553. ASSERT_GT(port, 0);
  14554. // Historically std::stoull would throw std::out_of_range here and crash
  14555. // the process, then parsing silently clamped to a bogus framing length and
  14556. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  14557. // so the stream fails to open, matching the not-a-number case above. The
  14558. // process still must NOT terminate.
  14559. Client cli("127.0.0.1", port);
  14560. auto handle = cli.open_stream("GET", "/");
  14561. EXPECT_FALSE(handle.is_valid());
  14562. server_thread.join();
  14563. }
  14564. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14565. TEST_F(OpenStreamTest, Gzip) {
  14566. Client cli("127.0.0.1", port_);
  14567. auto handle = cli.open_stream("GET", "/compressible", {},
  14568. {{"Accept-Encoding", "gzip"}});
  14569. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  14570. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14571. }
  14572. #endif
  14573. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14574. TEST_F(OpenStreamTest, Brotli) {
  14575. Client cli("127.0.0.1", port_);
  14576. auto handle =
  14577. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  14578. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  14579. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14580. }
  14581. #endif
  14582. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14583. TEST_F(OpenStreamTest, Zstd) {
  14584. Client cli("127.0.0.1", port_);
  14585. auto handle = cli.open_stream("GET", "/compressible", {},
  14586. {{"Accept-Encoding", "zstd"}});
  14587. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  14588. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14589. }
  14590. #endif
  14591. #ifdef CPPHTTPLIB_SSL_ENABLED
  14592. class SSLOpenStreamTest : public ::testing::Test {
  14593. protected:
  14594. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  14595. void SetUp() override {
  14596. svr_.Get("/hello", [](const Request &, Response &res) {
  14597. res.set_content("Hello SSL World!", "text/plain");
  14598. });
  14599. svr_.Get("/chunked", [](const Request &, Response &res) {
  14600. res.set_chunked_content_provider("text/plain",
  14601. [](size_t offset, DataSink &sink) {
  14602. if (offset < 15) {
  14603. sink.write("chunk", 5);
  14604. return true;
  14605. }
  14606. sink.done();
  14607. return true;
  14608. });
  14609. });
  14610. svr_.Post("/echo", [](const Request &req, Response &res) {
  14611. res.set_content(req.body, req.get_header_value("Content-Type"));
  14612. });
  14613. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  14614. std::string body = req.body;
  14615. res.set_chunked_content_provider(
  14616. "text/plain", [body](size_t offset, DataSink &sink) {
  14617. if (offset < body.size()) {
  14618. sink.write(body.data() + offset, body.size() - offset);
  14619. }
  14620. sink.done();
  14621. return true;
  14622. });
  14623. });
  14624. port_ = svr_.bind_to_any_port("127.0.0.1");
  14625. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14626. svr_.wait_until_ready();
  14627. }
  14628. void TearDown() override {
  14629. svr_.stop();
  14630. if (thread_.joinable()) thread_.join();
  14631. }
  14632. SSLServer svr_;
  14633. std::thread thread_;
  14634. int port_ = 0;
  14635. };
  14636. TEST_F(SSLOpenStreamTest, Basic) {
  14637. SSLClient cli("127.0.0.1", port_);
  14638. cli.enable_server_certificate_verification(false);
  14639. auto handle = cli.open_stream("GET", "/hello");
  14640. ASSERT_TRUE(handle.is_valid());
  14641. EXPECT_EQ("Hello SSL World!", read_all(handle));
  14642. }
  14643. TEST_F(SSLOpenStreamTest, Chunked) {
  14644. SSLClient cli("127.0.0.1", port_);
  14645. cli.enable_server_certificate_verification(false);
  14646. auto handle = cli.open_stream("GET", "/chunked");
  14647. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14648. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14649. "Transfer-Encoding") == "chunked");
  14650. auto body = read_all(handle);
  14651. EXPECT_EQ("chunkchunkchunk", body);
  14652. }
  14653. TEST_F(SSLOpenStreamTest, Post) {
  14654. SSLClient cli("127.0.0.1", port_);
  14655. cli.enable_server_certificate_verification(false);
  14656. auto handle =
  14657. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  14658. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14659. EXPECT_EQ(200, handle.response->status);
  14660. auto body = read_all(handle);
  14661. EXPECT_EQ("Hello SSL POST", body);
  14662. }
  14663. TEST_F(SSLOpenStreamTest, PostChunked) {
  14664. SSLClient cli("127.0.0.1", port_);
  14665. cli.enable_server_certificate_verification(false);
  14666. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  14667. "Chunked SSL Data", "text/plain");
  14668. ASSERT_TRUE(handle.is_valid());
  14669. EXPECT_EQ(200, handle.response->status);
  14670. auto body = read_all(handle);
  14671. EXPECT_EQ("Chunked SSL Data", body);
  14672. }
  14673. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  14674. // Content-Length is terminated by the server closing the connection. When the
  14675. // SSL peer sends a close_notify after the body, the client must treat it as a
  14676. // clean EOF and return a successful response rather than an error.
  14677. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  14678. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14679. ASSERT_TRUE(svr.is_valid());
  14680. svr.set_keep_alive_max_count(1);
  14681. const std::string expected_body = "Hello from connection-close response!";
  14682. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  14683. res.set_content_provider("text/plain",
  14684. [&](size_t offset, DataSink &sink) -> bool {
  14685. if (offset < expected_body.size()) {
  14686. sink.write(expected_body.data() + offset,
  14687. expected_body.size() - offset);
  14688. }
  14689. sink.done();
  14690. return true;
  14691. });
  14692. });
  14693. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  14694. auto se = detail::scope_exit([&] {
  14695. svr.stop();
  14696. listen_thread.join();
  14697. ASSERT_FALSE(svr.is_running());
  14698. });
  14699. svr.wait_until_ready();
  14700. SSLClient cli(HOST, PORT);
  14701. cli.enable_server_certificate_verification(false);
  14702. auto res = cli.Get("/no-content-length");
  14703. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  14704. EXPECT_EQ(StatusCode::OK_200, res->status);
  14705. EXPECT_EQ(expected_body, res->body);
  14706. }
  14707. #endif // CPPHTTPLIB_SSL_ENABLED
  14708. //==============================================================================
  14709. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  14710. // results for various scenarios.
  14711. //==============================================================================
  14712. TEST(ParityTest, GetVsOpenStream) {
  14713. Server svr;
  14714. const std::string path = "/parity";
  14715. const std::string content = "Parity test content: hello world";
  14716. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14717. res.set_content(content, "text/plain");
  14718. });
  14719. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14720. auto se = detail::scope_exit([&] {
  14721. svr.stop();
  14722. t.join();
  14723. ASSERT_FALSE(svr.is_running());
  14724. });
  14725. svr.wait_until_ready();
  14726. Client cli(HOST, PORT);
  14727. // Non-stream path
  14728. auto r1 = cli.Get(path);
  14729. ASSERT_TRUE(r1);
  14730. EXPECT_EQ(StatusCode::OK_200, r1->status);
  14731. // Stream path
  14732. auto h = cli.open_stream("GET", path);
  14733. ASSERT_TRUE(h.is_valid());
  14734. EXPECT_EQ(r1->body, read_all(h));
  14735. }
  14736. // Helper to compress data with provided compressor type T
  14737. template <typename Compressor>
  14738. static std::string compress_payload_for_parity(const std::string &in) {
  14739. std::string out;
  14740. Compressor compressor;
  14741. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14742. [&](const char *data, size_t n) {
  14743. out.append(data, n);
  14744. return true;
  14745. });
  14746. EXPECT_TRUE(ok);
  14747. return out;
  14748. }
  14749. // Helper function for compression parity tests
  14750. template <typename Compressor>
  14751. static void test_compression_parity(const std::string &original,
  14752. const std::string &path,
  14753. const std::string &encoding) {
  14754. const std::string compressed =
  14755. compress_payload_for_parity<Compressor>(original);
  14756. Server svr;
  14757. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14758. res.set_content(compressed, "application/octet-stream");
  14759. res.set_header("Content-Encoding", encoding);
  14760. });
  14761. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14762. auto se = detail::scope_exit([&] {
  14763. svr.stop();
  14764. t.join();
  14765. ASSERT_FALSE(svr.is_running());
  14766. });
  14767. svr.wait_until_ready();
  14768. Client cli(HOST, PORT);
  14769. // Non-streaming
  14770. {
  14771. auto res = cli.Get(path);
  14772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14773. EXPECT_EQ(StatusCode::OK_200, res->status);
  14774. EXPECT_EQ(original, res->body);
  14775. }
  14776. // Streaming
  14777. {
  14778. auto h = cli.open_stream("GET", path);
  14779. ASSERT_TRUE(h.is_valid());
  14780. EXPECT_EQ(original, read_all(h));
  14781. }
  14782. }
  14783. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14784. TEST(ParityTest, Gzip) {
  14785. test_compression_parity<detail::gzip_compressor>(
  14786. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14787. }
  14788. #endif
  14789. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14790. TEST(ParityTest, Brotli) {
  14791. test_compression_parity<detail::brotli_compressor>(
  14792. "Hello, brotli parity test payload", "/parity-br", "br");
  14793. }
  14794. #endif
  14795. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14796. TEST(ParityTest, Zstd) {
  14797. test_compression_parity<detail::zstd_compressor>(
  14798. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14799. }
  14800. #endif
  14801. //==============================================================================
  14802. // New Stream API Tests
  14803. //==============================================================================
  14804. inline std::string read_body(httplib::stream::Result &result) {
  14805. std::string body;
  14806. while (result.next()) {
  14807. body.append(result.data(), result.size());
  14808. }
  14809. return body;
  14810. }
  14811. TEST(ClientConnectionTest, Basic) {
  14812. httplib::ClientConnection conn;
  14813. EXPECT_FALSE(conn.is_open());
  14814. conn.sock = 1;
  14815. EXPECT_TRUE(conn.is_open());
  14816. httplib::ClientConnection conn2(std::move(conn));
  14817. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14818. conn2.sock = INVALID_SOCKET;
  14819. }
  14820. // Unified test server for all stream::* tests
  14821. class StreamApiTest : public ::testing::Test {
  14822. protected:
  14823. void SetUp() override {
  14824. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14825. res.set_content("Hello World!", "text/plain");
  14826. });
  14827. svr_.Get("/echo-params",
  14828. [](const httplib::Request &req, httplib::Response &res) {
  14829. std::string r;
  14830. for (const auto &p : req.params) {
  14831. if (!r.empty()) r += "&";
  14832. r += p.first + "=" + p.second;
  14833. }
  14834. res.set_content(r, "text/plain");
  14835. });
  14836. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14837. res.set_content(req.body, req.get_header_value("Content-Type"));
  14838. });
  14839. svr_.Post("/echo-headers",
  14840. [](const httplib::Request &req, httplib::Response &res) {
  14841. std::string r;
  14842. for (const auto &h : req.headers)
  14843. r += h.first + ": " + h.second + "\n";
  14844. res.set_content(r, "text/plain");
  14845. });
  14846. svr_.Post("/echo-params",
  14847. [](const httplib::Request &req, httplib::Response &res) {
  14848. std::string r = "params:";
  14849. for (const auto &p : req.params)
  14850. r += p.first + "=" + p.second + ";";
  14851. res.set_content(r + " body:" + req.body, "text/plain");
  14852. });
  14853. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14854. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14855. });
  14856. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14857. res.set_content("PUT:" + req.body, "text/plain");
  14858. });
  14859. svr_.Patch("/echo",
  14860. [](const httplib::Request &req, httplib::Response &res) {
  14861. res.set_content("PATCH:" + req.body, "text/plain");
  14862. });
  14863. svr_.Delete(
  14864. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14865. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14866. "text/plain");
  14867. });
  14868. svr_.Get("/head-test",
  14869. [](const httplib::Request &, httplib::Response &res) {
  14870. res.set_content("body for HEAD", "text/plain");
  14871. });
  14872. svr_.Options("/options",
  14873. [](const httplib::Request &, httplib::Response &res) {
  14874. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14875. });
  14876. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14877. svr_.wait_until_ready();
  14878. }
  14879. void TearDown() override {
  14880. svr_.stop();
  14881. if (thread_.joinable()) thread_.join();
  14882. }
  14883. httplib::Server svr_;
  14884. std::thread thread_;
  14885. };
  14886. // stream::Get tests
  14887. TEST_F(StreamApiTest, GetBasic) {
  14888. httplib::Client cli(HOST, PORT);
  14889. auto result = httplib::stream::Get(cli, "/hello");
  14890. ASSERT_TRUE(result.is_valid());
  14891. EXPECT_EQ(200, result.status());
  14892. EXPECT_EQ("Hello World!", read_body(result));
  14893. }
  14894. TEST_F(StreamApiTest, GetWithParams) {
  14895. httplib::Client cli(HOST, PORT);
  14896. httplib::Params params{{"foo", "bar"}};
  14897. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14898. ASSERT_TRUE(result.is_valid());
  14899. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14900. }
  14901. TEST_F(StreamApiTest, GetConnectionError) {
  14902. httplib::Client cli(HOST, 9999);
  14903. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14904. }
  14905. TEST_F(StreamApiTest, Get404) {
  14906. httplib::Client cli(HOST, PORT);
  14907. auto result = httplib::stream::Get(cli, "/nonexistent");
  14908. EXPECT_TRUE(result.is_valid());
  14909. EXPECT_EQ(404, result.status());
  14910. }
  14911. // stream::Post tests
  14912. TEST_F(StreamApiTest, PostBasic) {
  14913. httplib::Client cli(HOST, PORT);
  14914. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14915. "application/json");
  14916. ASSERT_TRUE(result.is_valid());
  14917. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14918. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14919. }
  14920. TEST_F(StreamApiTest, PostWithHeaders) {
  14921. httplib::Client cli(HOST, PORT);
  14922. httplib::Headers headers{{"X-Custom", "value"}};
  14923. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14924. "text/plain");
  14925. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14926. }
  14927. TEST_F(StreamApiTest, PostWithParams) {
  14928. httplib::Client cli(HOST, PORT);
  14929. httplib::Params params{{"k", "v"}};
  14930. auto result =
  14931. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14932. auto body = read_body(result);
  14933. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14934. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14935. }
  14936. TEST_F(StreamApiTest, PostLarge) {
  14937. httplib::Client cli(HOST, PORT);
  14938. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14939. size_t total = 0;
  14940. while (result.next()) {
  14941. total += result.size();
  14942. }
  14943. EXPECT_EQ(100u * 1024u, total);
  14944. }
  14945. // stream::Put/Patch tests
  14946. TEST_F(StreamApiTest, PutAndPatch) {
  14947. httplib::Client cli(HOST, PORT);
  14948. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14949. EXPECT_EQ("PUT:test", read_body(put));
  14950. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14951. EXPECT_EQ("PATCH:test", read_body(patch));
  14952. }
  14953. // stream::Delete tests
  14954. TEST_F(StreamApiTest, Delete) {
  14955. httplib::Client cli(HOST, PORT);
  14956. auto del1 = httplib::stream::Delete(cli, "/resource");
  14957. EXPECT_EQ("Deleted", read_body(del1));
  14958. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14959. EXPECT_EQ("Deleted:data", read_body(del2));
  14960. }
  14961. // stream::Head/Options tests
  14962. TEST_F(StreamApiTest, HeadAndOptions) {
  14963. httplib::Client cli(HOST, PORT);
  14964. auto head = httplib::stream::Head(cli, "/head-test");
  14965. EXPECT_TRUE(head.is_valid());
  14966. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14967. auto opts = httplib::stream::Options(cli, "/options");
  14968. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14969. }
  14970. // SSL stream::* tests
  14971. #ifdef CPPHTTPLIB_SSL_ENABLED
  14972. class SSLStreamApiTest : public ::testing::Test {
  14973. protected:
  14974. void SetUp() override {
  14975. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14976. res.set_content("Hello SSL!", "text/plain");
  14977. });
  14978. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14979. res.set_content(req.body, "text/plain");
  14980. });
  14981. port_ = svr_.bind_to_any_port("127.0.0.1");
  14982. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14983. svr_.wait_until_ready();
  14984. }
  14985. void TearDown() override {
  14986. svr_.stop();
  14987. if (thread_.joinable()) thread_.join();
  14988. }
  14989. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14990. std::thread thread_;
  14991. int port_ = 0;
  14992. };
  14993. TEST_F(SSLStreamApiTest, GetAndPost) {
  14994. httplib::SSLClient cli("127.0.0.1", port_);
  14995. cli.enable_server_certificate_verification(false);
  14996. auto get = httplib::stream::Get(cli, "/hello");
  14997. EXPECT_EQ("Hello SSL!", read_body(get));
  14998. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14999. EXPECT_EQ("test", read_body(post));
  15000. }
  15001. #endif
  15002. // Tests for Error::Timeout and Error::ConnectionClosed error types
  15003. // These errors are set in SocketStream/SSLSocketStream and propagated through
  15004. // BodyReader
  15005. TEST(ErrorHandlingTest, StreamReadTimeout) {
  15006. // Test that read timeout during streaming is detected
  15007. // Use a large content-length response where server delays mid-stream
  15008. Server svr;
  15009. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15010. // Send a large response with delay in the middle
  15011. res.set_content_provider(
  15012. 1000, // content_length
  15013. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  15014. if (offset < 100) {
  15015. // Send first 100 bytes immediately
  15016. std::string data(100, 'A');
  15017. sink.write(data.c_str(), data.size());
  15018. return true;
  15019. }
  15020. // Then delay longer than client timeout
  15021. std::this_thread::sleep_for(std::chrono::seconds(3));
  15022. std::string data(900, 'B');
  15023. sink.write(data.c_str(), data.size());
  15024. return true;
  15025. });
  15026. });
  15027. auto port = 8091;
  15028. std::thread t([&]() { svr.listen("localhost", port); });
  15029. svr.wait_until_ready();
  15030. Client cli("localhost", port);
  15031. cli.set_read_timeout(1, 0); // 1 second timeout
  15032. auto handle = cli.open_stream("GET", "/slow-stream");
  15033. ASSERT_TRUE(handle.is_valid());
  15034. char buf[256];
  15035. ssize_t total = 0;
  15036. ssize_t n;
  15037. bool got_error = false;
  15038. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15039. total += n;
  15040. }
  15041. if (n < 0) {
  15042. got_error = true;
  15043. // Should be timeout or read error
  15044. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15045. handle.get_read_error() == Error::Read)
  15046. << "Actual error: " << to_string(handle.get_read_error());
  15047. }
  15048. // Either we got an error, or we got less data than expected
  15049. EXPECT_TRUE(got_error || total < 1000)
  15050. << "Expected timeout but got all " << total << " bytes";
  15051. svr.stop();
  15052. t.join();
  15053. }
  15054. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  15055. // Test connection closed detection via BodyReader
  15056. Server svr;
  15057. std::atomic<bool> close_now{false};
  15058. svr.Get("/will-close", [&](const Request &, Response &res) {
  15059. res.set_content_provider(
  15060. 10000, // Large content_length that we won't fully send
  15061. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15062. if (offset < 100) {
  15063. std::string data(100, 'X');
  15064. sink.write(data.c_str(), data.size());
  15065. return true;
  15066. }
  15067. // Wait for signal then abort
  15068. while (!close_now) {
  15069. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15070. }
  15071. return false; // Abort - server will close connection
  15072. });
  15073. });
  15074. auto port = 8092;
  15075. std::thread t([&]() { svr.listen("localhost", port); });
  15076. svr.wait_until_ready();
  15077. Client cli("localhost", port);
  15078. auto handle = cli.open_stream("GET", "/will-close");
  15079. ASSERT_TRUE(handle.is_valid());
  15080. char buf[256];
  15081. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15082. EXPECT_GT(n, 0) << "First read should succeed";
  15083. // Signal server to close
  15084. close_now = true;
  15085. // Keep reading until error or EOF
  15086. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15087. // Keep reading
  15088. }
  15089. // Should get an error since content_length wasn't satisfied
  15090. if (n < 0) {
  15091. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15092. handle.get_read_error() == Error::Read)
  15093. << "Actual error: " << to_string(handle.get_read_error());
  15094. }
  15095. svr.stop();
  15096. t.join();
  15097. }
  15098. #ifdef CPPHTTPLIB_SSL_ENABLED
  15099. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  15100. // Test that read timeout during SSL streaming is detected
  15101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15102. svr.Get("/slow-stream", [](const Request &, Response &res) {
  15103. res.set_content_provider(
  15104. 1000, "text/plain",
  15105. [](size_t offset, size_t /*length*/, DataSink &sink) {
  15106. if (offset < 100) {
  15107. std::string data(100, 'A');
  15108. sink.write(data.c_str(), data.size());
  15109. return true;
  15110. }
  15111. std::this_thread::sleep_for(std::chrono::seconds(3));
  15112. std::string data(900, 'B');
  15113. sink.write(data.c_str(), data.size());
  15114. return true;
  15115. });
  15116. });
  15117. auto port = 8093;
  15118. std::thread t([&]() { svr.listen("localhost", port); });
  15119. svr.wait_until_ready();
  15120. SSLClient cli("localhost", port);
  15121. cli.enable_server_certificate_verification(false);
  15122. cli.set_read_timeout(1, 0); // 1 second timeout
  15123. auto handle = cli.open_stream("GET", "/slow-stream");
  15124. ASSERT_TRUE(handle.is_valid());
  15125. char buf[256];
  15126. ssize_t total = 0;
  15127. ssize_t n;
  15128. bool got_error = false;
  15129. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15130. total += n;
  15131. }
  15132. if (n < 0) {
  15133. got_error = true;
  15134. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  15135. handle.get_read_error() == Error::Read)
  15136. << "Actual error: " << to_string(handle.get_read_error());
  15137. }
  15138. EXPECT_TRUE(got_error || total < 1000)
  15139. << "Expected timeout but got all " << total << " bytes";
  15140. svr.stop();
  15141. t.join();
  15142. }
  15143. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  15144. // Test SSL connection closed detection
  15145. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15146. std::atomic<bool> close_now{false};
  15147. svr.Get("/will-close", [&](const Request &, Response &res) {
  15148. res.set_content_provider(
  15149. 10000, "text/plain",
  15150. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  15151. if (offset < 100) {
  15152. std::string data(100, 'X');
  15153. sink.write(data.c_str(), data.size());
  15154. return true;
  15155. }
  15156. while (!close_now) {
  15157. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15158. }
  15159. return false;
  15160. });
  15161. });
  15162. auto port = 8094;
  15163. std::thread t([&]() { svr.listen("localhost", port); });
  15164. svr.wait_until_ready();
  15165. SSLClient cli("localhost", port);
  15166. cli.enable_server_certificate_verification(false);
  15167. auto handle = cli.open_stream("GET", "/will-close");
  15168. ASSERT_TRUE(handle.is_valid());
  15169. char buf[256];
  15170. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15171. EXPECT_GT(n, 0);
  15172. // Signal server to close
  15173. close_now = true;
  15174. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15175. // Keep reading
  15176. }
  15177. if (n < 0) {
  15178. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15179. handle.get_read_error() == Error::Read)
  15180. << "Actual error: " << to_string(handle.get_read_error());
  15181. }
  15182. svr.stop();
  15183. t.join();
  15184. }
  15185. #endif
  15186. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  15187. using namespace httplib;
  15188. // Create a test file
  15189. const char *fname = "etag_testfile.txt";
  15190. const char *content = "etag-content";
  15191. {
  15192. std::ofstream ofs(fname);
  15193. ofs << content;
  15194. ASSERT_TRUE(ofs.good());
  15195. }
  15196. Server svr;
  15197. svr.set_mount_point("/static", ".");
  15198. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15199. svr.wait_until_ready();
  15200. Client cli(HOST, PORT);
  15201. // First request: should get 200 with ETag header
  15202. auto res1 = cli.Get("/static/etag_testfile.txt");
  15203. ASSERT_TRUE(res1);
  15204. ASSERT_EQ(200, res1->status);
  15205. ASSERT_TRUE(res1->has_header("ETag"));
  15206. std::string etag = res1->get_header_value("ETag");
  15207. EXPECT_FALSE(etag.empty());
  15208. // Verify ETag format: W/"hex-hex"
  15209. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  15210. EXPECT_EQ('W', etag[0]);
  15211. EXPECT_EQ('/', etag[1]);
  15212. EXPECT_EQ('"', etag[2]);
  15213. EXPECT_EQ('"', etag.back());
  15214. // Exact match: expect 304 Not Modified
  15215. Headers h2 = {{"If-None-Match", etag}};
  15216. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  15217. ASSERT_TRUE(res2);
  15218. EXPECT_EQ(304, res2->status);
  15219. // Wildcard match: expect 304 Not Modified
  15220. Headers h3 = {{"If-None-Match", "*"}};
  15221. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  15222. ASSERT_TRUE(res3);
  15223. EXPECT_EQ(304, res3->status);
  15224. // Non-matching ETag: expect 200
  15225. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  15226. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  15227. ASSERT_TRUE(res4);
  15228. EXPECT_EQ(200, res4->status);
  15229. // Multiple ETags with one matching: expect 304
  15230. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  15231. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  15232. ASSERT_TRUE(res5);
  15233. EXPECT_EQ(304, res5->status);
  15234. svr.stop();
  15235. t.join();
  15236. std::remove(fname);
  15237. }
  15238. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  15239. using namespace httplib;
  15240. Server svr;
  15241. svr.set_mount_point("/static", ".");
  15242. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15243. svr.wait_until_ready();
  15244. Client cli(HOST, PORT);
  15245. // Send If-None-Match: * to a non-existent file
  15246. Headers h = {{"If-None-Match", "*"}};
  15247. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  15248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15249. EXPECT_EQ(404, res->status);
  15250. svr.stop();
  15251. t.join();
  15252. }
  15253. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  15254. using namespace httplib;
  15255. // Create a test file
  15256. const char *fname = "etag_boundary_testfile.txt";
  15257. const char *content = "boundary-test";
  15258. {
  15259. std::ofstream ofs(fname);
  15260. ofs << content;
  15261. ASSERT_TRUE(ofs.good());
  15262. }
  15263. Server svr;
  15264. svr.set_mount_point("/static", ".");
  15265. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15266. svr.wait_until_ready();
  15267. Client cli(HOST, PORT);
  15268. // Get the actual ETag
  15269. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  15270. ASSERT_TRUE(res1);
  15271. ASSERT_EQ(200, res1->status);
  15272. ASSERT_TRUE(res1->has_header("ETag"));
  15273. std::string etag = res1->get_header_value("ETag");
  15274. // Test 1: Very long ETag value (longer than actual ETag)
  15275. // Should NOT match and return 200 (not trigger out-of-bounds read)
  15276. Headers h1 = {{"If-None-Match", "W/"
  15277. "\"very-long-etag-value-that-is-much-longer-"
  15278. "than-the-actual-etag-value\""}};
  15279. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  15280. ASSERT_TRUE(res2);
  15281. EXPECT_EQ(200, res2->status); // Should not match
  15282. // Test 2: Long string followed by wildcard
  15283. // Should match on "*" and return 304 (without out-of-bounds read on the long
  15284. // string)
  15285. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  15286. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  15287. ASSERT_TRUE(res3);
  15288. EXPECT_EQ(304, res3->status); // Should match on "*"
  15289. // Test 3: Wildcard followed by long string
  15290. // Should match on "*" immediately and return 304
  15291. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  15292. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  15293. ASSERT_TRUE(res4);
  15294. EXPECT_EQ(304, res4->status); // Should match on "*"
  15295. // Test 4: Multiple long non-matching values
  15296. // Should NOT match and return 200 (test that all comparisons are safe)
  15297. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  15298. "W/\"second-long-non-matching-value\", "
  15299. "W/\"third-long-non-matching-value\""}};
  15300. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  15301. ASSERT_TRUE(res5);
  15302. EXPECT_EQ(200, res5->status); // Should not match
  15303. // Test 5: Single character that is not "*" (edge case)
  15304. Headers h5 = {{"If-None-Match", "X"}};
  15305. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  15306. ASSERT_TRUE(res6);
  15307. EXPECT_EQ(200, res6->status); // Should not match
  15308. svr.stop();
  15309. t.join();
  15310. std::remove(fname);
  15311. }
  15312. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  15313. using namespace httplib;
  15314. // Create a test file
  15315. const char *fname = "ims_testfile.txt";
  15316. const char *content = "if-modified-since-test";
  15317. {
  15318. std::ofstream ofs(fname);
  15319. ofs << content;
  15320. ASSERT_TRUE(ofs.good());
  15321. }
  15322. Server svr;
  15323. svr.set_mount_point("/static", ".");
  15324. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15325. svr.wait_until_ready();
  15326. Client cli(HOST, PORT);
  15327. // First request: should get 200 with Last-Modified header
  15328. auto res1 = cli.Get("/static/ims_testfile.txt");
  15329. ASSERT_TRUE(res1);
  15330. ASSERT_EQ(200, res1->status);
  15331. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15332. std::string last_modified = res1->get_header_value("Last-Modified");
  15333. EXPECT_FALSE(last_modified.empty());
  15334. // If-Modified-Since with same time: expect 304
  15335. Headers h2 = {{"If-Modified-Since", last_modified}};
  15336. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  15337. ASSERT_TRUE(res2);
  15338. EXPECT_EQ(304, res2->status);
  15339. // If-Modified-Since with future time: expect 304
  15340. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15341. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  15342. ASSERT_TRUE(res3);
  15343. EXPECT_EQ(304, res3->status);
  15344. // If-Modified-Since with past time: expect 200
  15345. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15346. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  15347. ASSERT_TRUE(res4);
  15348. EXPECT_EQ(200, res4->status);
  15349. // If-None-Match takes precedence over If-Modified-Since
  15350. // (send matching ETag with old If-Modified-Since -> should still be 304)
  15351. ASSERT_TRUE(res1->has_header("ETag"));
  15352. std::string etag = res1->get_header_value("ETag");
  15353. Headers h5 = {{"If-None-Match", etag},
  15354. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15355. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  15356. ASSERT_TRUE(res5);
  15357. EXPECT_EQ(304, res5->status);
  15358. svr.stop();
  15359. t.join();
  15360. std::remove(fname);
  15361. }
  15362. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  15363. using namespace httplib;
  15364. Server svr;
  15365. // Endpoint that returns compressible content
  15366. svr.Get("/compressible", [](const Request &, Response &res) {
  15367. // Return a large enough body to trigger compression
  15368. std::string body(1000, 'a');
  15369. res.set_content(body, "text/plain");
  15370. });
  15371. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15372. svr.wait_until_ready();
  15373. Client cli(HOST, PORT);
  15374. // Request with gzip support: should get Vary header when compressed
  15375. cli.set_compress(true);
  15376. auto res1 = cli.Get("/compressible");
  15377. ASSERT_TRUE(res1);
  15378. EXPECT_EQ(200, res1->status);
  15379. // If Content-Encoding is set, Vary should also be set
  15380. if (res1->has_header("Content-Encoding")) {
  15381. EXPECT_TRUE(res1->has_header("Vary"));
  15382. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  15383. }
  15384. // Request without Accept-Encoding header: should not have compression
  15385. Headers h_no_compress;
  15386. auto res2 = cli.Get("/compressible", h_no_compress);
  15387. ASSERT_TRUE(res2);
  15388. EXPECT_EQ(200, res2->status);
  15389. // Verify Vary header is present when compression is applied
  15390. // (the exact behavior depends on server configuration)
  15391. svr.stop();
  15392. t.join();
  15393. }
  15394. TEST(ETagTest, IfRangeWithETag) {
  15395. using namespace httplib;
  15396. // Create a test file with known content
  15397. const char *fname = "if_range_testfile.txt";
  15398. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15399. {
  15400. std::ofstream ofs(fname);
  15401. ofs << content;
  15402. ASSERT_TRUE(ofs.good());
  15403. }
  15404. Server svr;
  15405. svr.set_mount_point("/static", ".");
  15406. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15407. svr.wait_until_ready();
  15408. Client cli(HOST, PORT);
  15409. // First request: get ETag
  15410. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15411. ASSERT_TRUE(res1);
  15412. ASSERT_EQ(200, res1->status);
  15413. ASSERT_TRUE(res1->has_header("ETag"));
  15414. std::string etag = res1->get_header_value("ETag");
  15415. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15416. // Since our server generates weak ETags (W/"..."), If-Range with our
  15417. // ETag should NOT result in partial content - it should return full content.
  15418. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15419. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15420. ASSERT_TRUE(res2);
  15421. // Weak ETag in If-Range -> full content (200), not partial (206)
  15422. EXPECT_EQ(200, res2->status);
  15423. EXPECT_EQ(content, res2->body);
  15424. EXPECT_FALSE(res2->has_header("Content-Range"));
  15425. // Range request with non-matching If-Range (ETag): should get 200 (full
  15426. // content)
  15427. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15428. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15429. ASSERT_TRUE(res3);
  15430. EXPECT_EQ(200, res3->status);
  15431. EXPECT_EQ(content, res3->body);
  15432. EXPECT_FALSE(res3->has_header("Content-Range"));
  15433. // Range request with strong ETag (hypothetical - our server doesn't generate
  15434. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15435. // should return full content)
  15436. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15437. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15438. ASSERT_TRUE(res4);
  15439. EXPECT_EQ(200, res4->status);
  15440. EXPECT_EQ(content, res4->body);
  15441. EXPECT_FALSE(res4->has_header("Content-Range"));
  15442. svr.stop();
  15443. t.join();
  15444. std::remove(fname);
  15445. }
  15446. TEST(ETagTest, IfRangeWithDate) {
  15447. using namespace httplib;
  15448. // Create a test file
  15449. const char *fname = "if_range_date_testfile.txt";
  15450. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15451. {
  15452. std::ofstream ofs(fname);
  15453. ofs << content;
  15454. ASSERT_TRUE(ofs.good());
  15455. }
  15456. Server svr;
  15457. svr.set_mount_point("/static", ".");
  15458. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15459. svr.wait_until_ready();
  15460. Client cli(HOST, PORT);
  15461. // First request: get Last-Modified
  15462. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  15463. ASSERT_TRUE(res1);
  15464. ASSERT_EQ(200, res1->status);
  15465. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15466. std::string last_modified = res1->get_header_value("Last-Modified");
  15467. // Range request with matching If-Range (date): should get 206
  15468. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  15469. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  15470. ASSERT_TRUE(res2);
  15471. EXPECT_EQ(206, res2->status);
  15472. EXPECT_EQ("FGHIJ", res2->body);
  15473. // Range request with old If-Range date: should get 200 (full content)
  15474. Headers h3 = {{"Range", "bytes=5-9"},
  15475. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15476. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  15477. ASSERT_TRUE(res3);
  15478. EXPECT_EQ(200, res3->status);
  15479. EXPECT_EQ(content, res3->body);
  15480. // Range request with future If-Range date: should get 206
  15481. Headers h4 = {{"Range", "bytes=0-4"},
  15482. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15483. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  15484. ASSERT_TRUE(res4);
  15485. EXPECT_EQ(206, res4->status);
  15486. EXPECT_EQ("ABCDE", res4->body);
  15487. svr.stop();
  15488. t.join();
  15489. std::remove(fname);
  15490. }
  15491. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  15492. using namespace httplib;
  15493. const char *fname = "etag_malformed.txt";
  15494. const char *content = "malformed-etag";
  15495. {
  15496. std::ofstream ofs(fname);
  15497. ofs << content;
  15498. ASSERT_TRUE(ofs.good());
  15499. }
  15500. Server svr;
  15501. svr.set_mount_point("/static", ".");
  15502. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15503. svr.wait_until_ready();
  15504. Client cli(HOST, PORT);
  15505. // baseline: should get 200 and an ETag
  15506. auto res1 = cli.Get("/static/etag_malformed.txt");
  15507. ASSERT_TRUE(res1);
  15508. ASSERT_EQ(200, res1->status);
  15509. ASSERT_TRUE(res1->has_header("ETag"));
  15510. // Malformed ETag value (missing quotes) should be treated as non-matching
  15511. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  15512. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  15513. ASSERT_TRUE(res_bad);
  15514. EXPECT_EQ(200, res_bad->status);
  15515. // Whitespace-only header value should be considered invalid / non-matching
  15516. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  15517. "Host: localhost\r\n"
  15518. "If-None-Match: \r\n"
  15519. "Connection: close\r\n"
  15520. "\r\n";
  15521. std::string out;
  15522. ASSERT_TRUE(send_request(5, raw_req, &out));
  15523. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15524. svr.stop();
  15525. t.join();
  15526. std::remove(fname);
  15527. }
  15528. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  15529. using namespace httplib;
  15530. const char *fname = "ims_invalid_format.txt";
  15531. const char *content = "ims-bad-format";
  15532. {
  15533. std::ofstream ofs(fname);
  15534. ofs << content;
  15535. ASSERT_TRUE(ofs.good());
  15536. }
  15537. Server svr;
  15538. svr.set_mount_point("/static", ".");
  15539. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15540. svr.wait_until_ready();
  15541. Client cli(HOST, PORT);
  15542. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  15543. ASSERT_TRUE(res1);
  15544. ASSERT_EQ(200, res1->status);
  15545. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15546. // If-Modified-Since with invalid format should not result in 304
  15547. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  15548. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  15549. ASSERT_TRUE(res_bad);
  15550. EXPECT_EQ(200, res_bad->status);
  15551. // If-Range with invalid date format should be treated as mismatch -> full
  15552. // content (200)
  15553. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  15554. {"If-Range", "invalid-date"}};
  15555. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  15556. ASSERT_TRUE(res_ifrange);
  15557. EXPECT_EQ(200, res_ifrange->status);
  15558. svr.stop();
  15559. t.join();
  15560. std::remove(fname);
  15561. }
  15562. TEST(ETagTest, IfRangeWithMalformedETag) {
  15563. using namespace httplib;
  15564. const char *fname = "ifrange_malformed.txt";
  15565. const std::string content = "0123456789";
  15566. {
  15567. std::ofstream ofs(fname);
  15568. ofs << content;
  15569. ASSERT_TRUE(ofs.good());
  15570. }
  15571. Server svr;
  15572. svr.set_mount_point("/static", ".");
  15573. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15574. svr.wait_until_ready();
  15575. Client cli(HOST, PORT);
  15576. // First request: get ETag
  15577. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  15578. ASSERT_TRUE(res1);
  15579. ASSERT_EQ(200, res1->status);
  15580. ASSERT_TRUE(res1->has_header("ETag"));
  15581. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  15582. // full content (200)
  15583. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  15584. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  15585. ASSERT_TRUE(res2);
  15586. EXPECT_EQ(200, res2->status);
  15587. EXPECT_EQ(content, res2->body);
  15588. svr.stop();
  15589. t.join();
  15590. std::remove(fname);
  15591. }
  15592. TEST(ETagTest, ExtremeLargeDateValues) {
  15593. using namespace httplib;
  15594. const char *fname = "ims_extreme_date.txt";
  15595. const char *content = "ims-extreme-date";
  15596. {
  15597. std::ofstream ofs(fname);
  15598. ofs << content;
  15599. ASSERT_TRUE(ofs.good());
  15600. }
  15601. Server svr;
  15602. svr.set_mount_point("/static", ".");
  15603. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15604. svr.wait_until_ready();
  15605. Client cli(HOST, PORT);
  15606. auto res1 = cli.Get(std::string("/static/") + fname);
  15607. ASSERT_TRUE(res1);
  15608. ASSERT_EQ(200, res1->status);
  15609. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15610. // Extremely large year that may overflow date parsing routines.
  15611. Headers h_large_date = {
  15612. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15613. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  15614. ASSERT_TRUE(res_bad);
  15615. // Expect server to treat this as invalid/mismatch and return full content
  15616. EXPECT_EQ(200, res_bad->status);
  15617. // If-Range with extremely large date should be treated as mismatch -> full
  15618. // content (200)
  15619. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  15620. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15621. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  15622. ASSERT_TRUE(res_ifrange);
  15623. EXPECT_EQ(200, res_ifrange->status);
  15624. svr.stop();
  15625. t.join();
  15626. std::remove(fname);
  15627. }
  15628. TEST(ETagTest, NegativeFileModificationTime) {
  15629. using namespace httplib;
  15630. const char *fname = "ims_negative_mtime.txt";
  15631. const std::string content = "negative-mtime";
  15632. {
  15633. std::ofstream ofs(fname);
  15634. ofs << content;
  15635. ASSERT_TRUE(ofs.good());
  15636. }
  15637. // Try to set file mtime to a negative value. This may fail on some
  15638. // platforms/filesystems; if it fails, the test will still verify server
  15639. // behaves safely by performing a regular conditional request.
  15640. #if defined(__APPLE__) || defined(__linux__)
  15641. bool set_negative = false;
  15642. do {
  15643. struct timeval times[2];
  15644. // access time: now
  15645. times[0].tv_sec = time(nullptr);
  15646. times[0].tv_usec = 0;
  15647. // modification time: negative (e.g., -1)
  15648. times[1].tv_sec = -1;
  15649. times[1].tv_usec = 0;
  15650. if (utimes(fname, times) == 0) { set_negative = true; }
  15651. } while (0);
  15652. #else
  15653. bool set_negative = false;
  15654. #endif
  15655. Server svr;
  15656. svr.set_mount_point("/static", ".");
  15657. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15658. svr.wait_until_ready();
  15659. Client cli(HOST, PORT);
  15660. auto res1 = cli.Get(std::string("/static/") + fname);
  15661. ASSERT_TRUE(res1);
  15662. ASSERT_EQ(200, res1->status);
  15663. bool has_last_modified = res1->has_header("Last-Modified");
  15664. std::string last_modified;
  15665. if (has_last_modified) {
  15666. last_modified = res1->get_header_value("Last-Modified");
  15667. }
  15668. if (set_negative) {
  15669. // If we successfully set a negative mtime, ensure server returns a
  15670. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  15671. // with an old date and ensure server handles it without crash.
  15672. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  15673. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  15674. ASSERT_TRUE(res2);
  15675. // Behavior may vary; at minimum ensure server responds (200 or 304).
  15676. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  15677. } else {
  15678. // Could not set negative mtime on this platform; fall back to verifying
  15679. // that normal invalid/malformed dates are treated safely (non-304).
  15680. Headers h_bad_date = {
  15681. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15682. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  15683. ASSERT_TRUE(res_bad);
  15684. EXPECT_EQ(200, res_bad->status);
  15685. }
  15686. svr.stop();
  15687. t.join();
  15688. std::remove(fname);
  15689. }
  15690. //==============================================================================
  15691. // SSE Parsing Tests
  15692. //==============================================================================
  15693. class SSEParsingTest : public ::testing::Test {
  15694. protected:
  15695. // Test helper that mimics SSE parsing behavior
  15696. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  15697. int &retry_ms) {
  15698. // Blank line signals end of event
  15699. if (line.empty() || line == "\r") { return true; }
  15700. // Lines starting with ':' are comments (ignored)
  15701. if (!line.empty() && line[0] == ':') { return false; }
  15702. // Find the colon separator
  15703. auto colon_pos = line.find(':');
  15704. if (colon_pos == std::string::npos) {
  15705. // Line with no colon is treated as field name with empty value
  15706. return false;
  15707. }
  15708. std::string field = line.substr(0, colon_pos);
  15709. std::string value;
  15710. // Value starts after colon, skip optional single space
  15711. if (colon_pos + 1 < line.size()) {
  15712. size_t value_start = colon_pos + 1;
  15713. if (line[value_start] == ' ') { value_start++; }
  15714. value = line.substr(value_start);
  15715. // Remove trailing \r if present
  15716. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  15717. }
  15718. // Handle known fields
  15719. if (field == "event") {
  15720. msg.event = value;
  15721. } else if (field == "data") {
  15722. // Multiple data lines are concatenated with newlines
  15723. if (!msg.data.empty()) { msg.data += "\n"; }
  15724. msg.data += value;
  15725. } else if (field == "id") {
  15726. // Empty id is valid (clears the last event ID)
  15727. msg.id = value;
  15728. } else if (field == "retry") {
  15729. // Parse retry interval in milliseconds
  15730. {
  15731. int v = 0;
  15732. auto res =
  15733. detail::from_chars(value.data(), value.data() + value.size(), v);
  15734. if (res.ec == std::errc{}) { retry_ms = v; }
  15735. }
  15736. }
  15737. // Unknown fields are ignored per SSE spec
  15738. return false;
  15739. }
  15740. };
  15741. // Test: Single-line data
  15742. TEST_F(SSEParsingTest, SingleLineData) {
  15743. sse::SSEMessage msg;
  15744. int retry_ms = 3000;
  15745. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15746. EXPECT_EQ(msg.data, "hello");
  15747. EXPECT_EQ(msg.event, "message");
  15748. // Blank line ends event
  15749. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15750. }
  15751. // Test: Multi-line data
  15752. TEST_F(SSEParsingTest, MultiLineData) {
  15753. sse::SSEMessage msg;
  15754. int retry_ms = 3000;
  15755. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15756. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15757. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15758. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15759. }
  15760. // Test: Custom event types
  15761. TEST_F(SSEParsingTest, CustomEventType) {
  15762. sse::SSEMessage msg;
  15763. int retry_ms = 3000;
  15764. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15765. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15766. EXPECT_EQ(msg.event, "update");
  15767. EXPECT_EQ(msg.data, "payload");
  15768. }
  15769. // Test: Event ID handling
  15770. TEST_F(SSEParsingTest, EventIdHandling) {
  15771. sse::SSEMessage msg;
  15772. int retry_ms = 3000;
  15773. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15774. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15775. EXPECT_EQ(msg.id, "12345");
  15776. }
  15777. // Test: Empty event ID (clears last event ID)
  15778. TEST_F(SSEParsingTest, EmptyEventId) {
  15779. sse::SSEMessage msg;
  15780. msg.id = "previous";
  15781. int retry_ms = 3000;
  15782. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15783. EXPECT_EQ(msg.id, "");
  15784. }
  15785. // Test: Retry field parsing
  15786. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15787. sse::SSEMessage msg;
  15788. int retry_ms = 3000;
  15789. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15790. EXPECT_EQ(retry_ms, 5000);
  15791. }
  15792. // Test: Invalid retry value
  15793. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15794. sse::SSEMessage msg;
  15795. int retry_ms = 3000;
  15796. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15797. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15798. }
  15799. // Test: Comments (lines starting with :)
  15800. TEST_F(SSEParsingTest, CommentsIgnored) {
  15801. sse::SSEMessage msg;
  15802. int retry_ms = 3000;
  15803. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15804. EXPECT_EQ(msg.data, "");
  15805. EXPECT_EQ(msg.event, "message");
  15806. }
  15807. // Test: Colon in value
  15808. TEST_F(SSEParsingTest, ColonInValue) {
  15809. sse::SSEMessage msg;
  15810. int retry_ms = 3000;
  15811. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15812. EXPECT_EQ(msg.data, "hello:world:test");
  15813. }
  15814. // Test: Line with no colon (field name only)
  15815. TEST_F(SSEParsingTest, FieldNameOnly) {
  15816. sse::SSEMessage msg;
  15817. int retry_ms = 3000;
  15818. // According to SSE spec, this is treated as field name with empty value
  15819. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15820. // Since we don't recognize "data" without colon, data should be empty
  15821. EXPECT_EQ(msg.data, "");
  15822. }
  15823. // Test: Trailing \r handling
  15824. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15825. sse::SSEMessage msg;
  15826. int retry_ms = 3000;
  15827. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15828. EXPECT_EQ(msg.data, "hello");
  15829. }
  15830. // Test: Unknown fields ignored
  15831. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15832. sse::SSEMessage msg;
  15833. int retry_ms = 3000;
  15834. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15835. EXPECT_EQ(msg.data, "");
  15836. EXPECT_EQ(msg.event, "message");
  15837. }
  15838. // Test: Space after colon is optional
  15839. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15840. sse::SSEMessage msg1, msg2;
  15841. int retry_ms = 3000;
  15842. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15843. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15844. EXPECT_EQ(msg1.data, "hello");
  15845. EXPECT_EQ(msg2.data, "hello");
  15846. }
  15847. // Test: SSEMessage clear
  15848. TEST_F(SSEParsingTest, MessageClear) {
  15849. sse::SSEMessage msg;
  15850. msg.event = "custom";
  15851. msg.data = "some data";
  15852. msg.id = "123";
  15853. msg.clear();
  15854. EXPECT_EQ(msg.event, "message");
  15855. EXPECT_EQ(msg.data, "");
  15856. EXPECT_EQ(msg.id, "");
  15857. }
  15858. // Test: Complete event parsing
  15859. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15860. sse::SSEMessage msg;
  15861. int retry_ms = 3000;
  15862. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15863. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15864. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15865. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15866. // Blank line ends event
  15867. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15868. EXPECT_EQ(msg.event, "notification");
  15869. EXPECT_EQ(msg.id, "evt-42");
  15870. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15871. EXPECT_EQ(retry_ms, 1000);
  15872. }
  15873. //==============================================================================
  15874. // Integration Tests with Server
  15875. //==============================================================================
  15876. class SSEIntegrationTest : public ::testing::Test {
  15877. protected:
  15878. void SetUp() override {
  15879. stop_server_.store(false);
  15880. events_.clear();
  15881. server_ = httplib::detail::make_unique<Server>();
  15882. setup_server();
  15883. start_server();
  15884. }
  15885. void TearDown() override {
  15886. stop_server_.store(true);
  15887. event_cv_.notify_all();
  15888. server_->stop();
  15889. if (server_thread_.joinable()) { server_thread_.join(); }
  15890. }
  15891. void setup_server() {
  15892. // Simple SSE endpoint
  15893. server_->Get("/events", [this](const Request &req, Response &res) {
  15894. auto last_id = req.get_header_value("Last-Event-ID");
  15895. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15896. res.set_chunked_content_provider(
  15897. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15898. std::unique_lock<std::mutex> lock(event_mutex_);
  15899. if (event_cv_.wait_for(
  15900. lock, std::chrono::milliseconds(200), [this] {
  15901. return !events_.empty() || stop_server_.load();
  15902. })) {
  15903. if (stop_server_.load()) { return false; }
  15904. if (!events_.empty()) {
  15905. std::string event = events_.front();
  15906. events_.erase(events_.begin());
  15907. sink.write(event.data(), event.size());
  15908. return true;
  15909. }
  15910. }
  15911. return !stop_server_.load();
  15912. });
  15913. });
  15914. // Endpoint that returns error
  15915. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15916. res.status = 500;
  15917. res.set_content("Internal Server Error", "text/plain");
  15918. });
  15919. // Endpoint for custom event types
  15920. server_->Get("/custom-events", [](const Request &, Response &res) {
  15921. res.set_chunked_content_provider(
  15922. "text/event-stream", [](size_t offset, DataSink &sink) {
  15923. if (offset == 0) {
  15924. std::string event = "event: update\ndata: updated\n\n"
  15925. "event: delete\ndata: deleted\n\n";
  15926. sink.write(event.data(), event.size());
  15927. }
  15928. return false; // End stream after sending
  15929. });
  15930. });
  15931. }
  15932. void start_server() {
  15933. port_ = server_->bind_to_any_port(HOST);
  15934. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15935. // Wait for server to start
  15936. while (!server_->is_running()) {
  15937. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15938. }
  15939. }
  15940. int get_port() const { return port_; }
  15941. void send_event(const std::string &event) {
  15942. std::lock_guard<std::mutex> lock(event_mutex_);
  15943. events_.push_back(event);
  15944. event_cv_.notify_all();
  15945. }
  15946. std::unique_ptr<Server> server_;
  15947. std::thread server_thread_;
  15948. std::mutex event_mutex_;
  15949. std::condition_variable event_cv_;
  15950. std::vector<std::string> events_;
  15951. std::atomic<bool> stop_server_{false};
  15952. std::string last_received_event_id_;
  15953. int port_ = 0;
  15954. };
  15955. // Test: Successful connection and on_open callback
  15956. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15957. // Add a simple endpoint that sends one event and closes
  15958. server_->Get("/simple-event", [](const Request &, Response &res) {
  15959. res.set_chunked_content_provider(
  15960. "text/event-stream", [](size_t offset, DataSink &sink) {
  15961. if (offset == 0) {
  15962. std::string event = "data: hello\n\n";
  15963. sink.write(event.data(), event.size());
  15964. }
  15965. return false; // Close stream after sending
  15966. });
  15967. });
  15968. Client client("localhost", get_port());
  15969. sse::SSEClient sse(client, "/simple-event");
  15970. std::atomic<bool> open_called{false};
  15971. std::atomic<bool> message_received{false};
  15972. sse.on_open([&open_called]() { open_called.store(true); });
  15973. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15974. if (msg.data == "hello") { message_received.store(true); }
  15975. });
  15976. sse.set_reconnect_interval(100);
  15977. sse.set_max_reconnect_attempts(1);
  15978. // Start async
  15979. sse.start_async();
  15980. // Wait for message to be processed
  15981. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15982. sse.stop();
  15983. EXPECT_TRUE(open_called.load());
  15984. EXPECT_TRUE(message_received.load());
  15985. }
  15986. // Test: on_message callback
  15987. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15988. // Endpoint that sends multiple events then closes
  15989. server_->Get("/multi-event", [](const Request &, Response &res) {
  15990. res.set_chunked_content_provider(
  15991. "text/event-stream", [](size_t offset, DataSink &sink) {
  15992. if (offset == 0) {
  15993. std::string events = "data: message1\n\ndata: message2\n\n";
  15994. sink.write(events.data(), events.size());
  15995. }
  15996. return false;
  15997. });
  15998. });
  15999. Client client("localhost", get_port());
  16000. sse::SSEClient sse(client, "/multi-event");
  16001. std::vector<std::string> received_messages;
  16002. std::mutex messages_mutex;
  16003. sse.on_message([&](const sse::SSEMessage &msg) {
  16004. std::lock_guard<std::mutex> lock(messages_mutex);
  16005. received_messages.push_back(msg.data);
  16006. });
  16007. sse.set_reconnect_interval(100);
  16008. sse.set_max_reconnect_attempts(1);
  16009. sse.start_async();
  16010. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16011. sse.stop();
  16012. std::lock_guard<std::mutex> lock(messages_mutex);
  16013. EXPECT_GE(received_messages.size(), 2u);
  16014. if (received_messages.size() >= 2) {
  16015. EXPECT_EQ(received_messages[0], "message1");
  16016. EXPECT_EQ(received_messages[1], "message2");
  16017. }
  16018. }
  16019. // Test: on_event for specific types
  16020. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  16021. Client client("localhost", get_port());
  16022. sse::SSEClient sse(client, "/custom-events");
  16023. std::atomic<bool> update_received{false};
  16024. std::atomic<bool> delete_received{false};
  16025. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  16026. if (msg.data == "updated") { update_received.store(true); }
  16027. });
  16028. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  16029. if (msg.data == "deleted") { delete_received.store(true); }
  16030. });
  16031. sse.set_max_reconnect_attempts(1);
  16032. sse.start_async();
  16033. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  16034. sse.stop();
  16035. EXPECT_TRUE(update_received.load());
  16036. EXPECT_TRUE(delete_received.load());
  16037. }
  16038. // Test: on_error callback on connection failure
  16039. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  16040. // Connect to a non-existent port
  16041. Client client("localhost", 59999);
  16042. sse::SSEClient sse(client, "/events");
  16043. std::atomic<bool> error_called{false};
  16044. Error received_error = Error::Success;
  16045. sse.on_error([&](Error err) {
  16046. error_called.store(true);
  16047. received_error = err;
  16048. });
  16049. sse.set_reconnect_interval(50);
  16050. sse.set_max_reconnect_attempts(1);
  16051. sse.start_async();
  16052. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16053. sse.stop();
  16054. EXPECT_TRUE(error_called.load());
  16055. EXPECT_NE(received_error, Error::Success);
  16056. }
  16057. // Test: Last-Event-ID header sent on reconnect
  16058. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  16059. // Endpoint that sends event with ID
  16060. server_->Get("/event-with-id", [](const Request &, Response &res) {
  16061. res.set_chunked_content_provider(
  16062. "text/event-stream", [](size_t offset, DataSink &sink) {
  16063. if (offset == 0) {
  16064. std::string event = "id: evt-123\ndata: test\n\n";
  16065. sink.write(event.data(), event.size());
  16066. }
  16067. return false;
  16068. });
  16069. });
  16070. Client client("localhost", get_port());
  16071. sse::SSEClient sse(client, "/event-with-id");
  16072. std::atomic<bool> id_received{false};
  16073. sse.on_message([&](const sse::SSEMessage &msg) {
  16074. if (!msg.id.empty()) { id_received.store(true); }
  16075. });
  16076. sse.set_reconnect_interval(100);
  16077. sse.set_max_reconnect_attempts(1);
  16078. sse.start_async();
  16079. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16080. sse.stop();
  16081. EXPECT_TRUE(id_received.load());
  16082. EXPECT_EQ(sse.last_event_id(), "evt-123");
  16083. }
  16084. // Test: Manual stop
  16085. TEST_F(SSEIntegrationTest, ManualStop) {
  16086. // Endpoint that sends one event and stays open briefly
  16087. std::atomic<bool> handler_running{true};
  16088. server_->Get("/stay-open", [&handler_running](const Request &,
  16089. Response &res) {
  16090. res.set_chunked_content_provider(
  16091. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  16092. if (offset == 0) {
  16093. std::string event = "data: connected\n\n";
  16094. sink.write(event.data(), event.size());
  16095. }
  16096. // Keep connection open while handler_running is true
  16097. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  16098. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16099. }
  16100. return false;
  16101. });
  16102. });
  16103. Client client("localhost", get_port());
  16104. sse::SSEClient sse(client, "/stay-open");
  16105. std::atomic<bool> connected{false};
  16106. sse.on_open([&connected]() { connected.store(true); });
  16107. sse.set_reconnect_interval(100);
  16108. sse.set_max_reconnect_attempts(1);
  16109. sse.start_async();
  16110. // Wait for connection to establish
  16111. for (int i = 0; i < 20 && !connected.load(); ++i) {
  16112. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  16113. }
  16114. EXPECT_TRUE(connected.load());
  16115. EXPECT_TRUE(sse.is_connected());
  16116. // Signal handler to stop
  16117. handler_running.store(false);
  16118. // Stop SSE client
  16119. sse.stop();
  16120. EXPECT_FALSE(sse.is_connected());
  16121. }
  16122. // Test: SSEClient with custom headers
  16123. TEST_F(SSEIntegrationTest, CustomHeaders) {
  16124. // Setup a server endpoint that checks for custom header
  16125. std::atomic<bool> header_received{false};
  16126. server_->Get("/header-check", [&](const Request &req, Response &res) {
  16127. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  16128. header_received.store(true);
  16129. }
  16130. res.set_chunked_content_provider("text/event-stream",
  16131. [](size_t, DataSink &) { return false; });
  16132. });
  16133. Client client("localhost", get_port());
  16134. Headers headers = {{"X-Custom-Header", "custom-value"}};
  16135. sse::SSEClient sse(client, "/header-check", headers);
  16136. sse.set_max_reconnect_attempts(1);
  16137. sse.start_async();
  16138. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16139. sse.stop();
  16140. EXPECT_TRUE(header_received.load());
  16141. }
  16142. // Test: Reconnect interval configuration
  16143. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  16144. Client client("localhost", get_port());
  16145. sse::SSEClient sse(client, "/events");
  16146. auto &result = sse.set_reconnect_interval(500);
  16147. // Builder pattern should return reference to self
  16148. EXPECT_EQ(&result, &sse);
  16149. }
  16150. // Test: Max reconnect attempts
  16151. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  16152. // Connect to non-existent port to force reconnects
  16153. Client client("localhost", 59998);
  16154. sse::SSEClient sse(client, "/events");
  16155. std::atomic<int> error_count{0};
  16156. sse.on_error([&](Error) { error_count.fetch_add(1); });
  16157. sse.set_reconnect_interval(50);
  16158. sse.set_max_reconnect_attempts(2);
  16159. auto start = std::chrono::steady_clock::now();
  16160. sse.start(); // Blocking call
  16161. auto end = std::chrono::steady_clock::now();
  16162. // Should have stopped after 2 failed attempts
  16163. EXPECT_GE(error_count.load(), 2);
  16164. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  16165. auto duration =
  16166. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  16167. #ifdef _WIN32
  16168. // Windows is much slower for socket connection failures
  16169. EXPECT_LT(duration.count(), 7000);
  16170. #else
  16171. EXPECT_LT(duration.count(), 1000);
  16172. #endif
  16173. }
  16174. // Test: Multi-line data in integration
  16175. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  16176. // Endpoint with multi-line data
  16177. server_->Get("/multiline-data", [](const Request &, Response &res) {
  16178. res.set_chunked_content_provider(
  16179. "text/event-stream", [](size_t offset, DataSink &sink) {
  16180. if (offset == 0) {
  16181. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  16182. sink.write(event.data(), event.size());
  16183. }
  16184. return false;
  16185. });
  16186. });
  16187. Client client("localhost", get_port());
  16188. sse::SSEClient sse(client, "/multiline-data");
  16189. std::string received_data;
  16190. std::mutex data_mutex;
  16191. sse.on_message([&](const sse::SSEMessage &msg) {
  16192. std::lock_guard<std::mutex> lock(data_mutex);
  16193. received_data = msg.data;
  16194. });
  16195. sse.set_reconnect_interval(100);
  16196. sse.set_max_reconnect_attempts(1);
  16197. sse.start_async();
  16198. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16199. sse.stop();
  16200. std::lock_guard<std::mutex> lock(data_mutex);
  16201. EXPECT_EQ(received_data, "line1\nline2\nline3");
  16202. }
  16203. // Test: Auto-reconnect after server disconnection
  16204. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  16205. std::atomic<int> connection_count{0};
  16206. std::atomic<int> message_count{0};
  16207. // Endpoint that sends one event and closes, forcing reconnect
  16208. server_->Get("/reconnect-test",
  16209. [&connection_count](const Request &, Response &res) {
  16210. connection_count.fetch_add(1);
  16211. res.set_chunked_content_provider(
  16212. "text/event-stream", [](size_t offset, DataSink &sink) {
  16213. if (offset == 0) {
  16214. std::string event = "data: hello\n\n";
  16215. sink.write(event.data(), event.size());
  16216. }
  16217. return false; // Close connection after sending
  16218. });
  16219. });
  16220. Client client("localhost", get_port());
  16221. sse::SSEClient sse(client, "/reconnect-test");
  16222. sse.on_message([&message_count](const sse::SSEMessage &) {
  16223. message_count.fetch_add(1);
  16224. });
  16225. sse.set_reconnect_interval(100);
  16226. sse.set_max_reconnect_attempts(3);
  16227. sse.start_async();
  16228. // Wait long enough for multiple reconnects
  16229. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16230. sse.stop();
  16231. // Should have connected multiple times (initial + reconnects)
  16232. EXPECT_GE(connection_count.load(), 2);
  16233. // Should have received messages from multiple connections
  16234. EXPECT_GE(message_count.load(), 2);
  16235. }
  16236. // Test: Last-Event-ID sent on reconnect
  16237. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  16238. std::atomic<int> connection_count{0};
  16239. std::vector<std::string> received_last_event_ids;
  16240. std::mutex id_mutex;
  16241. // Endpoint that checks Last-Event-ID header and sends event with ID
  16242. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  16243. int conn = connection_count.fetch_add(1);
  16244. // Capture the Last-Event-ID header from each connection
  16245. {
  16246. std::lock_guard<std::mutex> lock(id_mutex);
  16247. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  16248. }
  16249. res.set_chunked_content_provider(
  16250. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  16251. if (offset == 0) {
  16252. std::string event =
  16253. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  16254. sink.write(event.data(), event.size());
  16255. }
  16256. return false;
  16257. });
  16258. });
  16259. Client client("localhost", get_port());
  16260. sse::SSEClient sse(client, "/reconnect-with-id");
  16261. sse.set_reconnect_interval(100);
  16262. sse.set_max_reconnect_attempts(3);
  16263. sse.start_async();
  16264. // Wait for at least 2 connections
  16265. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16266. sse.stop();
  16267. // Verify behavior
  16268. std::lock_guard<std::mutex> lock(id_mutex);
  16269. EXPECT_GE(received_last_event_ids.size(), 2u);
  16270. // First connection should have no Last-Event-ID
  16271. if (!received_last_event_ids.empty()) {
  16272. EXPECT_EQ(received_last_event_ids[0], "");
  16273. }
  16274. // Second connection should have Last-Event-ID from first connection
  16275. if (received_last_event_ids.size() >= 2) {
  16276. EXPECT_EQ(received_last_event_ids[1], "event-0");
  16277. }
  16278. }
  16279. // Test: set_headers updates headers used on reconnect
  16280. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  16281. std::vector<std::string> received_tokens;
  16282. std::mutex token_mutex;
  16283. // Endpoint that captures Authorization header
  16284. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  16285. {
  16286. std::lock_guard<std::mutex> lock(token_mutex);
  16287. received_tokens.push_back(req.get_header_value("Authorization"));
  16288. }
  16289. res.set_chunked_content_provider(
  16290. "text/event-stream", [](size_t offset, DataSink &sink) {
  16291. if (offset == 0) {
  16292. std::string event = "data: hello\n\n";
  16293. sink.write(event.data(), event.size());
  16294. }
  16295. return false; // Close connection to trigger reconnect
  16296. });
  16297. });
  16298. Client client("localhost", get_port());
  16299. Headers headers = {{"Authorization", "Bearer old-token"}};
  16300. sse::SSEClient sse(client, "/auth-check", headers);
  16301. // Update headers on each successful connection
  16302. sse.on_open(
  16303. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  16304. sse.set_reconnect_interval(100);
  16305. sse.set_max_reconnect_attempts(3);
  16306. sse.start_async();
  16307. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16308. sse.stop();
  16309. std::lock_guard<std::mutex> lock(token_mutex);
  16310. ASSERT_GE(received_tokens.size(), 2u);
  16311. // First connection uses original header
  16312. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  16313. // Second connection uses updated header from set_headers
  16314. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  16315. }
  16316. // Test: 401 allows reconnection (so on_error can refresh headers)
  16317. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  16318. std::atomic<int> connection_count{0};
  16319. // Endpoint: returns 401 on first attempt, 200 on second
  16320. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  16321. int conn = connection_count.fetch_add(1);
  16322. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  16323. res.status = StatusCode::Unauthorized_401;
  16324. res.set_content("Unauthorized", "text/plain");
  16325. return;
  16326. }
  16327. res.set_chunked_content_provider(
  16328. "text/event-stream", [](size_t offset, DataSink &sink) {
  16329. if (offset == 0) {
  16330. std::string event = "data: authenticated\n\n";
  16331. sink.write(event.data(), event.size());
  16332. }
  16333. return false;
  16334. });
  16335. });
  16336. Client client("localhost", get_port());
  16337. Headers headers = {{"Authorization", "Bearer expired"}};
  16338. sse::SSEClient sse(client, "/auth-retry", headers);
  16339. std::atomic<bool> message_received{false};
  16340. // Refresh token on error
  16341. sse.on_error(
  16342. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  16343. sse.on_message([&](const sse::SSEMessage &msg) {
  16344. if (msg.data == "authenticated") { message_received.store(true); }
  16345. });
  16346. sse.set_reconnect_interval(100);
  16347. sse.set_max_reconnect_attempts(3);
  16348. sse.start_async();
  16349. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16350. sse.stop();
  16351. // Should have reconnected after 401 and succeeded with new token
  16352. EXPECT_GE(connection_count.load(), 2);
  16353. EXPECT_TRUE(message_received.load());
  16354. }
  16355. TEST(Issue2318Test, EmptyHostString) {
  16356. {
  16357. httplib::Client cli_empty("", PORT);
  16358. auto res = cli_empty.Get("/");
  16359. ASSERT_FALSE(res);
  16360. EXPECT_EQ(httplib::Error::Connection, res.error());
  16361. }
  16362. {
  16363. httplib::Client cli(" ", PORT);
  16364. auto res = cli.Get("/");
  16365. ASSERT_FALSE(res);
  16366. EXPECT_EQ(httplib::Error::Connection, res.error());
  16367. }
  16368. }
  16369. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16370. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  16371. Server svr;
  16372. // Set a small payload limit (1KB)
  16373. svr.set_payload_max_length(1024);
  16374. svr.Post("/test", [&](const Request &req, Response &res) {
  16375. res.set_content("Body size: " + std::to_string(req.body.size()),
  16376. "text/plain");
  16377. });
  16378. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16379. auto se = detail::scope_exit([&] {
  16380. svr.stop();
  16381. listen_thread.join();
  16382. });
  16383. svr.wait_until_ready();
  16384. // Create data that compresses well but exceeds limit when decompressed
  16385. // 8KB of repeated null bytes compresses to a very small size
  16386. std::string original_data(8 * 1024, '\0');
  16387. // Compress the data using gzip
  16388. std::string compressed_data;
  16389. detail::gzip_compressor compressor;
  16390. compressor.compress(original_data.data(), original_data.size(), true,
  16391. [&](const char *data, size_t size) {
  16392. compressed_data.append(data, size);
  16393. return true;
  16394. });
  16395. // Verify compression worked (compressed should be much smaller)
  16396. ASSERT_LT(compressed_data.size(), original_data.size());
  16397. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16398. // Send compressed data with Content-Encoding: gzip
  16399. Client cli(HOST, PORT);
  16400. Headers headers = {{"Content-Encoding", "gzip"}};
  16401. auto res =
  16402. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16403. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16405. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16406. }
  16407. #endif
  16408. // ============================================================================
  16409. // OpenSSL-Specific Tests
  16410. // ============================================================================
  16411. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16412. X509 *readCertificate(const std::string &strFileName) {
  16413. std::ifstream inStream(strFileName);
  16414. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16415. std::istreambuf_iterator<char>());
  16416. if (strCertPEM.empty()) return (nullptr);
  16417. BIO *pbCert = BIO_new(BIO_s_mem());
  16418. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16419. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16420. BIO_free(pbCert);
  16421. return (pCert);
  16422. }
  16423. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16424. std::ifstream inStream(strFileName);
  16425. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16426. std::istreambuf_iterator<char>());
  16427. if (strPrivateKeyPEM.empty()) return (nullptr);
  16428. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16429. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16430. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16431. BIO_free(pbPrivKey);
  16432. return (pPrivateKey);
  16433. }
  16434. TEST(BindServerTest, UpdateCerts) {
  16435. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16436. int port = svr.bind_to_any_port("0.0.0.0");
  16437. ASSERT_TRUE(svr.is_valid());
  16438. ASSERT_TRUE(port > 0);
  16439. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16440. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16441. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16442. ASSERT_TRUE(cert != nullptr);
  16443. ASSERT_TRUE(ca_cert != nullptr);
  16444. ASSERT_TRUE(key != nullptr);
  16445. X509_STORE *cert_store = X509_STORE_new();
  16446. X509_STORE_add_cert(cert_store, ca_cert);
  16447. // svr.update_certs(cert, key, cert_store); // deprecated
  16448. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16449. CLIENT_CA_CERT_FILE);
  16450. ASSERT_TRUE(svr.is_valid());
  16451. svr.stop();
  16452. X509_STORE_free(cert_store);
  16453. X509_free(cert);
  16454. X509_free(ca_cert);
  16455. EVP_PKEY_free(key);
  16456. }
  16457. // Test that update_certs() updates client CA list correctly
  16458. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  16459. // Start with file-based constructor
  16460. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16461. ASSERT_TRUE(svr.is_valid());
  16462. // Initially no client CA list should be set
  16463. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16464. ASSERT_TRUE(ssl_ctx != nullptr);
  16465. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  16466. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  16467. EXPECT_EQ(0, count_before);
  16468. // Now update with client CA (PEM string)
  16469. std::string cert_pem, key_pem, ca_pem;
  16470. read_file(SERVER_CERT_FILE, cert_pem);
  16471. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  16472. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  16473. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  16474. ASSERT_TRUE(svr.is_valid());
  16475. // Now client CA list should be set
  16476. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  16477. ASSERT_TRUE(ca_list_after != nullptr);
  16478. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  16479. }
  16480. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  16481. // Test that the file-path SSLServer constructor properly sets the client CA
  16482. // list that is sent to clients during the TLS handshake (CertificateRequest)
  16483. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16484. ASSERT_TRUE(svr.is_valid());
  16485. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16486. ASSERT_TRUE(ssl_ctx != nullptr);
  16487. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  16488. ASSERT_TRUE(ca_list != nullptr);
  16489. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  16490. }
  16491. #endif
  16492. // ============================================================================
  16493. // MbedTLS-Specific Tests
  16494. // ============================================================================
  16495. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16496. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  16497. using namespace httplib::tls;
  16498. // Track if callback was invoked
  16499. bool callback_invoked = false;
  16500. // The callback receives void* ctx which is actually MbedTlsContext*
  16501. // We can access the mbedtls_ssl_config via the context
  16502. auto setup_callback = [&callback_invoked](void *ctx) {
  16503. callback_invoked = true;
  16504. // Cast to MbedTlsContext* to access the ssl config
  16505. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  16506. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  16507. // Use static variables to hold certificate data (simplified for test)
  16508. static mbedtls_x509_crt own_cert;
  16509. static mbedtls_pk_context own_key;
  16510. static mbedtls_x509_crt ca_chain;
  16511. static bool initialized = false;
  16512. if (!initialized) {
  16513. mbedtls_x509_crt_init(&own_cert);
  16514. mbedtls_pk_init(&own_key);
  16515. mbedtls_x509_crt_init(&ca_chain);
  16516. // Load server certificate
  16517. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  16518. return false;
  16519. }
  16520. // Load server private key.
  16521. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  16522. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  16523. #if MBEDTLS_VERSION_MAJOR == 3
  16524. ,
  16525. mbedtls_ctr_drbg_random, nullptr
  16526. #endif
  16527. ) != 0) {
  16528. return false;
  16529. }
  16530. // Load CA chain for client verification
  16531. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  16532. return false;
  16533. }
  16534. initialized = true;
  16535. }
  16536. // Configure the SSL config
  16537. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  16538. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  16539. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16540. // Set minimum TLS version using mbedTLS native API
  16541. #if MBEDTLS_VERSION_MAJOR >= 3
  16542. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16543. #else
  16544. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16545. MBEDTLS_SSL_MINOR_VERSION_3);
  16546. #endif
  16547. return true;
  16548. };
  16549. SSLServer svr(setup_callback);
  16550. ASSERT_TRUE(svr.is_valid());
  16551. ASSERT_TRUE(callback_invoked);
  16552. svr.Get("/test", [&](const Request &req, Response &res) {
  16553. res.set_content("test", "text/plain");
  16554. auto cert = req.peer_cert();
  16555. ASSERT_TRUE(static_cast<bool>(cert));
  16556. auto common_name = cert.subject_cn();
  16557. EXPECT_EQ("Common Name", common_name);
  16558. });
  16559. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16560. auto se = detail::scope_exit([&] {
  16561. svr.stop();
  16562. t.join();
  16563. ASSERT_FALSE(svr.is_running());
  16564. });
  16565. svr.wait_until_ready();
  16566. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16567. cli.enable_server_certificate_verification(false);
  16568. cli.set_connection_timeout(30);
  16569. auto res = cli.Get("/test");
  16570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16571. ASSERT_EQ(StatusCode::OK_200, res->status);
  16572. }
  16573. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  16574. // context (owning mbedtls_ssl_config) before shutting down a still-open
  16575. // keep-alive SSL session, which reads through that config in
  16576. // mbedtls_ssl_close_notify.
  16577. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  16578. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16579. ASSERT_TRUE(svr.is_valid());
  16580. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16581. res.set_content("test", "text/plain");
  16582. });
  16583. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16584. auto se = detail::scope_exit([&] {
  16585. svr.stop();
  16586. t.join();
  16587. ASSERT_FALSE(svr.is_running());
  16588. });
  16589. svr.wait_until_ready();
  16590. {
  16591. SSLClient cli(HOST, PORT);
  16592. cli.enable_server_certificate_verification(false);
  16593. cli.set_keep_alive(true);
  16594. auto res = cli.Get("/test");
  16595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16596. ASSERT_EQ(StatusCode::OK_200, res->status);
  16597. // cli is destructed here with the keep-alive SSL session still open.
  16598. }
  16599. }
  16600. #endif
  16601. // WebSocket Tests
  16602. TEST(WebSocketTest, RSVBitsMustBeZero) {
  16603. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  16604. // defining the meaning of these bits has been negotiated.
  16605. auto make_frame = [](uint8_t first_byte) {
  16606. std::string frame;
  16607. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  16608. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  16609. frame += "Hello";
  16610. return frame;
  16611. };
  16612. // RSV1 set (0x40)
  16613. {
  16614. detail::BufferStream strm;
  16615. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  16616. ws::Opcode opcode;
  16617. std::string payload;
  16618. bool fin;
  16619. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16620. false, 1024));
  16621. }
  16622. // RSV2 set (0x20)
  16623. {
  16624. detail::BufferStream strm;
  16625. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  16626. ws::Opcode opcode;
  16627. std::string payload;
  16628. bool fin;
  16629. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16630. false, 1024));
  16631. }
  16632. // RSV3 set (0x10)
  16633. {
  16634. detail::BufferStream strm;
  16635. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  16636. ws::Opcode opcode;
  16637. std::string payload;
  16638. bool fin;
  16639. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16640. false, 1024));
  16641. }
  16642. // No RSV bits set - should succeed
  16643. {
  16644. detail::BufferStream strm;
  16645. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  16646. ws::Opcode opcode;
  16647. std::string payload;
  16648. bool fin;
  16649. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16650. false, 1024));
  16651. EXPECT_EQ(ws::Opcode::Text, opcode);
  16652. EXPECT_EQ("Hello", payload);
  16653. EXPECT_TRUE(fin);
  16654. }
  16655. }
  16656. TEST(WebSocketTest, ControlFrameValidation) {
  16657. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  16658. // payload length <= 125.
  16659. // Ping with FIN=0 - must be rejected
  16660. {
  16661. detail::BufferStream strm;
  16662. std::string frame;
  16663. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  16664. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16665. strm.write(frame.data(), frame.size());
  16666. ws::Opcode opcode;
  16667. std::string payload;
  16668. bool fin;
  16669. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16670. false, 1024));
  16671. }
  16672. // Close with FIN=0 - must be rejected
  16673. {
  16674. detail::BufferStream strm;
  16675. std::string frame;
  16676. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  16677. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16678. strm.write(frame.data(), frame.size());
  16679. ws::Opcode opcode;
  16680. std::string payload;
  16681. bool fin;
  16682. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16683. false, 1024));
  16684. }
  16685. // Ping with payload_len=126 (extended length) - must be rejected
  16686. {
  16687. detail::BufferStream strm;
  16688. std::string frame;
  16689. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16690. frame += static_cast<char>(126); // payload_len=126 (>125)
  16691. frame += static_cast<char>(0x00); // extended length high byte
  16692. frame += static_cast<char>(126); // extended length low byte
  16693. frame += std::string(126, 'x');
  16694. strm.write(frame.data(), frame.size());
  16695. ws::Opcode opcode;
  16696. std::string payload;
  16697. bool fin;
  16698. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16699. false, 1024));
  16700. }
  16701. // Ping with FIN=1 and payload_len=125 - should succeed
  16702. {
  16703. detail::BufferStream strm;
  16704. std::string frame;
  16705. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16706. frame += static_cast<char>(125); // payload_len=125
  16707. frame += std::string(125, 'x');
  16708. strm.write(frame.data(), frame.size());
  16709. ws::Opcode opcode;
  16710. std::string payload;
  16711. bool fin;
  16712. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16713. false, 1024));
  16714. EXPECT_EQ(ws::Opcode::Ping, opcode);
  16715. EXPECT_EQ(125u, payload.size());
  16716. EXPECT_TRUE(fin);
  16717. }
  16718. }
  16719. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  16720. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  16721. // length MUST be 0.
  16722. // MSB set - must be rejected
  16723. {
  16724. detail::BufferStream strm;
  16725. std::string frame;
  16726. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16727. frame += static_cast<char>(127); // 64-bit extended length
  16728. frame += static_cast<char>(0x80); // MSB set (invalid)
  16729. frame += std::string(7, '\0'); // remaining 7 bytes of length
  16730. strm.write(frame.data(), frame.size());
  16731. ws::Opcode opcode;
  16732. std::string payload;
  16733. bool fin;
  16734. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16735. false, 1024));
  16736. }
  16737. // MSB clear - should pass length parsing (will be rejected by max_len,
  16738. // but that's a different check; use a small length to verify)
  16739. {
  16740. detail::BufferStream strm;
  16741. std::string frame;
  16742. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16743. frame += static_cast<char>(127); // 64-bit extended length
  16744. frame += std::string(7, '\0'); // high bytes = 0
  16745. frame += static_cast<char>(0x03); // length = 3
  16746. frame += "abc";
  16747. strm.write(frame.data(), frame.size());
  16748. ws::Opcode opcode;
  16749. std::string payload;
  16750. bool fin;
  16751. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16752. false, 1024));
  16753. EXPECT_EQ(ws::Opcode::Text, opcode);
  16754. EXPECT_EQ("abc", payload);
  16755. }
  16756. }
  16757. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16758. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16759. // Valid UTF-8
  16760. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16761. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16762. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16763. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16764. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16765. // Invalid UTF-8
  16766. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16767. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16768. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16769. EXPECT_FALSE(
  16770. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16771. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16772. }
  16773. TEST(WebSocketTest, ConnectAndDisconnect) {
  16774. Server svr;
  16775. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16776. std::string msg;
  16777. while (ws.read(msg)) {}
  16778. });
  16779. auto port = svr.bind_to_any_port(HOST);
  16780. std::thread t([&]() { svr.listen_after_bind(); });
  16781. svr.wait_until_ready();
  16782. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16783. auto res = client.connect();
  16784. ASSERT_TRUE(res);
  16785. EXPECT_EQ(Error::Success, res.error());
  16786. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  16787. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  16788. EXPECT_TRUE(client.is_open());
  16789. client.close();
  16790. EXPECT_FALSE(client.is_open());
  16791. svr.stop();
  16792. t.join();
  16793. }
  16794. TEST(WebSocketTest, ValidURL) {
  16795. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16796. EXPECT_TRUE(ws1.is_valid());
  16797. ws::WebSocketClient ws2("ws://example.com/path");
  16798. EXPECT_TRUE(ws2.is_valid());
  16799. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16800. EXPECT_TRUE(ws3.is_valid());
  16801. #ifdef CPPHTTPLIB_SSL_ENABLED
  16802. ws::WebSocketClient wss1("wss://example.com/path");
  16803. EXPECT_TRUE(wss1.is_valid());
  16804. ws::WebSocketClient wss2("wss://example.com:443/path");
  16805. EXPECT_TRUE(wss2.is_valid());
  16806. #endif
  16807. }
  16808. TEST(WebSocketTest, InvalidURL) {
  16809. // No scheme
  16810. ws::WebSocketClient ws1("localhost:8080/path");
  16811. EXPECT_FALSE(ws1.is_valid());
  16812. // No path
  16813. ws::WebSocketClient ws2("ws://localhost:8080");
  16814. EXPECT_FALSE(ws2.is_valid());
  16815. // Empty string
  16816. ws::WebSocketClient ws3("");
  16817. EXPECT_FALSE(ws3.is_valid());
  16818. // Missing host
  16819. ws::WebSocketClient ws4("ws://:8080/path");
  16820. EXPECT_FALSE(ws4.is_valid());
  16821. // Port number overflow — should not crash
  16822. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16823. EXPECT_FALSE(ws5.is_valid());
  16824. // Port out of range
  16825. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16826. EXPECT_FALSE(ws6.is_valid());
  16827. }
  16828. TEST(WebSocketTest, UnsupportedScheme) {
  16829. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16830. ws::WebSocketClient ws1("http://localhost:8080/path");
  16831. EXPECT_FALSE(ws1.is_valid());
  16832. ws::WebSocketClient ws2("https://localhost:8080/path");
  16833. EXPECT_FALSE(ws2.is_valid());
  16834. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16835. EXPECT_FALSE(ws3.is_valid());
  16836. #else
  16837. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16838. std::invalid_argument);
  16839. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16840. std::invalid_argument);
  16841. #endif
  16842. }
  16843. TEST(WebSocketTest, ConnectWhenInvalid) {
  16844. ws::WebSocketClient ws("not a valid url");
  16845. EXPECT_FALSE(ws.is_valid());
  16846. auto res = ws.connect();
  16847. EXPECT_FALSE(res);
  16848. EXPECT_EQ(Error::Connection, res.error());
  16849. EXPECT_EQ(-1, res.status());
  16850. }
  16851. TEST(WebSocketTest, ConnectRefusedReportsError) {
  16852. // Grab a port that is free, then close it again so nothing listens there
  16853. Server svr;
  16854. auto port = svr.bind_to_any_port(HOST);
  16855. svr.stop();
  16856. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16857. auto res = client.connect();
  16858. ASSERT_FALSE(res);
  16859. EXPECT_EQ(Error::Connection, res.error());
  16860. EXPECT_EQ(-1, res.status());
  16861. }
  16862. TEST(WebSocketTest, DefaultPort) {
  16863. ws::WebSocketClient ws1("ws://example.com/path");
  16864. EXPECT_TRUE(ws1.is_valid());
  16865. // ws:// defaults to port 80 (verified by successful parse)
  16866. #ifdef CPPHTTPLIB_SSL_ENABLED
  16867. ws::WebSocketClient ws2("wss://example.com/path");
  16868. EXPECT_TRUE(ws2.is_valid());
  16869. // wss:// defaults to port 443 (verified by successful parse)
  16870. #endif
  16871. }
  16872. TEST(WebSocketTest, IPv6LiteralAddress) {
  16873. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16874. EXPECT_TRUE(ws1.is_valid());
  16875. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16876. EXPECT_TRUE(ws2.is_valid());
  16877. }
  16878. TEST(WebSocketTest, ComplexPath) {
  16879. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16880. EXPECT_TRUE(ws1.is_valid());
  16881. ws::WebSocketClient ws2("ws://localhost:8080/");
  16882. EXPECT_TRUE(ws2.is_valid());
  16883. }
  16884. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16885. Server svr;
  16886. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16887. std::string msg;
  16888. while (ws.read(msg)) {}
  16889. });
  16890. auto port = svr.bind_to_any_port(HOST);
  16891. std::thread t([&]() { svr.listen_after_bind(); });
  16892. svr.wait_until_ready();
  16893. auto another_host = "example.com";
  16894. auto wrong_ip = "192.0.2.1";
  16895. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16896. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16897. ASSERT_TRUE(client.connect());
  16898. EXPECT_TRUE(client.is_open());
  16899. client.close();
  16900. svr.stop();
  16901. t.join();
  16902. }
  16903. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16904. Server svr;
  16905. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16906. std::string msg;
  16907. while (ws.read(msg)) {}
  16908. });
  16909. auto port = svr.bind_to_any_port(HOST);
  16910. std::thread t([&]() { svr.listen_after_bind(); });
  16911. svr.wait_until_ready();
  16912. auto wrong_ip = "192.0.2.1";
  16913. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16914. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16915. client.set_connection_timeout(1);
  16916. client.set_read_timeout(1);
  16917. client.set_write_timeout(1);
  16918. EXPECT_FALSE(client.connect());
  16919. EXPECT_FALSE(client.is_open());
  16920. svr.stop();
  16921. t.join();
  16922. }
  16923. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16924. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16925. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16926. // (RFC 6761) is only a map key and the Host header value.
  16927. auto host = "target.invalid";
  16928. Server svr;
  16929. std::string received_host;
  16930. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16931. received_host = req.get_header_value("Host");
  16932. std::string msg;
  16933. while (ws.read(msg)) {}
  16934. });
  16935. auto port = svr.bind_to_any_port(HOST);
  16936. std::thread t([&]() { svr.listen_after_bind(); });
  16937. // ASSERT_* below returns from the test body, which would leave t joinable
  16938. // and make ~thread call std::terminate.
  16939. auto se = detail::scope_exit([&] {
  16940. svr.stop();
  16941. if (t.joinable()) { t.join(); }
  16942. });
  16943. svr.wait_until_ready();
  16944. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16945. std::to_string(port) + "/ws");
  16946. client.set_hostname_addr_map({{host, HOST}});
  16947. ASSERT_TRUE(client.connect());
  16948. EXPECT_TRUE(client.is_open());
  16949. client.close();
  16950. svr.stop();
  16951. t.join();
  16952. // The mapping only redirects the connection; the identity stays host_.
  16953. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16954. }
  16955. class WebSocketIntegrationTest : public ::testing::Test {
  16956. protected:
  16957. void SetUp() override {
  16958. server_ = httplib::detail::make_unique<Server>();
  16959. setup_server();
  16960. start_server();
  16961. }
  16962. void TearDown() override {
  16963. server_->stop();
  16964. if (server_thread_.joinable()) { server_thread_.join(); }
  16965. }
  16966. void setup_server() {
  16967. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16968. std::string msg;
  16969. ws::ReadResult ret;
  16970. while ((ret = ws.read(msg))) {
  16971. if (ret == ws::Binary) {
  16972. ws.send(msg.data(), msg.size());
  16973. } else {
  16974. ws.send(msg);
  16975. }
  16976. }
  16977. });
  16978. server_->WebSocket("/ws-echo-string",
  16979. [](const Request &, ws::WebSocket &ws) {
  16980. std::string msg;
  16981. while (ws.read(msg)) {
  16982. ws.send("echo: " + msg);
  16983. }
  16984. });
  16985. server_->WebSocket(
  16986. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16987. // Echo back request metadata
  16988. ws.send("path:" + req.path);
  16989. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16990. std::string msg;
  16991. while (ws.read(msg)) {}
  16992. });
  16993. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16994. std::string msg;
  16995. ws.read(msg); // wait for a message
  16996. ws.close();
  16997. });
  16998. server_->WebSocket("/ws-close-status",
  16999. [](const Request &, ws::WebSocket &ws) {
  17000. std::string msg;
  17001. ws.read(msg); // wait for a message
  17002. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  17003. });
  17004. server_->WebSocket(
  17005. "/ws-subprotocol",
  17006. [](const Request &, ws::WebSocket &ws) {
  17007. std::string msg;
  17008. while (ws.read(msg)) {
  17009. ws.send(msg);
  17010. }
  17011. },
  17012. [](const std::vector<std::string> &protocols) -> std::string {
  17013. for (const auto &p : protocols) {
  17014. if (p == "graphql-ws") { return p; }
  17015. }
  17016. return "";
  17017. });
  17018. }
  17019. void start_server() {
  17020. port_ = server_->bind_to_any_port(HOST);
  17021. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17022. server_->wait_until_ready();
  17023. }
  17024. std::unique_ptr<Server> server_;
  17025. std::thread server_thread_;
  17026. int port_ = 0;
  17027. };
  17028. TEST_F(WebSocketIntegrationTest, TextEcho) {
  17029. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17030. "/ws-echo");
  17031. ASSERT_TRUE(client.connect());
  17032. ASSERT_TRUE(client.is_open());
  17033. ASSERT_TRUE(client.send("Hello WebSocket"));
  17034. std::string msg;
  17035. EXPECT_EQ(ws::Text, client.read(msg));
  17036. EXPECT_EQ("Hello WebSocket", msg);
  17037. client.close();
  17038. }
  17039. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  17040. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17041. "/ws-echo");
  17042. ASSERT_TRUE(client.connect());
  17043. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  17044. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  17045. std::string msg;
  17046. EXPECT_EQ(ws::Binary, client.read(msg));
  17047. EXPECT_EQ(binary_data, msg);
  17048. client.close();
  17049. }
  17050. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  17051. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17052. "/ws-echo");
  17053. ASSERT_TRUE(client.connect());
  17054. for (int i = 0; i < 10; i++) {
  17055. auto text = "message " + std::to_string(i);
  17056. ASSERT_TRUE(client.send(text));
  17057. std::string msg;
  17058. ASSERT_TRUE(client.read(msg));
  17059. EXPECT_EQ(text, msg);
  17060. }
  17061. client.close();
  17062. }
  17063. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  17064. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17065. "/ws-close");
  17066. ASSERT_TRUE(client.connect());
  17067. // Send a message to trigger the server to close
  17068. ASSERT_TRUE(client.send("trigger close"));
  17069. // The server will close, so read should return false
  17070. std::string msg;
  17071. EXPECT_FALSE(client.read(msg));
  17072. EXPECT_FALSE(client.is_open());
  17073. }
  17074. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  17075. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17076. "/ws-echo");
  17077. ASSERT_TRUE(client.connect());
  17078. // 128KB message
  17079. std::string large_data(128 * 1024, 'X');
  17080. ASSERT_TRUE(client.send(large_data));
  17081. std::string msg;
  17082. ASSERT_TRUE(client.read(msg));
  17083. EXPECT_EQ(large_data, msg);
  17084. client.close();
  17085. }
  17086. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  17087. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17088. "/ws-echo");
  17089. ASSERT_TRUE(client.connect());
  17090. const int num_threads = 4;
  17091. std::vector<std::thread> threads;
  17092. std::atomic<int> send_count{0};
  17093. for (int t = 0; t < num_threads; t++) {
  17094. threads.emplace_back([&client, &send_count, t]() {
  17095. for (int i = 0; i < 5; i++) {
  17096. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  17097. if (client.send(text)) { send_count++; }
  17098. }
  17099. });
  17100. }
  17101. for (auto &th : threads) {
  17102. th.join();
  17103. }
  17104. int received = 0;
  17105. std::string msg;
  17106. while (received < send_count.load()) {
  17107. if (!client.read(msg)) { break; }
  17108. received++;
  17109. }
  17110. EXPECT_EQ(send_count.load(), received);
  17111. client.close();
  17112. }
  17113. TEST_F(WebSocketIntegrationTest, ReadString) {
  17114. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17115. "/ws-echo-string");
  17116. ASSERT_TRUE(client.connect());
  17117. ASSERT_TRUE(client.send("hello"));
  17118. std::string msg;
  17119. ASSERT_TRUE(client.read(msg));
  17120. EXPECT_EQ("echo: hello", msg);
  17121. ASSERT_TRUE(client.send("world"));
  17122. ASSERT_TRUE(client.read(msg));
  17123. EXPECT_EQ("echo: world", msg);
  17124. client.close();
  17125. }
  17126. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  17127. Headers headers = {{"X-Test-Header", "test-value"}};
  17128. ws::WebSocketClient client(
  17129. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  17130. ASSERT_TRUE(client.connect());
  17131. std::string msg;
  17132. ASSERT_TRUE(client.read(msg));
  17133. EXPECT_EQ("path:/ws-request-info", msg);
  17134. ASSERT_TRUE(client.read(msg));
  17135. EXPECT_EQ("header:test-value", msg);
  17136. client.close();
  17137. }
  17138. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  17139. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17140. "/ws-echo");
  17141. client.set_read_timeout(1, 0); // 1 second
  17142. ASSERT_TRUE(client.connect());
  17143. // Don't send anything — server echo handler waits for a message,
  17144. // so read() should time out and return false.
  17145. std::string msg;
  17146. EXPECT_FALSE(client.read(msg));
  17147. }
  17148. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  17149. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17150. "/ws-echo");
  17151. client.set_read_timeout(5, 0);
  17152. ASSERT_TRUE(client.connect());
  17153. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17154. // The server should reject it and close the connection.
  17155. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  17156. client.send(oversized);
  17157. // The server's read() should have failed due to payload limit,
  17158. // so our read() should return false (connection closed).
  17159. std::string msg;
  17160. EXPECT_FALSE(client.read(msg));
  17161. }
  17162. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  17163. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17164. "/ws-echo");
  17165. client.set_read_timeout(10, 0);
  17166. ASSERT_TRUE(client.connect());
  17167. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  17168. // This should succeed.
  17169. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  17170. ASSERT_TRUE(client.send(at_limit));
  17171. std::string msg;
  17172. ASSERT_TRUE(client.read(msg));
  17173. EXPECT_EQ(at_limit.size(), msg.size());
  17174. client.close();
  17175. }
  17176. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  17177. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17178. "/nonexistent");
  17179. auto res = client.connect();
  17180. EXPECT_FALSE(res);
  17181. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  17182. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  17183. EXPECT_FALSE(client.is_open());
  17184. }
  17185. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  17186. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17187. "/ws-echo");
  17188. ASSERT_TRUE(client.connect());
  17189. ASSERT_TRUE(client.send(""));
  17190. std::string msg;
  17191. EXPECT_EQ(ws::Text, client.read(msg));
  17192. EXPECT_EQ("", msg);
  17193. client.close();
  17194. }
  17195. TEST_F(WebSocketIntegrationTest, Reconnect) {
  17196. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17197. "/ws-echo");
  17198. // First connection
  17199. ASSERT_TRUE(client.connect());
  17200. ASSERT_TRUE(client.send("first"));
  17201. std::string msg;
  17202. ASSERT_TRUE(client.read(msg));
  17203. EXPECT_EQ("first", msg);
  17204. client.close();
  17205. EXPECT_FALSE(client.is_open());
  17206. // Reconnect using the same client object
  17207. ASSERT_TRUE(client.connect());
  17208. ASSERT_TRUE(client.is_open());
  17209. ASSERT_TRUE(client.send("second"));
  17210. ASSERT_TRUE(client.read(msg));
  17211. EXPECT_EQ("second", msg);
  17212. client.close();
  17213. }
  17214. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  17215. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17216. "/ws-close-status");
  17217. ASSERT_TRUE(client.connect());
  17218. // Trigger the server to close with GoingAway status
  17219. ASSERT_TRUE(client.send("trigger"));
  17220. // read() should return false after receiving the close frame
  17221. std::string msg;
  17222. EXPECT_FALSE(client.read(msg));
  17223. EXPECT_FALSE(client.is_open());
  17224. }
  17225. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  17226. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17227. "/ws-echo");
  17228. ASSERT_TRUE(client.connect());
  17229. client.close(ws::CloseStatus::GoingAway, "client leaving");
  17230. EXPECT_FALSE(client.is_open());
  17231. }
  17232. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  17233. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  17234. ws::WebSocketClient client(
  17235. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17236. ASSERT_TRUE(client.connect());
  17237. // Server should have selected graphql-ws
  17238. EXPECT_EQ("graphql-ws", client.subprotocol());
  17239. client.close();
  17240. }
  17241. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  17242. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  17243. ws::WebSocketClient client(
  17244. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17245. ASSERT_TRUE(client.connect());
  17246. // Server should not have selected any subprotocol
  17247. EXPECT_TRUE(client.subprotocol().empty());
  17248. client.close();
  17249. }
  17250. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  17251. // Connect without requesting any subprotocol
  17252. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17253. "/ws-subprotocol");
  17254. ASSERT_TRUE(client.connect());
  17255. EXPECT_TRUE(client.subprotocol().empty());
  17256. client.close();
  17257. }
  17258. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  17259. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17260. "/ws-echo");
  17261. client.set_tcp_nodelay(true);
  17262. client.set_connection_timeout(3, 0);
  17263. bool socket_options_called = false;
  17264. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  17265. ASSERT_TRUE(client.connect());
  17266. ASSERT_TRUE(client.is_open());
  17267. EXPECT_TRUE(socket_options_called);
  17268. ASSERT_TRUE(client.send("hello"));
  17269. std::string msg;
  17270. auto result = client.read(msg);
  17271. EXPECT_EQ(result, ws::ReadResult::Text);
  17272. EXPECT_EQ(msg, "hello");
  17273. client.close();
  17274. }
  17275. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  17276. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17277. "/ws-echo");
  17278. client.set_connection_timeout(std::chrono::seconds(3));
  17279. client.set_write_timeout(std::chrono::seconds(3));
  17280. // A sub-second remainder exercises the seconds/microseconds split.
  17281. client.set_read_timeout(std::chrono::milliseconds(1500));
  17282. ASSERT_TRUE(client.connect());
  17283. auto start = std::chrono::steady_clock::now();
  17284. std::string msg;
  17285. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  17286. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17287. std::chrono::steady_clock::now() - start)
  17288. .count();
  17289. // Above 1s so that dropping the microseconds half of the split fails here,
  17290. // and well under the 300s default so that ignoring the setter fails too.
  17291. EXPECT_GE(elapsed, 1400);
  17292. EXPECT_LT(elapsed, 30000);
  17293. }
  17294. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  17295. Server svr;
  17296. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  17297. if (!req.has_header("Authorization")) {
  17298. res.status = StatusCode::Unauthorized_401;
  17299. res.set_content("Unauthorized", "text/plain");
  17300. return Server::HandlerResponse::Handled;
  17301. }
  17302. return Server::HandlerResponse::Unhandled;
  17303. });
  17304. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17305. std::string msg;
  17306. while (ws.read(msg)) {
  17307. ws.send(msg);
  17308. }
  17309. });
  17310. auto port = svr.bind_to_any_port("localhost");
  17311. std::thread t([&]() { svr.listen_after_bind(); });
  17312. svr.wait_until_ready();
  17313. // Without Authorization header - should be rejected before upgrade
  17314. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  17315. EXPECT_FALSE(client1.connect());
  17316. // With Authorization header - should succeed
  17317. Headers headers = {{"Authorization", "Bearer token123"}};
  17318. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  17319. headers);
  17320. ASSERT_TRUE(client2.connect());
  17321. ASSERT_TRUE(client2.send("hello"));
  17322. std::string msg;
  17323. ASSERT_TRUE(client2.read(msg));
  17324. EXPECT_EQ("hello", msg);
  17325. client2.close();
  17326. svr.stop();
  17327. t.join();
  17328. }
  17329. TEST(WebSocketTest, QueryStringInHandshake) {
  17330. Server svr;
  17331. std::mutex mtx;
  17332. std::string received_target;
  17333. std::string received_token;
  17334. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17335. {
  17336. std::lock_guard<std::mutex> lock(mtx);
  17337. received_target = req.target;
  17338. if (req.has_param("token")) {
  17339. received_token = req.get_param_value("token");
  17340. }
  17341. }
  17342. std::string msg;
  17343. while (ws.read(msg)) {
  17344. ws.send(msg);
  17345. }
  17346. });
  17347. auto port = svr.bind_to_any_port("localhost");
  17348. std::thread t([&]() { svr.listen_after_bind(); });
  17349. svr.wait_until_ready();
  17350. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  17351. "/ws?token=ABC&session=123");
  17352. ASSERT_TRUE(client.connect());
  17353. // Round-trip ensures the handler has run and captured the request.
  17354. ASSERT_TRUE(client.send("hello"));
  17355. std::string msg;
  17356. ASSERT_TRUE(client.read(msg));
  17357. EXPECT_EQ("hello", msg);
  17358. client.close();
  17359. {
  17360. std::lock_guard<std::mutex> lock(mtx);
  17361. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  17362. EXPECT_EQ("ABC", received_token);
  17363. }
  17364. svr.stop();
  17365. t.join();
  17366. }
  17367. // Run a handshake against a throwaway server and hand the request the server
  17368. // received back to the caller, so tests can assert on the headers the client
  17369. // actually put on the wire.
  17370. static void capture_websocket_handshake_request(
  17371. const Headers &client_headers,
  17372. std::function<void(const Request &, int port)> verify) {
  17373. Server svr;
  17374. std::mutex mtx;
  17375. Request received;
  17376. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17377. {
  17378. std::lock_guard<std::mutex> lock(mtx);
  17379. received = req;
  17380. }
  17381. std::string msg;
  17382. while (ws.read(msg)) {
  17383. ws.send(msg);
  17384. }
  17385. });
  17386. auto port = svr.bind_to_any_port("localhost");
  17387. std::thread t([&]() { svr.listen_after_bind(); });
  17388. auto se = detail::scope_exit([&] {
  17389. svr.stop();
  17390. t.join();
  17391. });
  17392. svr.wait_until_ready();
  17393. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  17394. client_headers);
  17395. ASSERT_TRUE(client.connect());
  17396. ASSERT_TRUE(client.send("hello"));
  17397. std::string msg;
  17398. ASSERT_TRUE(client.read(msg));
  17399. client.close();
  17400. {
  17401. std::lock_guard<std::mutex> lock(mtx);
  17402. verify(received, port);
  17403. }
  17404. }
  17405. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  17406. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  17407. // Non-default port must be present in the Host header. Default ports
  17408. // (80/443) are omitted; that logic is covered by
  17409. // MakeHostAndPortStringTest.
  17410. EXPECT_EQ("localhost:" + std::to_string(port),
  17411. req.get_header_value("Host"));
  17412. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  17413. req.get_header_value("User-Agent"));
  17414. EXPECT_FALSE(req.has_header("Accept"));
  17415. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  17416. EXPECT_FALSE(req.has_header("Content-Length"));
  17417. });
  17418. }
  17419. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  17420. capture_websocket_handshake_request(
  17421. {{"Host", "example.com"},
  17422. {"User-Agent", "custom-agent"},
  17423. {"X-Custom", "value"}},
  17424. [](const Request &req, int) {
  17425. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17426. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17427. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17428. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17429. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17430. });
  17431. }
  17432. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17433. capture_websocket_handshake_request(
  17434. {{"Upgrade", "bogus"},
  17435. {"Connection", "close"},
  17436. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17437. {"Sec-WebSocket-Version", "8"}},
  17438. [](const Request &req, int) {
  17439. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17440. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17441. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17442. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17443. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17444. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17445. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  17446. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  17447. req.get_header_value("Sec-WebSocket-Key"));
  17448. });
  17449. }
  17450. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  17451. // A header the client refuses to send must abort the handshake before any
  17452. // part of it reaches the wire; a lone request line would otherwise sit in
  17453. // the peer's buffer as a truncated request.
  17454. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17455. ASSERT_NE(INVALID_SOCKET, srv);
  17456. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  17457. sockaddr_in addr{};
  17458. addr.sin_family = AF_INET;
  17459. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  17460. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17461. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17462. ASSERT_EQ(0, ::listen(srv, 1));
  17463. sockaddr_in bound{};
  17464. socklen_t bound_len = sizeof(bound);
  17465. ASSERT_EQ(
  17466. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  17467. auto port = ntohs(bound.sin_port);
  17468. ssize_t received = -1;
  17469. std::thread t([&] {
  17470. // Bound every blocking call so a regression fails the test with a bad
  17471. // value instead of hanging the suite.
  17472. fd_set rfds;
  17473. FD_ZERO(&rfds);
  17474. FD_SET(srv, &rfds);
  17475. timeval tv{5, 0};
  17476. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  17477. 0) {
  17478. return;
  17479. }
  17480. sockaddr_in cli_addr{};
  17481. socklen_t cli_len = sizeof(cli_addr);
  17482. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17483. if (cli == INVALID_SOCKET) { return; }
  17484. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  17485. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17486. char buf[4096];
  17487. received = ::recv(cli, buf, sizeof(buf), 0);
  17488. });
  17489. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  17490. // connect() has already shut the socket down by the time it returns false,
  17491. // so the peer sees EOF without waiting for the client to be destroyed.
  17492. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  17493. {{"X-Bad", "a\r\nInjected: 1"}});
  17494. EXPECT_FALSE(client.connect());
  17495. t.join();
  17496. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  17497. EXPECT_EQ(0, received);
  17498. }
  17499. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  17500. // The socket path doubles as the URL host, so it must not contain '/'.
  17501. const char *shard = getenv("GTEST_SHARD_INDEX");
  17502. const std::string sock_path =
  17503. shard ? std::string("httplib-ws-") + shard + ".sock"
  17504. : std::string("httplib-ws.sock");
  17505. std::remove(sock_path.c_str());
  17506. Server svr;
  17507. std::mutex mtx;
  17508. std::string received_host;
  17509. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17510. {
  17511. std::lock_guard<std::mutex> lock(mtx);
  17512. received_host = req.get_header_value("Host");
  17513. }
  17514. std::string msg;
  17515. while (ws.read(msg)) {
  17516. ws.send(msg);
  17517. }
  17518. });
  17519. svr.set_address_family(AF_UNIX);
  17520. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  17521. auto se = detail::scope_exit([&] {
  17522. svr.stop();
  17523. t.join();
  17524. std::remove(sock_path.c_str());
  17525. });
  17526. svr.wait_until_ready();
  17527. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  17528. client.set_address_family(AF_UNIX);
  17529. ASSERT_TRUE(client.connect());
  17530. ASSERT_TRUE(client.send("hello"));
  17531. std::string msg;
  17532. ASSERT_TRUE(client.read(msg));
  17533. client.close();
  17534. {
  17535. std::lock_guard<std::mutex> lock(mtx);
  17536. // There is no host:port for a Unix socket, so the same "localhost"
  17537. // placeholder the HTTP client uses is expected.
  17538. EXPECT_EQ("localhost", received_host);
  17539. }
  17540. }
  17541. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17542. class WebSocketSSLIntegrationTest : public ::testing::Test {
  17543. protected:
  17544. void SetUp() override {
  17545. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  17546. SERVER_PRIVATE_KEY_FILE);
  17547. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17548. std::string msg;
  17549. ws::ReadResult ret;
  17550. while ((ret = ws.read(msg))) {
  17551. if (ret == ws::Binary) {
  17552. ws.send(msg.data(), msg.size());
  17553. } else {
  17554. ws.send(msg);
  17555. }
  17556. }
  17557. });
  17558. port_ = server_->bind_to_any_port(HOST);
  17559. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17560. server_->wait_until_ready();
  17561. }
  17562. void TearDown() override {
  17563. server_->stop();
  17564. if (server_thread_.joinable()) { server_thread_.join(); }
  17565. }
  17566. std::unique_ptr<SSLServer> server_;
  17567. std::thread server_thread_;
  17568. int port_ = 0;
  17569. };
  17570. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  17571. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17572. "/ws-echo");
  17573. client.enable_server_certificate_verification(false);
  17574. ASSERT_TRUE(client.connect());
  17575. ASSERT_TRUE(client.is_open());
  17576. ASSERT_TRUE(client.send("Hello WSS"));
  17577. std::string msg;
  17578. EXPECT_EQ(ws::Text, client.read(msg));
  17579. EXPECT_EQ("Hello WSS", msg);
  17580. client.close();
  17581. }
  17582. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  17583. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  17584. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  17585. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  17586. // client (without calling close() first) is the only path that runs
  17587. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  17588. // bug exactly.
  17589. //
  17590. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  17591. // when linked against an instrumented libssl; run under Valgrind to catch it
  17592. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  17593. // suite (the freed session otherwise stalls on the close handshake) — this test
  17594. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  17595. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  17596. {
  17597. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17598. "/ws-echo");
  17599. client.enable_server_certificate_verification(false);
  17600. client.set_read_timeout(2, 0);
  17601. client.set_write_timeout(2, 0);
  17602. ASSERT_TRUE(client.connect());
  17603. ASSERT_TRUE(client.is_open());
  17604. ASSERT_TRUE(client.send("still open"));
  17605. // Intentionally do NOT call client.close(): leaving scope runs
  17606. // shutdown_and_close() with the WebSocket still open, which must send the
  17607. // close frame while the TLS session is still alive.
  17608. }
  17609. }
  17610. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  17611. // shutdown_and_close() at the start of connect(), reproducing the same
  17612. // use-after-free within the test body rather than at scope exit. The second
  17613. // connect must succeed and echo, proving the close handshake ran over a live
  17614. // session. See the note above about memory-tool requirements.
  17615. TEST_F(WebSocketSSLIntegrationTest,
  17616. ReconnectWhileOpenSendsCloseOverLiveSession) {
  17617. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17618. "/ws-echo");
  17619. client.enable_server_certificate_verification(false);
  17620. client.set_read_timeout(2, 0);
  17621. client.set_write_timeout(2, 0);
  17622. ASSERT_TRUE(client.connect());
  17623. ASSERT_TRUE(client.is_open());
  17624. ASSERT_TRUE(client.send("still open"));
  17625. // Reconnect without closing first: connect() calls shutdown_and_close() on
  17626. // the still-open connection, which must not touch a freed TLS session.
  17627. ASSERT_TRUE(client.connect());
  17628. ASSERT_TRUE(client.is_open());
  17629. ASSERT_TRUE(client.send("after reconnect"));
  17630. std::string msg;
  17631. EXPECT_EQ(ws::Text, client.read(msg));
  17632. EXPECT_EQ("after reconnect", msg);
  17633. client.close();
  17634. }
  17635. #endif
  17636. #ifdef CPPHTTPLIB_SSL_ENABLED
  17637. class WebSocketSSLCATest : public ::testing::Test {
  17638. protected:
  17639. void SetUp() override {
  17640. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  17641. SERVER_PRIVATE_KEY_FILE);
  17642. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17643. std::string msg;
  17644. while (ws.read(msg)) {
  17645. ws.send(msg);
  17646. }
  17647. });
  17648. port_ = server_->bind_to_any_port("127.0.0.1");
  17649. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17650. server_->wait_until_ready();
  17651. }
  17652. void TearDown() override {
  17653. server_->stop();
  17654. if (server_thread_.joinable()) { server_thread_.join(); }
  17655. }
  17656. std::string url() const {
  17657. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  17658. }
  17659. std::unique_ptr<SSLServer> server_;
  17660. std::thread server_thread_;
  17661. int port_ = 0;
  17662. };
  17663. // A custom CA loaded as PEM verifies the server with full certificate
  17664. // verification enabled
  17665. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  17666. ws::WebSocketClient client(url());
  17667. std::string cert;
  17668. read_file(SERVER_CERT2_FILE, cert);
  17669. client.load_ca_cert_store(cert.c_str(), cert.size());
  17670. ASSERT_TRUE(client.connect());
  17671. ASSERT_TRUE(client.send("hello"));
  17672. std::string msg;
  17673. EXPECT_EQ(ws::Text, client.read(msg));
  17674. EXPECT_EQ("hello", msg);
  17675. client.close();
  17676. }
  17677. // A custom CA that does not cover the server must fail verification (the
  17678. // custom CA is exclusive; system certs are not loaded alongside it)
  17679. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  17680. ws::WebSocketClient client(url());
  17681. std::string cert;
  17682. read_file(CLIENT_CA_CERT_FILE, cert);
  17683. client.load_ca_cert_store(cert.c_str(), cert.size());
  17684. auto res = client.connect();
  17685. ASSERT_FALSE(res);
  17686. EXPECT_EQ(Error::SSLServerVerification, res.error());
  17687. EXPECT_EQ(-1, res.status());
  17688. EXPECT_NE(0u, res.ssl_backend_error());
  17689. }
  17690. // The same CA as a file path rather than PEM in memory
  17691. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  17692. ws::WebSocketClient client(url());
  17693. client.set_ca_cert_path(SERVER_CERT2_FILE);
  17694. ASSERT_TRUE(client.connect());
  17695. ASSERT_TRUE(client.send("hello"));
  17696. std::string msg;
  17697. EXPECT_EQ(ws::Text, client.read(msg));
  17698. EXPECT_EQ("hello", msg);
  17699. client.close();
  17700. }
  17701. // ...and a CA file that does not cover the server still fails, so it is the
  17702. // path above that decides the outcome
  17703. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  17704. ws::WebSocketClient client(url());
  17705. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  17706. ASSERT_FALSE(client.connect());
  17707. }
  17708. // Regression test: reconnecting with a native custom CA store used to reuse
  17709. // a store handle the previous TLS context had already freed (use-after-free
  17710. // under the OpenSSL backend). The context now lives as long as the client.
  17711. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  17712. ws::WebSocketClient client(url());
  17713. std::string cert;
  17714. read_file(SERVER_CERT2_FILE, cert);
  17715. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  17716. ASSERT_TRUE(client.connect());
  17717. client.close();
  17718. ASSERT_TRUE(client.connect());
  17719. ASSERT_TRUE(client.send("again"));
  17720. std::string msg;
  17721. EXPECT_EQ(ws::Text, client.read(msg));
  17722. EXPECT_EQ("again", msg);
  17723. client.close();
  17724. }
  17725. // Regression test: a certificate with a trusted chain but no identity match
  17726. // for the server IP must be rejected. The Mbed TLS backend used to skip
  17727. // verification entirely for IP hosts, so this connection succeeded there.
  17728. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  17729. // chain verification while the identity check must still fail.
  17730. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  17731. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17732. ASSERT_TRUE(svr.is_valid());
  17733. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17734. std::string msg;
  17735. while (ws.read(msg)) {
  17736. ws.send(msg);
  17737. }
  17738. });
  17739. auto port = svr.bind_to_any_port("127.0.0.1");
  17740. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17741. auto se = detail::scope_exit([&] {
  17742. svr.stop();
  17743. t.join();
  17744. });
  17745. svr.wait_until_ready();
  17746. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  17747. "/echo");
  17748. std::string cert;
  17749. read_file(SERVER_CERT_FILE, cert);
  17750. client.load_ca_cert_store(cert.c_str(), cert.size());
  17751. ASSERT_FALSE(client.connect());
  17752. }
  17753. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  17754. // SNI, so nothing binds the host name to the TLS session. These bind the
  17755. // server to "localhost" instead, the only shape that exercises the SNI and
  17756. // hostname-verification path with certificate verification left enabled.
  17757. class WebSocketSSLDnsHostTest : public ::testing::Test {
  17758. protected:
  17759. void Start(const char *cert_file) {
  17760. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  17761. SERVER_PRIVATE_KEY_FILE);
  17762. ASSERT_TRUE(server_->is_valid());
  17763. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17764. std::string msg;
  17765. while (ws.read(msg)) {
  17766. ws.send(msg);
  17767. }
  17768. });
  17769. port_ = server_->bind_to_any_port("localhost");
  17770. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17771. server_->wait_until_ready();
  17772. }
  17773. void TearDown() override {
  17774. if (server_) { server_->stop(); }
  17775. if (server_thread_.joinable()) { server_thread_.join(); }
  17776. }
  17777. std::string url() const {
  17778. return "wss://localhost:" + std::to_string(port_) + "/echo";
  17779. }
  17780. std::unique_ptr<SSLServer> server_;
  17781. std::thread server_thread_;
  17782. int port_ = 0;
  17783. };
  17784. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  17785. // out and the connection is usable
  17786. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  17787. Start(SERVER_CERT2_FILE);
  17788. ws::WebSocketClient client(url());
  17789. client.set_ca_cert_path(SERVER_CERT2_FILE);
  17790. ASSERT_TRUE(client.connect());
  17791. ASSERT_TRUE(client.send("hello"));
  17792. std::string msg;
  17793. EXPECT_EQ(ws::Text, client.read(msg));
  17794. EXPECT_EQ("hello", msg);
  17795. client.close();
  17796. }
  17797. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  17798. // while the identity check must still reject "localhost"
  17799. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  17800. Start(SERVER_CERT_FILE);
  17801. ws::WebSocketClient client(url());
  17802. client.set_ca_cert_path(SERVER_CERT_FILE);
  17803. auto res = client.connect();
  17804. ASSERT_FALSE(res);
  17805. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  17806. EXPECT_EQ(-1, res.status());
  17807. }
  17808. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  17809. // disabled: the chain is still checked, only the identity check is skipped
  17810. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  17811. Start(SERVER_CERT_FILE);
  17812. ws::WebSocketClient client(url());
  17813. client.set_ca_cert_path(SERVER_CERT_FILE);
  17814. client.enable_server_hostname_verification(false);
  17815. ASSERT_TRUE(client.connect());
  17816. ASSERT_TRUE(client.send("hello"));
  17817. std::string msg;
  17818. EXPECT_EQ(ws::Text, client.read(msg));
  17819. EXPECT_EQ("hello", msg);
  17820. client.close();
  17821. }
  17822. // A CA that did not sign the server certificate fails the chain, even though
  17823. // the name would match
  17824. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  17825. Start(SERVER_CERT2_FILE);
  17826. ws::WebSocketClient client(url());
  17827. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  17828. ASSERT_FALSE(client.connect());
  17829. }
  17830. // With verification disabled, neither the chain nor the name is checked
  17831. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  17832. Start(SERVER_CERT_FILE);
  17833. ws::WebSocketClient client(url());
  17834. client.enable_server_certificate_verification(false);
  17835. ASSERT_TRUE(client.connect());
  17836. ASSERT_TRUE(client.send("hello"));
  17837. std::string msg;
  17838. EXPECT_EQ(ws::Text, client.read(msg));
  17839. EXPECT_EQ("hello", msg);
  17840. client.close();
  17841. }
  17842. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  17843. protected:
  17844. void SetUp() override {
  17845. server_ = httplib::detail::make_unique<SSLServer>(
  17846. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17847. ASSERT_TRUE(server_->is_valid());
  17848. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17849. std::string msg;
  17850. while (ws.read(msg)) {
  17851. ws.send(msg);
  17852. }
  17853. });
  17854. port_ = server_->bind_to_any_port("localhost");
  17855. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17856. server_->wait_until_ready();
  17857. }
  17858. void TearDown() override {
  17859. server_->stop();
  17860. if (server_thread_.joinable()) { server_thread_.join(); }
  17861. }
  17862. std::string url() const {
  17863. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  17864. }
  17865. void ConnectWithClientCert(const std::string &client_cert_file,
  17866. const std::string &client_private_key_file,
  17867. const char *private_key_password) {
  17868. std::string cert_pem, key_pem;
  17869. read_file(client_cert_file, cert_pem);
  17870. read_file(client_private_key_file, key_pem);
  17871. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  17872. key_pem.c_str(), key_pem.size(),
  17873. private_key_password};
  17874. ws::WebSocketClient client(url(), pem);
  17875. ASSERT_TRUE(client.is_valid());
  17876. client.enable_server_certificate_verification(false);
  17877. ASSERT_TRUE(client.connect());
  17878. ASSERT_TRUE(client.send("hello"));
  17879. std::string msg;
  17880. EXPECT_EQ(ws::Text, client.read(msg));
  17881. EXPECT_EQ("hello", msg);
  17882. client.close();
  17883. }
  17884. std::unique_ptr<SSLServer> server_;
  17885. std::thread server_thread_;
  17886. int port_ = 0;
  17887. };
  17888. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  17889. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  17890. }
  17891. // Control for the tests above: the fixture's server really does require a
  17892. // client certificate, so it is the PEM the constructor installed that decides
  17893. // the outcome.
  17894. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  17895. ws::WebSocketClient client(url());
  17896. ASSERT_TRUE(client.is_valid());
  17897. client.enable_server_certificate_verification(false);
  17898. EXPECT_FALSE(client.connect());
  17899. }
  17900. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  17901. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  17902. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  17903. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  17904. }
  17905. #endif
  17906. #if !defined(_WIN32)
  17907. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  17908. auto secret_dir = std::string("./symlink_test_secret");
  17909. auto served_dir = std::string("./symlink_test_served");
  17910. auto secret_file = secret_dir + "/secret.txt";
  17911. auto symlink_path = served_dir + "/escape";
  17912. // Setup: create directories and files
  17913. mkdir(secret_dir.c_str(), 0755);
  17914. mkdir(served_dir.c_str(), 0755);
  17915. {
  17916. std::ofstream ofs(secret_file);
  17917. ofs << "SECRET_DATA";
  17918. }
  17919. // Create symlink using absolute path so it resolves correctly
  17920. #ifdef PATH_MAX
  17921. char abs_secret[PATH_MAX];
  17922. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  17923. #else
  17924. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  17925. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  17926. ASSERT_NE(nullptr, abs_secret);
  17927. #endif
  17928. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  17929. auto se = detail::scope_exit([&] {
  17930. unlink(symlink_path.c_str());
  17931. unlink(secret_file.c_str());
  17932. rmdir(served_dir.c_str());
  17933. rmdir(secret_dir.c_str());
  17934. });
  17935. Server svr;
  17936. svr.set_mount_point("/", served_dir);
  17937. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17938. auto se2 = detail::scope_exit([&] {
  17939. svr.stop();
  17940. listen_thread.join();
  17941. });
  17942. svr.wait_until_ready();
  17943. Client cli("localhost", PORT);
  17944. // Symlink pointing outside base dir should be blocked
  17945. auto res = cli.Get("/escape/secret.txt");
  17946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17947. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17948. }
  17949. #endif
  17950. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  17951. // A GET request with Content-Length to a static file handler must have its
  17952. // body drained before the keep-alive connection is reused. Otherwise the
  17953. // unread body bytes are interpreted as the next HTTP request.
  17954. //
  17955. // The body is sent AFTER receiving the first response (as in the original
  17956. // PoC) so that the stream_line_reader cannot buffer it together with the
  17957. // headers of the first request.
  17958. Server svr;
  17959. svr.set_mount_point("/", "./www");
  17960. std::atomic<int> smuggled_count(0);
  17961. svr.Get("/smuggled", [&](const Request &, Response &res) {
  17962. smuggled_count++;
  17963. res.set_content("oops", "text/plain");
  17964. });
  17965. auto port = svr.bind_to_any_port("localhost");
  17966. thread t = thread([&] { svr.listen_after_bind(); });
  17967. auto se = detail::scope_exit([&] {
  17968. svr.stop();
  17969. t.join();
  17970. });
  17971. svr.wait_until_ready();
  17972. auto error = Error::Success;
  17973. auto sock = detail::create_client_socket(
  17974. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  17975. /*connection_timeout_sec=*/2, 0,
  17976. /*read_timeout_sec=*/2, 0,
  17977. /*write_timeout_sec=*/2, 0, std::string(), error);
  17978. ASSERT_NE(INVALID_SOCKET, sock);
  17979. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17980. // The "smuggled" request will be sent as the body of the outer GET
  17981. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17982. "Host: localhost\r\n"
  17983. "Connection: close\r\n"
  17984. "\r\n";
  17985. // Step 1: Send only the outer request headers (no body yet)
  17986. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17987. "Host: localhost\r\n"
  17988. "Content-Length: " +
  17989. std::to_string(smuggled.size()) +
  17990. "\r\n"
  17991. "\r\n";
  17992. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17993. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17994. // Step 2: Read the first response (server serves file without reading body)
  17995. std::string first_response;
  17996. char buf[4096];
  17997. for (;;) {
  17998. auto n = recv(sock, buf, sizeof(buf), 0);
  17999. if (n <= 0) break;
  18000. first_response.append(buf, static_cast<size_t>(n));
  18001. // Stop once we have a complete response (headers + body)
  18002. auto hdr_end = first_response.find("\r\n\r\n");
  18003. if (hdr_end != std::string::npos) {
  18004. // Check for Content-Length to know when the body is complete
  18005. auto cl_pos = first_response.find("Content-Length:");
  18006. if (cl_pos != std::string::npos) {
  18007. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  18008. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  18009. auto cl = std::stoul(
  18010. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  18011. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  18012. } else {
  18013. break; // No Content-Length, assume headers-only response
  18014. }
  18015. }
  18016. }
  18017. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  18018. // Step 3: Now send the body, which looks like a new HTTP request.
  18019. // On a vulnerable server the keep-alive loop reads this as a second request.
  18020. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  18021. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  18022. // Step 4: Try to read a second response (should NOT exist after fix)
  18023. std::string second_response;
  18024. for (;;) {
  18025. auto n = recv(sock, buf, sizeof(buf), 0);
  18026. if (n <= 0) break;
  18027. second_response.append(buf, static_cast<size_t>(n));
  18028. }
  18029. // The smuggled request must NOT have been processed
  18030. EXPECT_EQ(0, smuggled_count.load());
  18031. }
  18032. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18033. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  18034. // must be rejected with 400 Bad Request.
  18035. Server svr;
  18036. svr.Post("/test", [&](const Request &, Response &res) {
  18037. res.set_content("ok", "text/plain");
  18038. });
  18039. thread t = thread([&] { svr.listen(HOST, PORT); });
  18040. auto se = detail::scope_exit([&] {
  18041. svr.stop();
  18042. t.join();
  18043. ASSERT_FALSE(svr.is_running());
  18044. });
  18045. svr.wait_until_ready();
  18046. // Exact "chunked"
  18047. {
  18048. auto req = "POST /test HTTP/1.1\r\n"
  18049. "Host: localhost\r\n"
  18050. "Content-Length: 5\r\n"
  18051. "Transfer-Encoding: chunked\r\n"
  18052. "Connection: close\r\n"
  18053. "\r\n"
  18054. "hello";
  18055. std::string response;
  18056. ASSERT_TRUE(send_request(1, req, &response));
  18057. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18058. response.substr(0, response.find("\r\n")));
  18059. }
  18060. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  18061. {
  18062. auto req = "POST /test HTTP/1.1\r\n"
  18063. "Host: localhost\r\n"
  18064. "Content-Length: 5\r\n"
  18065. "Transfer-Encoding: gzip, chunked\r\n"
  18066. "Connection: close\r\n"
  18067. "\r\n"
  18068. "hello";
  18069. std::string response;
  18070. ASSERT_TRUE(send_request(1, req, &response));
  18071. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18072. response.substr(0, response.find("\r\n")));
  18073. }
  18074. }
  18075. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  18076. Server svr;
  18077. svr.Post("/test", [&](const Request &, Response &res) {
  18078. res.set_content("ok", "text/plain");
  18079. });
  18080. thread t = thread([&] { svr.listen(HOST, PORT); });
  18081. auto se = detail::scope_exit([&] {
  18082. svr.stop();
  18083. t.join();
  18084. ASSERT_FALSE(svr.is_running());
  18085. });
  18086. svr.wait_until_ready();
  18087. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  18088. // length cannot be determined, so the server must answer 400 and close
  18089. // rather than treat the request as bodyless and leave the body in the
  18090. // socket for the next request to pick up.
  18091. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  18092. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  18093. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  18094. std::string response;
  18095. ASSERT_TRUE(send_request(1, req, &response));
  18096. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18097. response.substr(0, response.find("\r\n")))
  18098. << transfer_encoding;
  18099. }
  18100. // RFC 9110 5.3: the codings may also be split across several
  18101. // Transfer-Encoding lines, which combine in the order they were received.
  18102. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  18103. // just like the single-line "chunked, gzip" above.
  18104. {
  18105. auto req = "POST /test HTTP/1.1\r\n"
  18106. "Host: localhost\r\n"
  18107. "Transfer-Encoding: chunked\r\n"
  18108. "Transfer-Encoding: gzip\r\n"
  18109. "\r\n"
  18110. "0\r\n\r\n";
  18111. std::string response;
  18112. ASSERT_TRUE(send_request(1, req, &response));
  18113. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  18114. response.substr(0, response.find("\r\n")));
  18115. }
  18116. // A sequence ending in chunked stays valid.
  18117. auto req = "POST /test HTTP/1.1\r\n"
  18118. "Host: localhost\r\n"
  18119. "Transfer-Encoding: gzip, chunked\r\n"
  18120. "Connection: close\r\n"
  18121. "\r\n"
  18122. "0\r\n\r\n";
  18123. std::string response;
  18124. ASSERT_TRUE(send_request(1, req, &response));
  18125. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18126. // ...including when it is spread over several lines.
  18127. auto split_req = "POST /test HTTP/1.1\r\n"
  18128. "Host: localhost\r\n"
  18129. "Transfer-Encoding: gzip\r\n"
  18130. "Transfer-Encoding: chunked\r\n"
  18131. "Connection: close\r\n"
  18132. "\r\n"
  18133. "0\r\n\r\n";
  18134. std::string split_response;
  18135. ASSERT_TRUE(send_request(1, split_req, &split_response));
  18136. EXPECT_EQ("HTTP/1.1 200 OK",
  18137. split_response.substr(0, split_response.find("\r\n")));
  18138. }
  18139. // Regression for issue #2450: a DELETE without Content-Length on a
  18140. // keep-alive connection must not let the post-response drain consume the
  18141. // next request's bytes.
  18142. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  18143. Server svr;
  18144. std::atomic<int> delete_count(0);
  18145. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  18146. delete_count++;
  18147. res.status = StatusCode::NoContent_204;
  18148. });
  18149. auto port = svr.bind_to_any_port(HOST);
  18150. thread t = thread([&] { svr.listen_after_bind(); });
  18151. auto se = detail::scope_exit([&] {
  18152. svr.stop();
  18153. t.join();
  18154. });
  18155. svr.wait_until_ready();
  18156. auto error = Error::Success;
  18157. auto sock = detail::create_client_socket(
  18158. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18159. /*connection_timeout_sec=*/2, 0,
  18160. /*read_timeout_sec=*/2, 0,
  18161. /*write_timeout_sec=*/2, 0, std::string(), error);
  18162. ASSERT_NE(INVALID_SOCKET, sock);
  18163. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18164. auto send_request_and_read_response = [&](const std::string &req,
  18165. std::string &out) -> bool {
  18166. auto sent = send(sock, req.data(), req.size(), 0);
  18167. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  18168. char buf[4096];
  18169. for (;;) {
  18170. auto n = recv(sock, buf, sizeof(buf), 0);
  18171. if (n <= 0) { return !out.empty(); }
  18172. out.append(buf, static_cast<size_t>(n));
  18173. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  18174. }
  18175. };
  18176. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  18177. "Host: localhost\r\n"
  18178. "\r\n";
  18179. std::string resp1;
  18180. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  18181. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  18182. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  18183. "Host: localhost\r\n"
  18184. "Connection: close\r\n"
  18185. "\r\n";
  18186. std::string resp2;
  18187. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  18188. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  18189. EXPECT_EQ(2, delete_count.load());
  18190. }
  18191. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  18192. Server svr;
  18193. svr.Post("/ingest", [&](const Request &, Response &res,
  18194. const ContentReader &content_reader) {
  18195. auto consumed = content_reader([](const char *, size_t) { return false; });
  18196. EXPECT_FALSE(consumed);
  18197. res.status = StatusCode::Conflict_409;
  18198. res.set_header("Connection", "close");
  18199. });
  18200. auto port = svr.bind_to_any_port(HOST);
  18201. thread t = thread([&] { svr.listen_after_bind(); });
  18202. auto se = detail::scope_exit([&] {
  18203. svr.stop();
  18204. t.join();
  18205. });
  18206. svr.wait_until_ready();
  18207. auto error = Error::Success;
  18208. auto sock = detail::create_client_socket(
  18209. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18210. /*connection_timeout_sec=*/2, 0,
  18211. /*read_timeout_sec=*/1, 0,
  18212. /*write_timeout_sec=*/2, 0, std::string(), error);
  18213. ASSERT_NE(INVALID_SOCKET, sock);
  18214. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18215. std::string request = "POST /ingest HTTP/1.1\r\n"
  18216. "Host: localhost\r\n"
  18217. "Transfer-Encoding: chunked\r\n"
  18218. "\r\n"
  18219. "4\r\n"
  18220. "data\r\n";
  18221. auto sent = send(sock, request.data(), request.size(), 0);
  18222. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  18223. std::string response;
  18224. ssize_t received = 0;
  18225. do {
  18226. char buf[4096];
  18227. received = recv(sock, buf, sizeof(buf), 0);
  18228. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  18229. } while (received > 0);
  18230. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  18231. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  18232. EXPECT_EQ(0, received);
  18233. }
  18234. namespace no_proxy_test {
  18235. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  18236. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  18237. // calling listen().
  18238. class ScopedServer {
  18239. public:
  18240. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  18241. ~ScopedServer() {
  18242. svr_.stop();
  18243. if (th_.joinable()) { th_.join(); }
  18244. }
  18245. Server &svr() { return svr_; }
  18246. int port() const { return port_; }
  18247. void listen() {
  18248. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18249. svr_.wait_until_ready();
  18250. }
  18251. private:
  18252. Server svr_;
  18253. std::thread th_;
  18254. int port_ = 0;
  18255. };
  18256. class ProxyAndTargetServers {
  18257. public:
  18258. ProxyAndTargetServers() {
  18259. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  18260. proxy_hits_++;
  18261. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18262. res.set_content("via-proxy", "text/plain");
  18263. });
  18264. target_.Get(".*", [this](const Request &req, Response &res) {
  18265. target_hits_++;
  18266. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18267. res.set_content("direct", "text/plain");
  18268. });
  18269. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  18270. target_port_ = target_.bind_to_any_port("127.0.0.1");
  18271. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  18272. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  18273. proxy_mock_.wait_until_ready();
  18274. target_.wait_until_ready();
  18275. }
  18276. ~ProxyAndTargetServers() {
  18277. proxy_mock_.stop();
  18278. target_.stop();
  18279. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  18280. if (target_thread_.joinable()) { target_thread_.join(); }
  18281. }
  18282. Server &proxy_mock() { return proxy_mock_; }
  18283. Server &target() { return target_; }
  18284. int proxy_port() const { return proxy_port_; }
  18285. int target_port() const { return target_port_; }
  18286. int proxy_hits() const { return proxy_hits_.load(); }
  18287. int target_hits() const { return target_hits_.load(); }
  18288. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  18289. void reset_counters() {
  18290. proxy_hits_ = 0;
  18291. target_hits_ = 0;
  18292. last_had_proxy_authz_ = false;
  18293. }
  18294. private:
  18295. Server proxy_mock_;
  18296. Server target_;
  18297. std::thread proxy_thread_;
  18298. std::thread target_thread_;
  18299. int proxy_port_ = 0;
  18300. int target_port_ = 0;
  18301. std::atomic<int> proxy_hits_{0};
  18302. std::atomic<int> target_hits_{0};
  18303. std::atomic<bool> last_had_proxy_authz_{false};
  18304. };
  18305. inline std::unique_ptr<Client> make_client(const std::string &host,
  18306. ProxyAndTargetServers &s) {
  18307. auto cli = detail::make_unique<Client>(host, s.target_port());
  18308. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  18309. cli->set_proxy("127.0.0.1", s.proxy_port());
  18310. return cli;
  18311. }
  18312. } // namespace no_proxy_test
  18313. using no_proxy_test::make_client;
  18314. using no_proxy_test::ProxyAndTargetServers;
  18315. TEST(NoProxyTest, ExactHostnameBypasses) {
  18316. ProxyAndTargetServers s;
  18317. auto cli = make_client("example.com", s);
  18318. cli->set_no_proxy({"example.com"});
  18319. auto res = cli->Get("/");
  18320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18321. EXPECT_EQ(0, s.proxy_hits());
  18322. EXPECT_EQ(1, s.target_hits());
  18323. }
  18324. TEST(NoProxyTest, SubdomainBypasses) {
  18325. ProxyAndTargetServers s;
  18326. auto cli = make_client("foo.example.com", s);
  18327. cli->set_no_proxy({"example.com"});
  18328. auto res = cli->Get("/");
  18329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18330. EXPECT_EQ(0, s.proxy_hits());
  18331. EXPECT_EQ(1, s.target_hits());
  18332. }
  18333. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  18334. // Regression guard: "evilexample.com" must not be considered a subdomain
  18335. // of "example.com". Without the dot-boundary rule, a naive endsWith
  18336. // check would let traffic bypass the proxy and leak credentials direct
  18337. // to the attacker host.
  18338. ProxyAndTargetServers s;
  18339. auto cli = make_client("evilexample.com", s);
  18340. cli->set_no_proxy({"example.com"});
  18341. auto res = cli->Get("/");
  18342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18343. EXPECT_GE(s.proxy_hits(), 1);
  18344. EXPECT_EQ(0, s.target_hits());
  18345. }
  18346. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  18347. ProxyAndTargetServers s;
  18348. auto cli = make_client("example.com.evil.com", s);
  18349. cli->set_no_proxy({"example.com"});
  18350. auto res = cli->Get("/");
  18351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18352. EXPECT_GE(s.proxy_hits(), 1);
  18353. EXPECT_EQ(0, s.target_hits());
  18354. }
  18355. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  18356. ProxyAndTargetServers s;
  18357. auto cli = make_client("example.com", s);
  18358. cli->set_no_proxy({".example.com"});
  18359. auto res = cli->Get("/");
  18360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18361. EXPECT_EQ(0, s.proxy_hits());
  18362. EXPECT_EQ(1, s.target_hits());
  18363. }
  18364. TEST(NoProxyTest, CaseInsensitiveHostname) {
  18365. ProxyAndTargetServers s;
  18366. auto cli = make_client("Example.COM", s);
  18367. cli->set_no_proxy({"EXAMPLE.com"});
  18368. auto res = cli->Get("/");
  18369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18370. EXPECT_EQ(0, s.proxy_hits());
  18371. EXPECT_EQ(1, s.target_hits());
  18372. }
  18373. TEST(NoProxyTest, TrailingDotIsNormalized) {
  18374. ProxyAndTargetServers s;
  18375. auto cli = make_client("example.com.", s);
  18376. cli->set_no_proxy({"example.com"});
  18377. auto res = cli->Get("/");
  18378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18379. EXPECT_EQ(0, s.proxy_hits());
  18380. EXPECT_EQ(1, s.target_hits());
  18381. }
  18382. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  18383. // Trailing dots must be normalized on BOTH sides — host and entry.
  18384. // An implementation that only strips the host-side trailing dot would
  18385. // fail to match host "example.com" against entry "example.com." because
  18386. // a literal substring search would compare 11 chars against 12.
  18387. ProxyAndTargetServers s;
  18388. auto cli = make_client("example.com", s);
  18389. cli->set_no_proxy({"example.com."});
  18390. auto res = cli->Get("/");
  18391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18392. EXPECT_EQ(0, s.proxy_hits());
  18393. EXPECT_EQ(1, s.target_hits());
  18394. }
  18395. TEST(NoProxyTest, WildcardBypassesEverything) {
  18396. ProxyAndTargetServers s;
  18397. auto cli = make_client("anything.invalid.test", s);
  18398. cli->set_no_proxy({"*"});
  18399. auto res = cli->Get("/");
  18400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18401. EXPECT_EQ(0, s.proxy_hits());
  18402. EXPECT_EQ(1, s.target_hits());
  18403. }
  18404. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  18405. ProxyAndTargetServers s;
  18406. Client cli("127.0.0.1", s.target_port());
  18407. cli.set_proxy("127.0.0.1", s.proxy_port());
  18408. cli.set_no_proxy({"127.0.0.1"});
  18409. auto res = cli.Get("/");
  18410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18411. EXPECT_EQ(0, s.proxy_hits());
  18412. EXPECT_EQ(1, s.target_hits());
  18413. }
  18414. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  18415. ProxyAndTargetServers s;
  18416. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  18417. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  18418. cli.set_proxy("127.0.0.1", s.proxy_port());
  18419. cli.set_no_proxy({"::1"});
  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, BareIPv6LiteralMatchesIPv6Cidr) {
  18426. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  18427. // must still be recognized as IPv6 for CIDR matching. Implementations
  18428. // that detect IPv6 only when the host begins with '[' would parse the
  18429. // host as a hostname and miss the match.
  18430. ProxyAndTargetServers s;
  18431. Client cli("fe80::1", s.target_port());
  18432. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18433. cli.set_proxy("127.0.0.1", s.proxy_port());
  18434. cli.set_no_proxy({"fe80::/10"});
  18435. auto res = cli.Get("/");
  18436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18437. EXPECT_EQ(0, s.proxy_hits());
  18438. EXPECT_EQ(1, s.target_hits());
  18439. }
  18440. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  18441. ProxyAndTargetServers s;
  18442. Client cli("::1", s.target_port());
  18443. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  18444. cli.set_proxy("127.0.0.1", s.proxy_port());
  18445. cli.set_no_proxy({"[::1]"});
  18446. auto res = cli.Get("/");
  18447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18448. EXPECT_EQ(0, s.proxy_hits());
  18449. EXPECT_EQ(1, s.target_hits());
  18450. }
  18451. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  18452. ProxyAndTargetServers s;
  18453. Client cli("fe80::1", s.target_port());
  18454. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18455. cli.set_proxy("127.0.0.1", s.proxy_port());
  18456. cli.set_no_proxy({"[fe80::]/10"});
  18457. auto res = cli.Get("/");
  18458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18459. EXPECT_EQ(0, s.proxy_hits());
  18460. EXPECT_EQ(1, s.target_hits());
  18461. }
  18462. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  18463. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  18464. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  18465. // tricks via address-family conversion.
  18466. ProxyAndTargetServers s;
  18467. Client cli("::ffff:127.0.0.1", s.target_port());
  18468. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  18469. cli.set_proxy("127.0.0.1", s.proxy_port());
  18470. cli.set_no_proxy({"127.0.0.1"});
  18471. auto res = cli.Get("/");
  18472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18473. EXPECT_GE(s.proxy_hits(), 1);
  18474. EXPECT_EQ(0, s.target_hits());
  18475. }
  18476. TEST(NoProxyTest, IPv4CidrMatch) {
  18477. ProxyAndTargetServers s;
  18478. Client cli("127.0.0.1", s.target_port());
  18479. cli.set_proxy("127.0.0.1", s.proxy_port());
  18480. cli.set_no_proxy({"127.0.0.0/8"});
  18481. auto res = cli.Get("/");
  18482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18483. EXPECT_EQ(0, s.proxy_hits());
  18484. EXPECT_EQ(1, s.target_hits());
  18485. }
  18486. TEST(NoProxyTest, IPv4CidrNonMatch) {
  18487. ProxyAndTargetServers s;
  18488. Client cli("127.0.0.1", s.target_port());
  18489. cli.set_proxy("127.0.0.1", s.proxy_port());
  18490. cli.set_no_proxy({"10.0.0.0/8"});
  18491. auto res = cli.Get("/");
  18492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18493. EXPECT_GE(s.proxy_hits(), 1);
  18494. EXPECT_EQ(0, s.target_hits());
  18495. }
  18496. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  18497. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  18498. // IPv4 target matches.
  18499. ProxyAndTargetServers s;
  18500. Client cli("127.0.0.1", s.target_port());
  18501. cli.set_proxy("127.0.0.1", s.proxy_port());
  18502. cli.set_no_proxy({"0.0.0.0/0"});
  18503. auto res = cli.Get("/");
  18504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18505. EXPECT_EQ(0, s.proxy_hits());
  18506. EXPECT_EQ(1, s.target_hits());
  18507. }
  18508. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  18509. ProxyAndTargetServers s;
  18510. Client cli("127.0.0.1", s.target_port());
  18511. cli.set_proxy("127.0.0.1", s.proxy_port());
  18512. cli.set_no_proxy({"127.0.0.1"});
  18513. auto res = cli.Get("/");
  18514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18515. EXPECT_EQ(0, s.proxy_hits());
  18516. EXPECT_EQ(1, s.target_hits());
  18517. }
  18518. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  18519. ProxyAndTargetServers s;
  18520. Client cli("127.0.0.1", s.target_port());
  18521. cli.set_proxy("127.0.0.1", s.proxy_port());
  18522. cli.set_no_proxy({"127.0.0.0/33"});
  18523. auto res = cli.Get("/");
  18524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18525. EXPECT_GE(s.proxy_hits(), 1);
  18526. EXPECT_EQ(0, s.target_hits());
  18527. }
  18528. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  18529. // Empty prefix after the slash must be rejected, not silently treated as /32.
  18530. ProxyAndTargetServers s;
  18531. Client cli("127.0.0.1", s.target_port());
  18532. cli.set_proxy("127.0.0.1", s.proxy_port());
  18533. cli.set_no_proxy({"127.0.0.1/"});
  18534. auto res = cli.Get("/");
  18535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18536. EXPECT_GE(s.proxy_hits(), 1);
  18537. EXPECT_EQ(0, s.target_hits());
  18538. }
  18539. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  18540. ProxyAndTargetServers s;
  18541. auto cli = make_client("internal.corp", s);
  18542. cli->set_proxy_basic_auth("u", "p");
  18543. cli->set_no_proxy({"internal.corp"});
  18544. auto res = cli->Get("/");
  18545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18546. EXPECT_EQ(1, s.target_hits());
  18547. EXPECT_EQ(0, s.proxy_hits());
  18548. EXPECT_FALSE(s.last_had_proxy_authz())
  18549. << "Proxy-Authorization must not be sent direct to the target";
  18550. }
  18551. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  18552. ProxyAndTargetServers s;
  18553. auto cli = make_client("public.example", s);
  18554. cli->set_proxy_basic_auth("u", "p");
  18555. cli->set_no_proxy({"internal.corp"}); // does not match
  18556. auto res = cli->Get("/");
  18557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18558. EXPECT_GE(s.proxy_hits(), 1);
  18559. EXPECT_TRUE(s.last_had_proxy_authz());
  18560. }
  18561. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  18562. ProxyAndTargetServers s;
  18563. auto cli = make_client("anything.test", s);
  18564. auto res = cli->Get("/");
  18565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18566. EXPECT_GE(s.proxy_hits(), 1);
  18567. EXPECT_EQ(0, s.target_hits());
  18568. }
  18569. TEST(NoProxyTest, PortSpecificEntryRejected) {
  18570. ProxyAndTargetServers s;
  18571. auto cli = make_client("example.com", s);
  18572. cli->set_no_proxy({"example.com:8080"});
  18573. auto res = cli->Get("/");
  18574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18575. EXPECT_GE(s.proxy_hits(), 1);
  18576. EXPECT_EQ(0, s.target_hits());
  18577. }
  18578. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  18579. ProxyAndTargetServers s;
  18580. auto cli = make_client("anything.test", s);
  18581. cli->set_no_proxy({"", " ", "\t"});
  18582. auto res = cli->Get("/");
  18583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18584. EXPECT_GE(s.proxy_hits(), 1);
  18585. EXPECT_EQ(0, s.target_hits());
  18586. }
  18587. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  18588. // An entry with leading/trailing whitespace must still match — env-style
  18589. // values are commonly pasted with stray spaces and an implementation
  18590. // that feeds the raw token directly to inet_pton would fail to match
  18591. // valid CIDRs because of the spaces.
  18592. ProxyAndTargetServers s;
  18593. Client cli("127.0.0.1", s.target_port());
  18594. cli.set_proxy("127.0.0.1", s.proxy_port());
  18595. cli.set_no_proxy({" 127.0.0.0/8 "});
  18596. auto res = cli.Get("/");
  18597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18598. EXPECT_EQ(0, s.proxy_hits());
  18599. EXPECT_EQ(1, s.target_hits());
  18600. }
  18601. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  18602. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  18603. // go direct and must NOT carry Proxy-Authorization.
  18604. std::atomic<int> proxy_hits{0};
  18605. std::atomic<int> target_hits{0};
  18606. std::atomic<bool> target_saw_authz{false};
  18607. no_proxy_test::ScopedServer proxy_mock, target;
  18608. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18609. proxy_hits++;
  18610. res.status = 302;
  18611. res.set_header("Location", "http://127.0.0.1:" +
  18612. std::to_string(target.port()) + "/landed");
  18613. });
  18614. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18615. target_hits++;
  18616. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  18617. res.set_content("direct", "text/plain");
  18618. });
  18619. proxy_mock.listen();
  18620. target.listen();
  18621. Client cli("public.example", target.port());
  18622. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18623. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18624. cli.set_proxy_basic_auth("u", "p");
  18625. cli.set_no_proxy({"127.0.0.1"});
  18626. cli.set_follow_location(true);
  18627. auto res = cli.Get("/redir");
  18628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18629. EXPECT_GE(proxy_hits.load(), 1);
  18630. EXPECT_GE(target_hits.load(), 1);
  18631. EXPECT_FALSE(target_saw_authz.load());
  18632. }
  18633. #ifdef CPPHTTPLIB_SSL_ENABLED
  18634. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  18635. // Direct origin replying 407 must not trigger the digest retry; otherwise
  18636. // proxy creds would be sent to the (possibly hostile) origin.
  18637. std::atomic<int> target_hits{0};
  18638. std::atomic<bool> target_saw_proxy_authz{false};
  18639. no_proxy_test::ScopedServer target;
  18640. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18641. target_hits++;
  18642. if (req.has_header("Proxy-Authorization")) {
  18643. target_saw_proxy_authz = true;
  18644. }
  18645. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18646. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  18647. "nonce=\"abc\", algorithm=MD5");
  18648. });
  18649. target.listen();
  18650. // The proxy address is set to the target's port: the bypass MUST kick in;
  18651. // if it doesn't, the test still routes "via proxy" to the same server and
  18652. // the Proxy-Authorization assertion below catches the leak.
  18653. Client cli("evil.example", target.port());
  18654. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  18655. cli.set_proxy("127.0.0.1", target.port());
  18656. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18657. cli.set_no_proxy({"evil.example"});
  18658. auto res = cli.Get("/x");
  18659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18660. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18661. EXPECT_EQ(1, target_hits.load());
  18662. EXPECT_FALSE(target_saw_proxy_authz.load());
  18663. }
  18664. #endif
  18665. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  18666. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  18667. std::atomic<int> proxy_hits{0};
  18668. std::atomic<int> bypass_hits{0};
  18669. std::atomic<bool> proxy_saw_c_url{false};
  18670. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  18671. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  18672. proxy_hits++;
  18673. if (req.path.find("/start") != std::string::npos) {
  18674. res.status = 302;
  18675. res.set_header("Location", "http://127.0.0.1:" +
  18676. std::to_string(bypass_server.port()) +
  18677. "/middle");
  18678. return;
  18679. }
  18680. if (req.path.find("/end") != std::string::npos) {
  18681. proxy_saw_c_url = true;
  18682. res.set_content("c-via-proxy", "text/plain");
  18683. return;
  18684. }
  18685. res.set_content("unexpected", "text/plain");
  18686. });
  18687. // public.example's "advertised" port is arbitrary (the request never lands
  18688. // there — it goes through the proxy), but use a dynamic value to stay
  18689. // friendly with sharded parallel runs.
  18690. int public_port = bypass_server.port();
  18691. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  18692. bypass_hits++;
  18693. res.status = 302;
  18694. res.set_header("Location", "http://public.example:" +
  18695. std::to_string(public_port) + "/end");
  18696. });
  18697. proxy_mock.listen();
  18698. bypass_server.listen();
  18699. Client cli("public.example", public_port);
  18700. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18701. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18702. cli.set_no_proxy({"127.0.0.1"});
  18703. cli.set_follow_location(true);
  18704. auto res = cli.Get("/start");
  18705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18706. EXPECT_EQ(StatusCode::OK_200, res->status);
  18707. EXPECT_EQ("c-via-proxy", res->body);
  18708. EXPECT_GE(proxy_hits.load(), 2);
  18709. EXPECT_GE(bypass_hits.load(), 1);
  18710. EXPECT_TRUE(proxy_saw_c_url.load());
  18711. }
  18712. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  18713. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  18714. // request reconnects to the correct endpoint.
  18715. std::atomic<int> proxy_hits{0};
  18716. std::atomic<int> target_hits{0};
  18717. no_proxy_test::ScopedServer proxy_mock, target;
  18718. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18719. proxy_hits++;
  18720. res.set_content("via-proxy", "text/plain");
  18721. });
  18722. target.svr().Get(".*", [&](const Request &, Response &res) {
  18723. target_hits++;
  18724. res.set_content("direct", "text/plain");
  18725. });
  18726. proxy_mock.listen();
  18727. target.listen();
  18728. Client cli("public.example", target.port());
  18729. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18730. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18731. cli.set_keep_alive(true);
  18732. auto res1 = cli.Get("/a");
  18733. ASSERT_TRUE(res1);
  18734. EXPECT_EQ("via-proxy", res1->body);
  18735. EXPECT_EQ(1, proxy_hits.load());
  18736. EXPECT_EQ(0, target_hits.load());
  18737. cli.set_no_proxy({"public.example"});
  18738. auto res2 = cli.Get("/b");
  18739. ASSERT_TRUE(res2);
  18740. EXPECT_EQ("direct", res2->body);
  18741. EXPECT_EQ(1, proxy_hits.load());
  18742. EXPECT_EQ(1, target_hits.load());
  18743. }
  18744. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  18745. namespace proxy_tunnel_test {
  18746. // SSLServer counterpart to no_proxy_test::ScopedServer.
  18747. class ScopedSSLServer {
  18748. public:
  18749. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  18750. port_ = svr_.bind_to_any_port("127.0.0.1");
  18751. }
  18752. ~ScopedSSLServer() {
  18753. svr_.stop();
  18754. if (th_.joinable()) { th_.join(); }
  18755. }
  18756. SSLServer &svr() { return svr_; }
  18757. int port() const { return port_; }
  18758. void listen() {
  18759. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18760. svr_.wait_until_ready();
  18761. }
  18762. private:
  18763. SSLServer svr_;
  18764. std::thread th_;
  18765. int port_ = 0;
  18766. };
  18767. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  18768. class ScopedConnectProxy {
  18769. public:
  18770. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  18771. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  18772. if (listen_fd_ < 0) { return; }
  18773. int yes = 1;
  18774. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  18775. sockaddr_in a{};
  18776. a.sin_family = AF_INET;
  18777. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18778. a.sin_port = 0;
  18779. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  18780. return;
  18781. }
  18782. socklen_t alen = sizeof(a);
  18783. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  18784. 0) {
  18785. return;
  18786. }
  18787. port_ = ntohs(a.sin_port);
  18788. if (::listen(listen_fd_, 1) != 0) { return; }
  18789. th_ = std::thread([this] { run(); });
  18790. }
  18791. ~ScopedConnectProxy() {
  18792. stop_ = true;
  18793. if (listen_fd_ >= 0) {
  18794. ::shutdown(listen_fd_, SHUT_RDWR);
  18795. ::close(listen_fd_);
  18796. }
  18797. if (th_.joinable()) { th_.join(); }
  18798. }
  18799. int port() const { return port_; }
  18800. int connect_hits() const { return connect_hits_.load(); }
  18801. private:
  18802. void run() {
  18803. while (!stop_.load()) {
  18804. fd_set rfds;
  18805. FD_ZERO(&rfds);
  18806. FD_SET(listen_fd_, &rfds);
  18807. timeval tv{0, 100 * 1000};
  18808. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  18809. if (sel <= 0) { continue; }
  18810. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  18811. if (client_fd < 0) { continue; }
  18812. std::string req;
  18813. char buf[2048];
  18814. while (req.find("\r\n\r\n") == std::string::npos) {
  18815. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  18816. if (n <= 0) { break; }
  18817. req.append(buf, static_cast<size_t>(n));
  18818. }
  18819. if (req.compare(0, 7, "CONNECT") != 0) {
  18820. ::close(client_fd);
  18821. continue;
  18822. }
  18823. connect_hits_++;
  18824. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  18825. ::send(client_fd, ok, std::strlen(ok), 0);
  18826. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  18827. sockaddr_in o{};
  18828. o.sin_family = AF_INET;
  18829. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18830. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  18831. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  18832. 0) {
  18833. ::close(client_fd);
  18834. ::close(origin_fd);
  18835. continue;
  18836. }
  18837. auto forward = [](int from, int to) {
  18838. char b[8192];
  18839. for (;;) {
  18840. ssize_t n = ::recv(from, b, sizeof(b), 0);
  18841. if (n <= 0) { break; }
  18842. ssize_t off = 0;
  18843. while (off < n) {
  18844. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  18845. if (s <= 0) {
  18846. off = n;
  18847. break;
  18848. }
  18849. off += s;
  18850. }
  18851. }
  18852. ::shutdown(to, SHUT_WR);
  18853. };
  18854. std::thread t1([&] { forward(client_fd, origin_fd); });
  18855. std::thread t2([&] { forward(origin_fd, client_fd); });
  18856. t1.join();
  18857. t2.join();
  18858. ::close(client_fd);
  18859. ::close(origin_fd);
  18860. }
  18861. }
  18862. int forward_port_ = -1;
  18863. int listen_fd_ = -1;
  18864. int port_ = 0;
  18865. std::thread th_;
  18866. std::atomic<bool> stop_{false};
  18867. std::atomic<int> connect_hits_{0};
  18868. };
  18869. } // namespace proxy_tunnel_test
  18870. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  18871. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  18872. // retry; otherwise proxy creds would be sent to the origin.
  18873. std::atomic<int> origin_hits{0};
  18874. std::atomic<bool> origin_saw_proxy_authz{false};
  18875. proxy_tunnel_test::ScopedSSLServer origin;
  18876. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  18877. origin_hits++;
  18878. if (req.has_header("Proxy-Authorization")) {
  18879. origin_saw_proxy_authz = true;
  18880. }
  18881. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18882. res.set_header("Proxy-Authenticate",
  18883. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  18884. "algorithm=MD5");
  18885. });
  18886. origin.listen();
  18887. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  18888. ASSERT_NE(0, proxy.port());
  18889. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  18890. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  18891. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  18892. // and answer with its own status, making this test flaky.
  18893. SSLClient cli("127.0.0.1", origin.port());
  18894. cli.enable_server_certificate_verification(false);
  18895. cli.set_proxy("127.0.0.1", proxy.port());
  18896. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18897. auto res = cli.Get("/x");
  18898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18899. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18900. EXPECT_EQ(1, origin_hits.load());
  18901. EXPECT_FALSE(origin_saw_proxy_authz.load());
  18902. EXPECT_EQ(1, proxy.connect_hits());
  18903. }
  18904. #endif